4 #include <boost/asio.hpp>
6 #ifndef ASIO_STANDALONE
7 #define ASIO_STANDALONE
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"
34 namespace asio = boost::asio;
35 using error_code = boost::system::error_code;
37 using error_code = asio::error_code;
39 using tcp = asio::ip::tcp;
41 #ifdef CROW_ENABLE_DEBUG
42 static std::atomic<int> connectionCount;
46 template<
typename Adaptor,
typename Handler,
typename... Middlewares>
47 class Connection :
public std::enable_shared_from_this<Connection<Adaptor, Handler, Middlewares...>>
53 asio::io_service& io_service,
55 const std::string& server_name,
56 std::tuple<Middlewares...>* middlewares,
57 std::function<std::string()>& get_cached_date_str_f,
59 typename Adaptor::context* adaptor_ctx_,
60 std::atomic<unsigned int>& queue_length):
61 adaptor_(io_service, adaptor_ctx_),
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)
72 #ifdef CROW_ENABLE_DEBUG
74 CROW_LOG_DEBUG <<
"Connection (" <<
this <<
") allocated, total: " << connectionCount;
80 #ifdef CROW_ENABLE_DEBUG
82 CROW_LOG_DEBUG <<
"Connection (" <<
this <<
") freed, total: " << connectionCount;
87 decltype(std::declval<Adaptor>().raw_socket())&
socket()
89 return adaptor_.raw_socket();
94 auto self = this->shared_from_this();
95 adaptor_.start([
self](
const error_code& ec) {
98 self->start_deadline();
99 self->parser_.clear();
105 CROW_LOG_ERROR <<
"Could not start adaptor: " << ec.message();
112 routing_handle_result_ = handler_->handle_initial(req_, res);
114 if (!routing_handle_result_->rule_index)
117 need_to_call_after_handlers_ =
true;
125 if (req_.http_ver_major == 1 && req_.http_ver_minor == 1 &&
get_header_value(req_.headers,
"expect") ==
"100-continue")
127 continue_requested =
true;
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());
138 cancel_deadline_timer();
139 bool is_invalid_request =
false;
140 add_keep_alive_ =
false;
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();
153 if (req_.check_version(1, 1))
155 if (!req_.headers.count(
"host"))
157 is_invalid_request =
true;
163 if (req_.get_header_value(
"upgrade").substr(0, 2) ==
"h2")
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_));
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;
183 need_to_call_after_handlers_ =
false;
184 if (!is_invalid_request)
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();
192 detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
193 0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
197 res.complete_request_handler_ = [
self] {
198 self->complete_request();
200 need_to_call_after_handlers_ =
true;
201 handler_->handle(req_, res, routing_handle_result_);
203 res.set_header(
"connection",
"Keep-Alive");
219 CROW_LOG_INFO <<
"Response: " <<
this <<
' ' << req_.raw_url <<
' ' << res.code <<
' ' << close_connection_;
220 res.is_alive_helper_ =
nullptr;
222 if (need_to_call_after_handlers_)
224 need_to_call_after_handlers_ =
false;
227 detail::after_handlers_call_helper<
229 (
static_cast<int>(
sizeof...(Middlewares)) - 1),
231 decltype(*middlewares_)>({}, *middlewares_, ctx_, req_, res);
233 #ifdef CROW_ENABLE_COMPRESSION
234 if (!res.body.empty() && handler_->compression_used())
236 std::string accept_encoding = req_.get_header_value(
"Accept-Encoding");
237 if (!accept_encoding.empty() && res.compressed)
239 switch (handler_->compression_algorithm())
241 case compression::DEFLATE:
242 if (accept_encoding.find(
"deflate") != std::string::npos)
244 res.body = compression::compress_string(res.body, compression::algorithm::DEFLATE);
245 res.set_header(
"Content-Encoding",
"deflate");
248 case compression::GZIP:
249 if (accept_encoding.find(
"gzip") != std::string::npos)
251 res.body = compression::compress_string(res.body, compression::algorithm::GZIP);
252 res.set_header(
"Content-Encoding",
"gzip");
262 std::string location = res.get_header_value(
"Location");
263 if (!location.empty() && location.find(
"://", 0) == std::string::npos)
265 #ifdef CROW_ENABLE_SSL
266 if (handler_->ssl_used())
267 location.insert(0,
"https://" + req_.get_header_value(
"Host"));
270 location.insert(0,
"http://" + req_.get_header_value(
"Host"));
271 res.set_header(
"location", location);
276 if (res.is_static_type())
287 void prepare_buffers()
289 res.complete_request_handler_ =
nullptr;
290 res.is_alive_helper_ =
nullptr;
292 if (!adaptor_.is_open())
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"},
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"},
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"},
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"},
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"},
345 static const std::string seperator =
": ";
348 buffers_.reserve(4 * (res.headers.size() + 5) + 3);
350 if (!statusCodes.count(res.code))
352 CROW_LOG_WARNING <<
this <<
" status code "
353 <<
"(" << res.code <<
")"
354 <<
" not defined, returning 500 instead";
358 auto& status = statusCodes.find(res.code)->second;
359 buffers_.emplace_back(status.data(), status.size());
361 if (res.code >= 400 && res.body.empty())
362 res.body = statusCodes[res.code].substr(9);
364 for (
auto& kv : res.headers)
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());
372 if (!res.manual_length_header && !res.headers.count(
"content-length"))
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());
380 if (!res.headers.count(
"server"))
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());
387 if (!res.headers.count(
"date"))
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());
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());
402 buffers_.emplace_back(crlf.data(), crlf.size());
405 void do_write_static()
407 asio::write(adaptor_.socket(), buffers_);
409 if (res.file_info.statResult == 0)
411 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
412 std::vector<asio::const_buffer> buffers{1};
414 is.read(buf,
sizeof(buf));
415 while (is.gcount() > 0)
417 buffers[0] = asio::buffer(buf, is.gcount());
418 do_write_sync(buffers);
419 is.read(buf,
sizeof(buf));
422 if (close_connection_)
424 adaptor_.shutdown_readwrite();
426 CROW_LOG_DEBUG <<
this <<
" from write (static)";
435 void do_write_general()
437 if (res.body.length() < res_stream_threshold_)
439 res_body_copy_.swap(res.body);
440 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
444 if (need_to_start_read_after_complete_)
446 need_to_start_read_after_complete_ =
false;
453 asio::write(adaptor_.socket(), buffers_);
454 cancel_deadline_timer();
455 if (res.body.length() > 0)
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;)
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;
468 if (close_connection_)
470 adaptor_.shutdown_readwrite();
472 CROW_LOG_DEBUG <<
this <<
" from write (res_stream)";
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;
491 bool ret =
self->parser_.feed(self->buffer_.data(), bytes_transferred);
492 if (ret && self->adaptor_.is_open())
494 error_while_reading = false;
498 if (error_while_reading)
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)) <<
'\"';
506 else if (self->close_connection_)
508 self->cancel_deadline_timer();
509 self->parser_.done();
512 else if (!self->need_to_call_after_handlers_)
514 self->start_deadline();
520 self->need_to_start_read_after_complete_ =
true;
527 auto self = this->shared_from_this();
529 adaptor_.socket(), buffers_,
530 [
self](
const error_code& ec, std::size_t ) {
532 self->res_body_copy_.clear();
533 if (!self->continue_requested)
535 self->parser_.clear();
539 self->continue_requested = false;
544 if (self->close_connection_)
546 self->adaptor_.shutdown_write();
547 self->adaptor_.close();
548 CROW_LOG_DEBUG << self <<
" from write(1)";
553 CROW_LOG_DEBUG <<
self <<
" from write(2)";
558 inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
561 asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
568 CROW_LOG_ERROR << ec <<
" - happened while sending buffers";
569 CROW_LOG_DEBUG << this <<
" from write (sync)(2)";
575 void cancel_deadline_timer()
577 CROW_LOG_DEBUG <<
this <<
" timer cancelled: " << &task_timer_ <<
' ' << task_id_;
578 task_timer_.cancel(task_id_);
581 void start_deadline()
583 cancel_deadline_timer();
585 auto self = this->shared_from_this();
586 task_id_ = task_timer_.schedule([
self] {
587 if (!self->adaptor_.is_open())
591 self->adaptor_.shutdown_readwrite();
592 self->adaptor_.close();
594 CROW_LOG_DEBUG <<
this <<
" timer added: " << &task_timer_ <<
' ' << task_id_;
601 std::array<char, 4096> buffer_;
603 HTTPParser<Connection> parser_;
604 std::unique_ptr<routing_handle_result> routing_handle_result_;
608 bool close_connection_ =
false;
610 const std::string& server_name_;
611 std::vector<asio::const_buffer> buffers_;
613 std::string content_length_;
614 std::string date_str_;
615 std::string res_body_copy_;
617 detail::task_timer::identifier_type task_id_{};
619 bool continue_requested{};
620 bool need_to_call_after_handlers_{};
621 bool need_to_start_read_after_complete_{};
622 bool add_keep_alive_{};
624 std::tuple<Middlewares...>* middlewares_;
625 detail::context<Middlewares...> ctx_;
627 std::function<std::string()>& get_cached_date_str;
628 detail::task_timer& task_timer_;
630 size_t res_stream_threshold_;
632 std::atomic<unsigned int>& queue_length_;
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
Definition: middleware.h:204
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