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");
264 if (res.is_static_type())
275 void prepare_buffers()
277 res.complete_request_handler_ =
nullptr;
278 res.is_alive_helper_ =
nullptr;
280 if (!adaptor_.is_open())
288 static std::unordered_map<int, std::string> statusCodes = {
289 {status::CONTINUE,
"HTTP/1.1 100 Continue\r\n"},
290 {status::SWITCHING_PROTOCOLS,
"HTTP/1.1 101 Switching Protocols\r\n"},
292 {status::OK,
"HTTP/1.1 200 OK\r\n"},
293 {status::CREATED,
"HTTP/1.1 201 Created\r\n"},
294 {status::ACCEPTED,
"HTTP/1.1 202 Accepted\r\n"},
295 {status::NON_AUTHORITATIVE_INFORMATION,
"HTTP/1.1 203 Non-Authoritative Information\r\n"},
296 {status::NO_CONTENT,
"HTTP/1.1 204 No Content\r\n"},
297 {status::RESET_CONTENT,
"HTTP/1.1 205 Reset Content\r\n"},
298 {status::PARTIAL_CONTENT,
"HTTP/1.1 206 Partial Content\r\n"},
300 {status::MULTIPLE_CHOICES,
"HTTP/1.1 300 Multiple Choices\r\n"},
301 {status::MOVED_PERMANENTLY,
"HTTP/1.1 301 Moved Permanently\r\n"},
302 {status::FOUND,
"HTTP/1.1 302 Found\r\n"},
303 {status::SEE_OTHER,
"HTTP/1.1 303 See Other\r\n"},
304 {status::NOT_MODIFIED,
"HTTP/1.1 304 Not Modified\r\n"},
305 {status::TEMPORARY_REDIRECT,
"HTTP/1.1 307 Temporary Redirect\r\n"},
306 {status::PERMANENT_REDIRECT,
"HTTP/1.1 308 Permanent Redirect\r\n"},
308 {status::BAD_REQUEST,
"HTTP/1.1 400 Bad Request\r\n"},
309 {status::UNAUTHORIZED,
"HTTP/1.1 401 Unauthorized\r\n"},
310 {status::FORBIDDEN,
"HTTP/1.1 403 Forbidden\r\n"},
311 {status::NOT_FOUND,
"HTTP/1.1 404 Not Found\r\n"},
312 {status::METHOD_NOT_ALLOWED,
"HTTP/1.1 405 Method Not Allowed\r\n"},
313 {status::NOT_ACCEPTABLE,
"HTTP/1.1 406 Not Acceptable\r\n"},
314 {status::PROXY_AUTHENTICATION_REQUIRED,
"HTTP/1.1 407 Proxy Authentication Required\r\n"},
315 {status::CONFLICT,
"HTTP/1.1 409 Conflict\r\n"},
316 {status::GONE,
"HTTP/1.1 410 Gone\r\n"},
317 {status::PAYLOAD_TOO_LARGE,
"HTTP/1.1 413 Payload Too Large\r\n"},
318 {status::UNSUPPORTED_MEDIA_TYPE,
"HTTP/1.1 415 Unsupported Media Type\r\n"},
319 {status::RANGE_NOT_SATISFIABLE,
"HTTP/1.1 416 Range Not Satisfiable\r\n"},
320 {status::EXPECTATION_FAILED,
"HTTP/1.1 417 Expectation Failed\r\n"},
321 {status::PRECONDITION_REQUIRED,
"HTTP/1.1 428 Precondition Required\r\n"},
322 {status::TOO_MANY_REQUESTS,
"HTTP/1.1 429 Too Many Requests\r\n"},
323 {status::UNAVAILABLE_FOR_LEGAL_REASONS,
"HTTP/1.1 451 Unavailable For Legal Reasons\r\n"},
325 {status::INTERNAL_SERVER_ERROR,
"HTTP/1.1 500 Internal Server Error\r\n"},
326 {status::NOT_IMPLEMENTED,
"HTTP/1.1 501 Not Implemented\r\n"},
327 {status::BAD_GATEWAY,
"HTTP/1.1 502 Bad Gateway\r\n"},
328 {status::SERVICE_UNAVAILABLE,
"HTTP/1.1 503 Service Unavailable\r\n"},
329 {status::GATEWAY_TIMEOUT,
"HTTP/1.1 504 Gateway Timeout\r\n"},
330 {status::VARIANT_ALSO_NEGOTIATES,
"HTTP/1.1 506 Variant Also Negotiates\r\n"},
333 static const std::string seperator =
": ";
336 buffers_.reserve(4 * (res.headers.size() + 5) + 3);
338 if (!statusCodes.count(res.code))
340 CROW_LOG_WARNING <<
this <<
" status code "
341 <<
"(" << res.code <<
")"
342 <<
" not defined, returning 500 instead";
346 auto& status = statusCodes.find(res.code)->second;
347 buffers_.emplace_back(status.data(), status.size());
349 if (res.code >= 400 && res.body.empty())
350 res.body = statusCodes[res.code].substr(9);
352 for (
auto& kv : res.headers)
354 buffers_.emplace_back(kv.first.data(), kv.first.size());
355 buffers_.emplace_back(seperator.data(), seperator.size());
356 buffers_.emplace_back(kv.second.data(), kv.second.size());
357 buffers_.emplace_back(crlf.data(), crlf.size());
360 if (!res.manual_length_header && !res.headers.count(
"content-length"))
362 content_length_ = std::to_string(res.body.size());
363 static std::string content_length_tag =
"Content-Length: ";
364 buffers_.emplace_back(content_length_tag.data(), content_length_tag.size());
365 buffers_.emplace_back(content_length_.data(), content_length_.size());
366 buffers_.emplace_back(crlf.data(), crlf.size());
368 if (!res.headers.count(
"server"))
370 static std::string server_tag =
"Server: ";
371 buffers_.emplace_back(server_tag.data(), server_tag.size());
372 buffers_.emplace_back(server_name_.data(), server_name_.size());
373 buffers_.emplace_back(crlf.data(), crlf.size());
375 if (!res.headers.count(
"date"))
377 static std::string date_tag =
"Date: ";
378 date_str_ = get_cached_date_str();
379 buffers_.emplace_back(date_tag.data(), date_tag.size());
380 buffers_.emplace_back(date_str_.data(), date_str_.size());
381 buffers_.emplace_back(crlf.data(), crlf.size());
385 static std::string keep_alive_tag =
"Connection: Keep-Alive";
386 buffers_.emplace_back(keep_alive_tag.data(), keep_alive_tag.size());
387 buffers_.emplace_back(crlf.data(), crlf.size());
390 buffers_.emplace_back(crlf.data(), crlf.size());
393 void do_write_static()
395 asio::write(adaptor_.socket(), buffers_);
397 if (res.file_info.statResult == 0)
399 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
400 std::vector<asio::const_buffer> buffers{1};
402 is.read(buf,
sizeof(buf));
403 while (is.gcount() > 0)
405 buffers[0] = asio::buffer(buf, is.gcount());
406 do_write_sync(buffers);
407 is.read(buf,
sizeof(buf));
410 if (close_connection_)
412 adaptor_.shutdown_readwrite();
414 CROW_LOG_DEBUG <<
this <<
" from write (static)";
423 void do_write_general()
425 if (res.body.length() < res_stream_threshold_)
427 res_body_copy_.swap(res.body);
428 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
432 if (need_to_start_read_after_complete_)
434 need_to_start_read_after_complete_ =
false;
441 asio::write(adaptor_.socket(), buffers_);
442 cancel_deadline_timer();
443 if (res.body.length() > 0)
445 std::vector<asio::const_buffer> buffers{1};
446 const uint8_t* data =
reinterpret_cast<const uint8_t*
>(res.body.data());
447 size_t length = res.body.length();
448 for (
size_t transferred = 0; transferred < length;)
450 size_t to_transfer = CROW_MIN(16384UL, length - transferred);
451 buffers[0] = asio::const_buffer(data + transferred, to_transfer);
452 do_write_sync(buffers);
453 transferred += to_transfer;
456 if (close_connection_)
458 adaptor_.shutdown_readwrite();
460 CROW_LOG_DEBUG <<
this <<
" from write (res_stream)";
472 auto self = this->shared_from_this();
473 adaptor_.socket().async_read_some(
474 asio::buffer(buffer_),
475 [
self](
const error_code& ec, std::size_t bytes_transferred) {
476 bool error_while_reading =
true;
479 bool ret =
self->parser_.feed(self->buffer_.data(), bytes_transferred);
480 if (ret && self->adaptor_.is_open())
482 error_while_reading = false;
486 if (error_while_reading)
488 self->cancel_deadline_timer();
489 self->parser_.done();
490 self->adaptor_.shutdown_read();
491 self->adaptor_.close();
492 CROW_LOG_DEBUG <<
self <<
" from read(1) with description: \"" << http_errno_description(
static_cast<http_errno
>(self->parser_.http_errno)) <<
'\"';
494 else if (self->close_connection_)
496 self->cancel_deadline_timer();
497 self->parser_.done();
500 else if (!self->need_to_call_after_handlers_)
502 self->start_deadline();
508 self->need_to_start_read_after_complete_ =
true;
515 auto self = this->shared_from_this();
517 adaptor_.socket(), buffers_,
518 [
self](
const error_code& ec, std::size_t ) {
520 self->res_body_copy_.clear();
521 if (!self->continue_requested)
523 self->parser_.clear();
527 self->continue_requested = false;
532 if (self->close_connection_)
534 self->adaptor_.shutdown_write();
535 self->adaptor_.close();
536 CROW_LOG_DEBUG << self <<
" from write(1)";
541 CROW_LOG_DEBUG <<
self <<
" from write(2)";
546 inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
549 asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
556 CROW_LOG_ERROR << ec <<
" - happened while sending buffers";
557 CROW_LOG_DEBUG << this <<
" from write (sync)(2)";
563 void cancel_deadline_timer()
565 CROW_LOG_DEBUG <<
this <<
" timer cancelled: " << &task_timer_ <<
' ' << task_id_;
566 task_timer_.cancel(task_id_);
569 void start_deadline()
571 cancel_deadline_timer();
573 auto self = this->shared_from_this();
574 task_id_ = task_timer_.schedule([
self] {
575 if (!self->adaptor_.is_open())
579 self->adaptor_.shutdown_readwrite();
580 self->adaptor_.close();
582 CROW_LOG_DEBUG <<
this <<
" timer added: " << &task_timer_ <<
' ' << task_id_;
589 std::array<char, 4096> buffer_;
591 HTTPParser<Connection> parser_;
592 std::unique_ptr<routing_handle_result> routing_handle_result_;
596 bool close_connection_ =
false;
598 const std::string& server_name_;
599 std::vector<asio::const_buffer> buffers_;
601 std::string content_length_;
602 std::string date_str_;
603 std::string res_body_copy_;
605 detail::task_timer::identifier_type task_id_{};
607 bool continue_requested{};
608 bool need_to_call_after_handlers_{};
609 bool need_to_start_read_after_complete_{};
610 bool add_keep_alive_{};
612 std::tuple<Middlewares...>* middlewares_;
613 detail::context<Middlewares...> ctx_;
615 std::function<std::string()>& get_cached_date_str;
616 detail::task_timer& task_timer_;
618 size_t res_stream_threshold_;
620 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