Crow  1.1
A C++ microframework for the web
http_connection.h
1 #pragma once
2 
3 #ifdef CROW_USE_BOOST
4 #include <boost/asio.hpp>
5 #else
6 #ifndef ASIO_STANDALONE
7 #define ASIO_STANDALONE
8 #endif
9 #include <asio.hpp>
10 #endif
11 
12 #include <algorithm>
13 #include <atomic>
14 #include <chrono>
15 #include <memory>
16 #include <vector>
17 
18 #include "crow/http_parser_merged.h"
19 #include "crow/common.h"
20 #include "crow/compression.h"
21 #include "crow/http_response.h"
22 #include "crow/logging.h"
23 #include "crow/middleware.h"
24 #include "crow/middleware_context.h"
25 #include "crow/parser.h"
26 #include "crow/settings.h"
27 #include "crow/socket_adaptors.h"
28 #include "crow/task_timer.h"
29 #include "crow/utility.h"
30 
31 namespace crow
32 {
33 #ifdef CROW_USE_BOOST
34  namespace asio = boost::asio;
35  using error_code = boost::system::error_code;
36 #else
37  using error_code = asio::error_code;
38 #endif
39  using tcp = asio::ip::tcp;
40 
41 #ifdef CROW_ENABLE_DEBUG
42  static std::atomic<int> connectionCount;
43 #endif
44 
45  /// An HTTP connection.
46  template<typename Adaptor, typename Handler, typename... Middlewares>
47  class Connection : public std::enable_shared_from_this<Connection<Adaptor, Handler, Middlewares...>>
48  {
49  friend struct crow::response;
50 
51  public:
52  Connection(
53  asio::io_service& io_service,
54  Handler* handler,
55  const std::string& server_name,
56  std::tuple<Middlewares...>* middlewares,
57  std::function<std::string()>& get_cached_date_str_f,
58  detail::task_timer& task_timer,
59  typename Adaptor::context* adaptor_ctx_,
60  std::atomic<unsigned int>& queue_length):
61  adaptor_(io_service, adaptor_ctx_),
62  handler_(handler),
63  parser_(this),
64  req_(parser_.req),
65  server_name_(server_name),
66  middlewares_(middlewares),
67  get_cached_date_str(get_cached_date_str_f),
68  task_timer_(task_timer),
69  res_stream_threshold_(handler->stream_threshold()),
70  queue_length_(queue_length)
71  {
72 #ifdef CROW_ENABLE_DEBUG
73  connectionCount++;
74  CROW_LOG_DEBUG << "Connection (" << this << ") allocated, total: " << connectionCount;
75 #endif
76  }
77 
78  ~Connection()
79  {
80 #ifdef CROW_ENABLE_DEBUG
81  connectionCount--;
82  CROW_LOG_DEBUG << "Connection (" << this << ") freed, total: " << connectionCount;
83 #endif
84  }
85 
86  /// The TCP socket on top of which the connection is established.
87  decltype(std::declval<Adaptor>().raw_socket())& socket()
88  {
89  return adaptor_.raw_socket();
90  }
91 
92  void start()
93  {
94  auto self = this->shared_from_this();
95  adaptor_.start([self](const error_code& ec) {
96  if (!ec)
97  {
98  self->start_deadline();
99  self->parser_.clear();
100 
101  self->do_read();
102  }
103  else
104  {
105  CROW_LOG_ERROR << "Could not start adaptor: " << ec.message();
106  }
107  });
108  }
109 
110  void handle_url()
111  {
112  routing_handle_result_ = handler_->handle_initial(req_, res);
113  // if no route is found for the request method, return the response without parsing or processing anything further.
114  if (!routing_handle_result_->rule_index)
115  {
116  parser_.done();
117  need_to_call_after_handlers_ = true;
119  }
120  }
121 
122  void handle_header()
123  {
124  // HTTP 1.1 Expect: 100-continue
125  if (req_.http_ver_major == 1 && req_.http_ver_minor == 1 && get_header_value(req_.headers, "expect") == "100-continue")
126  {
127  continue_requested = true;
128  buffers_.clear();
129  static std::string expect_100_continue = "HTTP/1.1 100 Continue\r\n\r\n";
130  buffers_.emplace_back(expect_100_continue.data(), expect_100_continue.size());
131  do_write();
132  }
133  }
134 
135  void handle()
136  {
137  // TODO(EDev): cancel_deadline_timer should be looked into, it might be a good idea to add it to handle_url() and then restart the timer once everything passes
138  cancel_deadline_timer();
139  bool is_invalid_request = false;
140  add_keep_alive_ = false;
141 
142  // Create context
143  ctx_ = detail::context<Middlewares...>();
144  req_.middleware_context = static_cast<void*>(&ctx_);
145  req_.middleware_container = static_cast<void*>(middlewares_);
146  req_.io_service = &adaptor_.get_io_service();
147 
148  req_.remote_ip_address = adaptor_.remote_endpoint().address().to_string();
149 
150  add_keep_alive_ = req_.keep_alive;
151  close_connection_ = req_.close_connection;
152 
153  if (req_.check_version(1, 1)) // HTTP/1.1
154  {
155  if (!req_.headers.count("host"))
156  {
157  is_invalid_request = true;
158  res = response(400);
159  }
160  else if (req_.upgrade)
161  {
162  // h2 or h2c headers
163  if (req_.get_header_value("upgrade").substr(0, 2) == "h2")
164  {
165  // TODO(ipkn): HTTP/2
166  // currently, ignore upgrade header
167  }
168  else
169  {
170 
171  detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
172  0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
173  close_connection_ = true;
174  handler_->handle_upgrade(req_, res, std::move(adaptor_));
175  return;
176  }
177  }
178  }
179 
180  CROW_LOG_INFO << "Request: " << utility::lexical_cast<std::string>(adaptor_.remote_endpoint()) << " " << this << " HTTP/" << (char)(req_.http_ver_major + '0') << "." << (char)(req_.http_ver_minor + '0') << ' ' << method_name(req_.method) << " " << req_.url;
181 
182 
183  need_to_call_after_handlers_ = false;
184  if (!is_invalid_request)
185  {
186  res.complete_request_handler_ = nullptr;
187  auto self = this->shared_from_this();
188  res.is_alive_helper_ = [self]() -> bool {
189  return self->adaptor_.is_open();
190  };
191 
192  detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
193  0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
194 
195  if (!res.completed_)
196  {
197  res.complete_request_handler_ = [self] {
198  self->complete_request();
199  };
200  need_to_call_after_handlers_ = true;
201  handler_->handle(req_, res, routing_handle_result_);
202  if (add_keep_alive_)
203  res.set_header("connection", "Keep-Alive");
204  }
205  else
206  {
208  }
209  }
210  else
211  {
213  }
214  }
215 
216  /// Call the after handle middleware and send the write the response to the connection.
218  {
219  CROW_LOG_INFO << "Response: " << this << ' ' << req_.raw_url << ' ' << res.code << ' ' << close_connection_;
220  res.is_alive_helper_ = nullptr;
221 
222  if (need_to_call_after_handlers_)
223  {
224  need_to_call_after_handlers_ = false;
225 
226  // call all after_handler of middlewares
227  detail::after_handlers_call_helper<
229  (static_cast<int>(sizeof...(Middlewares)) - 1),
230  decltype(ctx_),
231  decltype(*middlewares_)>({}, *middlewares_, ctx_, req_, res);
232  }
233 #ifdef CROW_ENABLE_COMPRESSION
234  if (!res.body.empty() && handler_->compression_used())
235  {
236  std::string accept_encoding = req_.get_header_value("Accept-Encoding");
237  if (!accept_encoding.empty() && res.compressed)
238  {
239  switch (handler_->compression_algorithm())
240  {
241  case compression::DEFLATE:
242  if (accept_encoding.find("deflate") != std::string::npos)
243  {
244  res.body = compression::compress_string(res.body, compression::algorithm::DEFLATE);
245  res.set_header("Content-Encoding", "deflate");
246  }
247  break;
248  case compression::GZIP:
249  if (accept_encoding.find("gzip") != std::string::npos)
250  {
251  res.body = compression::compress_string(res.body, compression::algorithm::GZIP);
252  res.set_header("Content-Encoding", "gzip");
253  }
254  break;
255  default:
256  break;
257  }
258  }
259  }
260 #endif
261  //if there is a redirection with a partial URL, treat the URL as a route.
262  std::string location = res.get_header_value("Location");
263  if (!location.empty() && location.find("://", 0) == std::string::npos)
264  {
265 #ifdef CROW_ENABLE_SSL
266  if (handler_->ssl_used())
267  location.insert(0, "https://" + req_.get_header_value("Host"));
268  else
269 #endif
270  location.insert(0, "http://" + req_.get_header_value("Host"));
271  res.set_header("location", location);
272  }
273 
274  prepare_buffers();
275 
276  if (res.is_static_type())
277  {
278  do_write_static();
279  }
280  else
281  {
282  do_write_general();
283  }
284  }
285 
286  private:
287  void prepare_buffers()
288  {
289  res.complete_request_handler_ = nullptr;
290  res.is_alive_helper_ = nullptr;
291 
292  if (!adaptor_.is_open())
293  {
294  //CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading << ' ' << is_writing;
295  //delete this;
296  return;
297  }
298  // TODO(EDev): HTTP version in status codes should be dynamic
299  // Keep in sync with common.h/status
300  static std::unordered_map<int, std::string> statusCodes = {
301  {status::CONTINUE, "HTTP/1.1 100 Continue\r\n"},
302  {status::SWITCHING_PROTOCOLS, "HTTP/1.1 101 Switching Protocols\r\n"},
303 
304  {status::OK, "HTTP/1.1 200 OK\r\n"},
305  {status::CREATED, "HTTP/1.1 201 Created\r\n"},
306  {status::ACCEPTED, "HTTP/1.1 202 Accepted\r\n"},
307  {status::NON_AUTHORITATIVE_INFORMATION, "HTTP/1.1 203 Non-Authoritative Information\r\n"},
308  {status::NO_CONTENT, "HTTP/1.1 204 No Content\r\n"},
309  {status::RESET_CONTENT, "HTTP/1.1 205 Reset Content\r\n"},
310  {status::PARTIAL_CONTENT, "HTTP/1.1 206 Partial Content\r\n"},
311 
312  {status::MULTIPLE_CHOICES, "HTTP/1.1 300 Multiple Choices\r\n"},
313  {status::MOVED_PERMANENTLY, "HTTP/1.1 301 Moved Permanently\r\n"},
314  {status::FOUND, "HTTP/1.1 302 Found\r\n"},
315  {status::SEE_OTHER, "HTTP/1.1 303 See Other\r\n"},
316  {status::NOT_MODIFIED, "HTTP/1.1 304 Not Modified\r\n"},
317  {status::TEMPORARY_REDIRECT, "HTTP/1.1 307 Temporary Redirect\r\n"},
318  {status::PERMANENT_REDIRECT, "HTTP/1.1 308 Permanent Redirect\r\n"},
319 
320  {status::BAD_REQUEST, "HTTP/1.1 400 Bad Request\r\n"},
321  {status::UNAUTHORIZED, "HTTP/1.1 401 Unauthorized\r\n"},
322  {status::FORBIDDEN, "HTTP/1.1 403 Forbidden\r\n"},
323  {status::NOT_FOUND, "HTTP/1.1 404 Not Found\r\n"},
324  {status::METHOD_NOT_ALLOWED, "HTTP/1.1 405 Method Not Allowed\r\n"},
325  {status::NOT_ACCEPTABLE, "HTTP/1.1 406 Not Acceptable\r\n"},
326  {status::PROXY_AUTHENTICATION_REQUIRED, "HTTP/1.1 407 Proxy Authentication Required\r\n"},
327  {status::CONFLICT, "HTTP/1.1 409 Conflict\r\n"},
328  {status::GONE, "HTTP/1.1 410 Gone\r\n"},
329  {status::PAYLOAD_TOO_LARGE, "HTTP/1.1 413 Payload Too Large\r\n"},
330  {status::UNSUPPORTED_MEDIA_TYPE, "HTTP/1.1 415 Unsupported Media Type\r\n"},
331  {status::RANGE_NOT_SATISFIABLE, "HTTP/1.1 416 Range Not Satisfiable\r\n"},
332  {status::EXPECTATION_FAILED, "HTTP/1.1 417 Expectation Failed\r\n"},
333  {status::PRECONDITION_REQUIRED, "HTTP/1.1 428 Precondition Required\r\n"},
334  {status::TOO_MANY_REQUESTS, "HTTP/1.1 429 Too Many Requests\r\n"},
335  {status::UNAVAILABLE_FOR_LEGAL_REASONS, "HTTP/1.1 451 Unavailable For Legal Reasons\r\n"},
336 
337  {status::INTERNAL_SERVER_ERROR, "HTTP/1.1 500 Internal Server Error\r\n"},
338  {status::NOT_IMPLEMENTED, "HTTP/1.1 501 Not Implemented\r\n"},
339  {status::BAD_GATEWAY, "HTTP/1.1 502 Bad Gateway\r\n"},
340  {status::SERVICE_UNAVAILABLE, "HTTP/1.1 503 Service Unavailable\r\n"},
341  {status::GATEWAY_TIMEOUT, "HTTP/1.1 504 Gateway Timeout\r\n"},
342  {status::VARIANT_ALSO_NEGOTIATES, "HTTP/1.1 506 Variant Also Negotiates\r\n"},
343  };
344 
345  static const std::string seperator = ": ";
346 
347  buffers_.clear();
348  buffers_.reserve(4 * (res.headers.size() + 5) + 3);
349 
350  if (!statusCodes.count(res.code))
351  {
352  CROW_LOG_WARNING << this << " status code "
353  << "(" << res.code << ")"
354  << " not defined, returning 500 instead";
355  res.code = 500;
356  }
357 
358  auto& status = statusCodes.find(res.code)->second;
359  buffers_.emplace_back(status.data(), status.size());
360 
361  if (res.code >= 400 && res.body.empty())
362  res.body = statusCodes[res.code].substr(9);
363 
364  for (auto& kv : res.headers)
365  {
366  buffers_.emplace_back(kv.first.data(), kv.first.size());
367  buffers_.emplace_back(seperator.data(), seperator.size());
368  buffers_.emplace_back(kv.second.data(), kv.second.size());
369  buffers_.emplace_back(crlf.data(), crlf.size());
370  }
371 
372  if (!res.manual_length_header && !res.headers.count("content-length"))
373  {
374  content_length_ = std::to_string(res.body.size());
375  static std::string content_length_tag = "Content-Length: ";
376  buffers_.emplace_back(content_length_tag.data(), content_length_tag.size());
377  buffers_.emplace_back(content_length_.data(), content_length_.size());
378  buffers_.emplace_back(crlf.data(), crlf.size());
379  }
380  if (!res.headers.count("server"))
381  {
382  static std::string server_tag = "Server: ";
383  buffers_.emplace_back(server_tag.data(), server_tag.size());
384  buffers_.emplace_back(server_name_.data(), server_name_.size());
385  buffers_.emplace_back(crlf.data(), crlf.size());
386  }
387  if (!res.headers.count("date"))
388  {
389  static std::string date_tag = "Date: ";
390  date_str_ = get_cached_date_str();
391  buffers_.emplace_back(date_tag.data(), date_tag.size());
392  buffers_.emplace_back(date_str_.data(), date_str_.size());
393  buffers_.emplace_back(crlf.data(), crlf.size());
394  }
395  if (add_keep_alive_)
396  {
397  static std::string keep_alive_tag = "Connection: Keep-Alive";
398  buffers_.emplace_back(keep_alive_tag.data(), keep_alive_tag.size());
399  buffers_.emplace_back(crlf.data(), crlf.size());
400  }
401 
402  buffers_.emplace_back(crlf.data(), crlf.size());
403  }
404 
405  void do_write_static()
406  {
407  asio::write(adaptor_.socket(), buffers_);
408 
409  if (res.file_info.statResult == 0)
410  {
411  std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
412  std::vector<asio::const_buffer> buffers{1};
413  char buf[16384];
414  is.read(buf, sizeof(buf));
415  while (is.gcount() > 0)
416  {
417  buffers[0] = asio::buffer(buf, is.gcount());
418  do_write_sync(buffers);
419  is.read(buf, sizeof(buf));
420  }
421  }
422  if (close_connection_)
423  {
424  adaptor_.shutdown_readwrite();
425  adaptor_.close();
426  CROW_LOG_DEBUG << this << " from write (static)";
427  }
428 
429  res.end();
430  res.clear();
431  buffers_.clear();
432  parser_.clear();
433  }
434 
435  void do_write_general()
436  {
437  if (res.body.length() < res_stream_threshold_)
438  {
439  res_body_copy_.swap(res.body);
440  buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
441 
442  do_write();
443 
444  if (need_to_start_read_after_complete_)
445  {
446  need_to_start_read_after_complete_ = false;
447  start_deadline();
448  do_read();
449  }
450  }
451  else
452  {
453  asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
454  cancel_deadline_timer();
455  if (res.body.length() > 0)
456  {
457  std::vector<asio::const_buffer> buffers{1};
458  const uint8_t* data = reinterpret_cast<const uint8_t*>(res.body.data());
459  size_t length = res.body.length();
460  for (size_t transferred = 0; transferred < length;)
461  {
462  size_t to_transfer = CROW_MIN(16384UL, length - transferred);
463  buffers[0] = asio::const_buffer(data + transferred, to_transfer);
464  do_write_sync(buffers);
465  transferred += to_transfer;
466  }
467  }
468  if (close_connection_)
469  {
470  adaptor_.shutdown_readwrite();
471  adaptor_.close();
472  CROW_LOG_DEBUG << this << " from write (res_stream)";
473  }
474 
475  res.end();
476  res.clear();
477  buffers_.clear();
478  parser_.clear();
479  }
480  }
481 
482  void do_read()
483  {
484  auto self = this->shared_from_this();
485  adaptor_.socket().async_read_some(
486  asio::buffer(buffer_),
487  [self](const error_code& ec, std::size_t bytes_transferred) {
488  bool error_while_reading = true;
489  if (!ec)
490  {
491  bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
492  if (ret && self->adaptor_.is_open())
493  {
494  error_while_reading = false;
495  }
496  }
497 
498  if (error_while_reading)
499  {
500  self->cancel_deadline_timer();
501  self->parser_.done();
502  self->adaptor_.shutdown_read();
503  self->adaptor_.close();
504  CROW_LOG_DEBUG << self << " from read(1) with description: \"" << http_errno_description(static_cast<http_errno>(self->parser_.http_errno)) << '\"';
505  }
506  else if (self->close_connection_)
507  {
508  self->cancel_deadline_timer();
509  self->parser_.done();
510  // adaptor will close after write
511  }
512  else if (!self->need_to_call_after_handlers_)
513  {
514  self->start_deadline();
515  self->do_read();
516  }
517  else
518  {
519  // res will be completed later by user
520  self->need_to_start_read_after_complete_ = true;
521  }
522  });
523  }
524 
525  void do_write()
526  {
527  auto self = this->shared_from_this();
528  asio::async_write(
529  adaptor_.socket(), buffers_,
530  [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
531  self->res.clear();
532  self->res_body_copy_.clear();
533  if (!self->continue_requested)
534  {
535  self->parser_.clear();
536  }
537  else
538  {
539  self->continue_requested = false;
540  }
541 
542  if (!ec)
543  {
544  if (self->close_connection_)
545  {
546  self->adaptor_.shutdown_write();
547  self->adaptor_.close();
548  CROW_LOG_DEBUG << self << " from write(1)";
549  }
550  }
551  else
552  {
553  CROW_LOG_DEBUG << self << " from write(2)";
554  }
555  });
556  }
557 
558  inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
559  {
560 
561  asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
562  if (!ec)
563  {
564  return false;
565  }
566  else
567  {
568  CROW_LOG_ERROR << ec << " - happened while sending buffers";
569  CROW_LOG_DEBUG << this << " from write (sync)(2)";
570  return true;
571  }
572  });
573  }
574 
575  void cancel_deadline_timer()
576  {
577  CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
578  task_timer_.cancel(task_id_);
579  }
580 
581  void start_deadline(/*int timeout = 5*/)
582  {
583  cancel_deadline_timer();
584 
585  auto self = this->shared_from_this();
586  task_id_ = task_timer_.schedule([self] {
587  if (!self->adaptor_.is_open())
588  {
589  return;
590  }
591  self->adaptor_.shutdown_readwrite();
592  self->adaptor_.close();
593  });
594  CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
595  }
596 
597  private:
598  Adaptor adaptor_;
599  Handler* handler_;
600 
601  std::array<char, 4096> buffer_;
602 
603  HTTPParser<Connection> parser_;
604  std::unique_ptr<routing_handle_result> routing_handle_result_;
605  request& req_;
606  response res;
607 
608  bool close_connection_ = false;
609 
610  const std::string& server_name_;
611  std::vector<asio::const_buffer> buffers_;
612 
613  std::string content_length_;
614  std::string date_str_;
615  std::string res_body_copy_;
616 
617  detail::task_timer::identifier_type task_id_{};
618 
619  bool continue_requested{};
620  bool need_to_call_after_handlers_{};
621  bool need_to_start_read_after_complete_{};
622  bool add_keep_alive_{};
623 
624  std::tuple<Middlewares...>* middlewares_;
625  detail::context<Middlewares...> ctx_;
626 
627  std::function<std::string()>& get_cached_date_str;
628  detail::task_timer& task_timer_;
629 
630  size_t res_stream_threshold_;
631 
632  std::atomic<unsigned int>& queue_length_;
633  };
634 
635 } // namespace crow
An HTTP connection.
Definition: http_connection.h:48
void complete_request()
Call the after handle middleware and send the write the response to the connection.
Definition: http_connection.h:217
decltype(std::declval< Adaptor >().raw_socket()) & socket()
The TCP socket on top of which the connection is established.
Definition: http_connection.h:87
Definition: task_timer.h:36
The main namespace of the library. In this namespace is defined the most important classes and functi...
const std::string & get_header_value(const T &headers, const std::string &key)
Find and return the value associated with the key. (returns an empty string if nothing is found)
Definition: http_request.h:24
bool close_connection
Whether or not the server should shut down the TCP connection once a response is sent.
Definition: http_request.h:46
bool keep_alive
Whether or not the server should send a connection: Keep-Alive header to the client.
Definition: http_request.h:45
std::string url
The endpoint without any parameters.
Definition: http_request.h:39
std::string remote_ip_address
The IP address from which the request was sent.
Definition: http_request.h:43
bool upgrade
Whether or noth the server should change the HTTP connection to a different connection.
Definition: http_request.h:47
HTTP response.
Definition: http_response.h:34