Crow  1.1
A C++ microframework for the web
 
Loading...
Searching...
No Matches
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
31namespace 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:
53 asio::io_context& io_context,
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_context, 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
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_sync(buffers_);
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_context = &adaptor_.get_io_context();
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
262 prepare_buffers();
263
264 if (res.is_static_type())
265 {
266 do_write_static();
267 }
268 else
269 {
270 do_write_general();
271 }
272 }
273
274 private:
275 void prepare_buffers()
276 {
277 res.complete_request_handler_ = nullptr;
278 res.is_alive_helper_ = nullptr;
279
280 if (!adaptor_.is_open())
281 {
282 //CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading << ' ' << is_writing;
283 //delete this;
284 return;
285 }
286 // TODO(EDev): HTTP version in status codes should be dynamic
287 // Keep in sync with common.h/status
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"},
291
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"},
299
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"},
307
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"},
324
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"},
331 };
332
333 static const std::string seperator = ": ";
334
335 buffers_.clear();
336 buffers_.reserve(4 * (res.headers.size() + 5) + 3);
337
338 if (!statusCodes.count(res.code))
339 {
340 CROW_LOG_WARNING << this << " status code "
341 << "(" << res.code << ")"
342 << " not defined, returning 500 instead";
343 res.code = 500;
344 }
345
346 auto& status = statusCodes.find(res.code)->second;
347 buffers_.emplace_back(status.data(), status.size());
348
349 if (res.code >= 400 && res.body.empty())
350 res.body = statusCodes[res.code].substr(9);
351
352 for (auto& kv : res.headers)
353 {
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());
358 }
359
360 if (!res.manual_length_header && !res.headers.count("content-length"))
361 {
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());
367 }
368 if (!res.headers.count("server"))
369 {
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());
374 }
375 if (!res.headers.count("date"))
376 {
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());
382 }
383 if (add_keep_alive_)
384 {
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());
388 }
389
390 buffers_.emplace_back(crlf.data(), crlf.size());
391 }
392
393 void do_write_static()
394 {
395 asio::write(adaptor_.socket(), buffers_);
396
397 if (res.file_info.statResult == 0)
398 {
399 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
400 std::vector<asio::const_buffer> buffers{1};
401 char buf[16384];
402 is.read(buf, sizeof(buf));
403 while (is.gcount() > 0)
404 {
405 buffers[0] = asio::buffer(buf, is.gcount());
406 do_write_sync(buffers);
407 is.read(buf, sizeof(buf));
408 }
409 }
410 if (close_connection_)
411 {
412 adaptor_.shutdown_readwrite();
413 adaptor_.close();
414 CROW_LOG_DEBUG << this << " from write (static)";
415 }
416
417 res.end();
418 res.clear();
419 buffers_.clear();
420 parser_.clear();
421 }
422
423 void do_write_general()
424 {
425 if (res.body.length() < res_stream_threshold_)
426 {
427 res_body_copy_.swap(res.body);
428 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
429
430 do_write_sync(buffers_);
431
432 if (need_to_start_read_after_complete_)
433 {
434 need_to_start_read_after_complete_ = false;
435 start_deadline();
436 do_read();
437 }
438 }
439 else
440 {
441 asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
442 cancel_deadline_timer();
443 if (res.body.length() > 0)
444 {
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;)
449 {
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;
454 }
455 }
456 if (close_connection_)
457 {
458 adaptor_.shutdown_readwrite();
459 adaptor_.close();
460 CROW_LOG_DEBUG << this << " from write (res_stream)";
461 }
462
463 res.end();
464 res.clear();
465 buffers_.clear();
466 parser_.clear();
467 }
468 }
469
470 void do_read()
471 {
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;
477 if (!ec)
478 {
479 bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
480 if (ret && self->adaptor_.is_open())
481 {
482 error_while_reading = false;
483 }
484 }
485
486 if (error_while_reading)
487 {
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)) << '\"';
493 }
494 else if (self->close_connection_)
495 {
496 self->cancel_deadline_timer();
497 self->parser_.done();
498 // adaptor will close after write
499 }
500 else if (!self->need_to_call_after_handlers_)
501 {
502 self->start_deadline();
503 self->do_read();
504 }
505 else
506 {
507 // res will be completed later by user
508 self->need_to_start_read_after_complete_ = true;
509 }
510 });
511 }
512
513 void do_write()
514 {
515 auto self = this->shared_from_this();
516 asio::async_write(
517 adaptor_.socket(), buffers_,
518 [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
519 self->res.clear();
520 self->res_body_copy_.clear();
521 if (!self->continue_requested)
522 {
523 self->parser_.clear();
524 }
525 else
526 {
527 self->continue_requested = false;
528 }
529
530 if (!ec)
531 {
532 if (self->close_connection_)
533 {
534 self->adaptor_.shutdown_write();
535 self->adaptor_.close();
536 CROW_LOG_DEBUG << self << " from write(1)";
537 }
538 }
539 else
540 {
541 CROW_LOG_DEBUG << self << " from write(2)";
542 }
543 });
544 }
545
546 inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
547 {
548
549 asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
550 if (!ec)
551 {
552 return false;
553 }
554 else
555 {
556 CROW_LOG_ERROR << ec << " - happened while sending buffers";
557 CROW_LOG_DEBUG << this << " from write (sync)(2)";
558 return true;
559 }
560 });
561 }
562
563 void cancel_deadline_timer()
564 {
565 CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
566 task_timer_.cancel(task_id_);
567 }
568
569 void start_deadline(/*int timeout = 5*/)
570 {
571 cancel_deadline_timer();
572
573 auto self = this->shared_from_this();
574 task_id_ = task_timer_.schedule([self] {
575 if (!self->adaptor_.is_open())
576 {
577 return;
578 }
579 self->adaptor_.shutdown_readwrite();
580 self->adaptor_.close();
581 });
582 CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
583 }
584
585 private:
586 Adaptor adaptor_;
587 Handler* handler_;
588
589 std::array<char, 4096> buffer_;
590
591 HTTPParser<Connection> parser_;
592 std::unique_ptr<routing_handle_result> routing_handle_result_;
593 request& req_;
594 response res;
595
596 bool close_connection_ = false;
597
598 const std::string& server_name_;
599 std::vector<asio::const_buffer> buffers_;
600
601 std::string content_length_;
602 std::string date_str_;
603 std::string res_body_copy_;
604
605 detail::task_timer::identifier_type task_id_{};
606
607 bool continue_requested{};
608 bool need_to_call_after_handlers_{};
609 bool need_to_start_read_after_complete_{};
610 bool add_keep_alive_{};
611
612 std::tuple<Middlewares...>* middlewares_;
613 detail::context<Middlewares...> ctx_;
614
615 std::function<std::string()>& get_cached_date_str;
616 detail::task_timer& task_timer_;
617
618 size_t res_stream_threshold_;
619
620 std::atomic<unsigned int>& queue_length_;
621 };
622
623} // namespace crow
An HTTP connection.
Definition http_connection.h:48
decltype(std::declval< Adaptor >().raw_socket()) & socket()
The TCP socket on top of which the connection is established.
Definition http_connection.h:87
void complete_request()
Call the after handle middleware and send the write the response to the connection.
Definition http_connection.h:217
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