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 queue_length_++;
73#ifdef CROW_ENABLE_DEBUG
74 connectionCount++;
75 CROW_LOG_DEBUG << "Connection (" << this << ") allocated, total: " << connectionCount;
76#endif
77 }
78
80 {
81 queue_length_--;
82#ifdef CROW_ENABLE_DEBUG
83 connectionCount--;
84 CROW_LOG_DEBUG << "Connection (" << this << ") freed, total: " << connectionCount;
85#endif
86 }
87
88 /// The TCP socket on top of which the connection is established.
89 decltype(std::declval<Adaptor>().raw_socket())& socket()
90 {
91 return adaptor_.raw_socket();
92 }
93
94 void start()
95 {
96 auto self = this->shared_from_this();
97 adaptor_.start([self](const error_code& ec) {
98 if (!ec)
99 {
100 self->start_deadline();
101 self->parser_.clear();
102
103 self->do_read();
104 }
105 else
106 {
107 CROW_LOG_ERROR << "Could not start adaptor: " << ec.message();
108 }
109 });
110 }
111
112 void handle_url()
113 {
114 // A new request begins here (on_url may fire more than once for a URL split across reads).
115 // Reset what the previous request on this keep-alive connection left behind before anything
116 // can complete this one: a request completed early here or in handle_header() runs the after
117 // handlers on ctx_. The response flags are reset here rather than in response::clear(), which
118 // the 100-continue write in handle_header() calls in the middle of a request.
119 ctx_ = detail::context<Middlewares...>();
120 req_.middleware_context = static_cast<void*>(&ctx_);
121 req_.middleware_container = static_cast<void*>(middlewares_);
122 add_keep_alive_ = false;
123 res.skip_body = false;
124 res.manual_length_header = false;
125#ifdef CROW_ENABLE_COMPRESSION
126 res.compressed = true;
127#endif
128
129 routing_handle_result_ = handler_->handle_initial(req_, res);
130 // if no route is found for the request method, return the response without parsing or processing anything further.
131 if (!routing_handle_result_->rule_index && !routing_handle_result_->catch_all && (req_.method != HTTPMethod::Options || routing_handle_result_->method == HTTPMethod::InternalMethodCount))
132 {
133 parser_.done();
134 need_to_call_after_handlers_ = true;
136 }
137 }
138
139 void handle_header()
140 {
141 // HTTP 1.1 Expect: 100-continue
142 if (req_.http_ver_major == 1 && req_.http_ver_minor == 1 && get_header_value(req_.headers, "expect") == "100-continue")
143 {
144 continue_requested = true;
145 buffers_.clear();
146 static const std::string expect_100_continue = "HTTP/1.1 100 Continue\r\n\r\n";
147 buffers_.emplace_back(expect_100_continue.data(), expect_100_continue.size());
148 error_code ec = do_write_sync(buffers_);
149 if (ec)
150 {
151 CROW_LOG_ERROR << ec << " buffer write error happened while handling sending continuation buffer header";
152 }
153 }
154 if (!routing_handle_result_->rule_index && !routing_handle_result_->catch_all && req_.method == HTTPMethod::Options)
155 {
156 parser_.done();
157 need_to_call_after_handlers_ = true;
159 }
160 }
161
162 void handle()
163 {
164 // 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
165 cancel_deadline_timer();
166 bool is_invalid_request = false;
167 add_keep_alive_ = false;
168
169 req_.io_context = &adaptor_.get_io_context();
170 req_.remote_ip_address = adaptor_.address();
171 req_.remote_port = adaptor_.remote_port();
172 add_keep_alive_ = req_.keep_alive;
173 close_connection_ = req_.close_connection;
174
175 if (req_.check_version(1, 1)) // HTTP/1.1
176 {
177 if (!req_.headers.count("host"))
178 {
179 is_invalid_request = true;
180 res = response(400);
181 }
182 else if (req_.upgrade && req_.method != HTTPMethod::Options)
183 {
184 // h2 or h2c headers
185 if (req_.get_header_value("upgrade").find("h2")==0)
186 {
187 // TODO(ipkn): HTTP/2
188 // currently, ignore upgrade header
189 }
190 else
191 {
192
193 detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
194 0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
195 close_connection_ = true;
196 add_keep_alive_ = false;
197 if (res.is_completed())
198 {
199 CROW_LOG_INFO << "Request completed before websocket upgrade: " << req_.remote_ip_address << ":" << req_.remote_port << " " << this << " HTTP/" << (char)(req_.http_ver_major + '0') << "." << (char)(req_.http_ver_minor + '0') << ' ' << method_name(req_.method) << " " << req_.url;
201
202 }
203 else
204 {
205 // the global before_handle ran for this request, so its after_handle runs too
206 need_to_call_after_handlers_ = true;
207 handler_->handle_upgrade(req_, res, std::move(adaptor_));
208 if (res.is_completed() && adaptor_.is_open())
209 {
210 // the router answered the request itself (404, 405, redirect, exception): send it
212 }
213 else
214 {
215 // the connection now belongs to the websocket (even if it threw after taking
216 // it), no response is sent from here
217 call_after_handlers();
218 }
219 }
220 return;
221 }
222 }
223 }
224
225 CROW_LOG_INFO << "Request: " << req_.remote_ip_address << ":" << req_.remote_port << " " << this << " HTTP/" << (char)(req_.http_ver_major + '0') << "." << (char)(req_.http_ver_minor + '0') << ' ' << method_name(req_.method) << " " << req_.url;
226
227
228 need_to_call_after_handlers_ = false;
229 if (!is_invalid_request)
230 {
231 res.complete_request_handler_ = nullptr;
232 auto self = this->shared_from_this();
233 res.is_alive_helper_ = [self]() -> bool {
234 return self->adaptor_.is_open();
235 };
236
237 detail::middleware_call_helper<detail::middleware_call_criteria_only_global,
238 0, decltype(ctx_), decltype(*middlewares_)>({}, *middlewares_, req_, res, ctx_);
239
240 if (!res.completed_)
241 {
242 res.complete_request_handler_ = [self] {
243 self->complete_request();
244 };
245 need_to_call_after_handlers_ = true;
246 handler_->handle(req_, res, routing_handle_result_);
247 }
248 else
249 {
251 }
252 }
253 else
254 {
256 }
257 }
258
259 /// Call the after handle middleware and send the write the response to the connection.
261 {
262 CROW_LOG_INFO << "Response: " << this << ' ' << req_.raw_url << ' ' << res.code << ' ' << close_connection_;
263 res.is_alive_helper_ = nullptr;
264
265 call_after_handlers();
266#ifdef CROW_ENABLE_COMPRESSION
267 if (!res.body.empty() && handler_->compression_used())
268 {
269 std::string accept_encoding = req_.get_header_value("Accept-Encoding");
270 if (!accept_encoding.empty() && res.compressed)
271 {
272 switch (handler_->compression_algorithm())
273 {
274 case compression::DEFLATE:
275 if (accept_encoding.find("deflate") != std::string::npos)
276 {
277 res.body = compression::compress_string(res.body, compression::algorithm::DEFLATE);
278 res.set_header("Content-Encoding", "deflate");
279 }
280 break;
281 case compression::GZIP:
282 if (accept_encoding.find("gzip") != std::string::npos)
283 {
284 res.body = compression::compress_string(res.body, compression::algorithm::GZIP);
285 res.set_header("Content-Encoding", "gzip");
286 }
287 break;
288 default:
289 break;
290 }
291 }
292 }
293#endif
294
295 prepare_buffers();
296
297 if (res.is_static_type())
298 {
299 do_write_static();
300 }
301 else
302 {
303 do_write_general();
304 }
305 }
306
307 private:
308 /// Call the after handle of the global middlewares, once per request.
309 void call_after_handlers()
310 {
311 if (need_to_call_after_handlers_)
312 {
313 need_to_call_after_handlers_ = false;
314
315 // call all after_handler of middlewares
316 detail::after_handlers_call_helper<
318 (static_cast<int>(sizeof...(Middlewares)) - 1),
319 decltype(ctx_),
320 decltype(*middlewares_)>({}, *middlewares_, ctx_, req_, res);
321 }
322 }
323
324 void prepare_buffers()
325 {
326 res.complete_request_handler_ = nullptr;
327 res.is_alive_helper_ = nullptr;
328
329 if (!adaptor_.is_open())
330 {
331 //CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading << ' ' << is_writing;
332 //delete this;
333 return;
334 }
335 res.write_header_into_buffer(buffers_, content_length_, add_keep_alive_, server_name_);
336 }
337
338 void do_write_static()
339 {
340 asio::write(adaptor_.socket(), buffers_);
341
342 // responses to HEAD requests carry no message body (RFC 9112 6.3)
343 if (res.file_info.statResult == 0 && !res.skip_body)
344 {
345 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
346 std::vector<asio::const_buffer> buffers{1};
347 char buf[16384];
348 is.read(buf, sizeof(buf));
349 while (is.gcount() > 0)
350 {
351 buffers[0] = asio::buffer(buf, is.gcount());
352 error_code ec = do_write_sync(buffers);
353 if (ec) {
354 CROW_LOG_ERROR << ec << " - buffer write error happened while sending content of file "
355 << res.file_info.path << ". Writing stopped premature.";
356 break;
357 }
358 is.read(buf, sizeof(buf));
359 }
360 }
361 if (close_connection_)
362 {
363 adaptor_.shutdown_readwrite();
364 adaptor_.close();
365 CROW_LOG_DEBUG << this << " from write (static)";
366 }
367
368 res.end();
369 res.clear();
370 buffers_.clear();
371 parser_.clear();
372 }
373
374 void do_write_general()
375 {
376 error_code ec;
377 if (res.body.length() < res_stream_threshold_)
378 {
379 res_body_copy_.swap(res.body);
380 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
381
382 ec = do_write_sync(buffers_);
383 if (ec) {
384 CROW_LOG_ERROR << ec << " - buffer write error happened while sending response. Writing stopped premature.";
385 }
386 if (need_to_start_read_after_complete_)
387 {
388 need_to_start_read_after_complete_ = false;
389 start_deadline();
390 do_read();
391 }
392 }
393 else
394 {
395 asio::write(adaptor_.socket(), buffers_,ec); // Write the response start / headers
396 if (ec) {
397 CROW_LOG_ERROR << ec << "- buffer write error happened while sending response start / headers. Writing stopped premature.";
398 }
399 cancel_deadline_timer();
400 if (res.body.length() > 0)
401 {
402 std::vector<asio::const_buffer> buffers{1};
403 const uint8_t* data = reinterpret_cast<const uint8_t*>(res.body.data());
404 size_t length = res.body.length();
405 for (size_t transferred = 0; transferred < length;)
406 {
407 size_t to_transfer = CROW_MIN(16384UL, length - transferred);
408 buffers[0] = asio::const_buffer(data + transferred, to_transfer);
409 ec = do_write_sync(buffers);
410 if (ec) {
411 CROW_LOG_ERROR << ec << " - " << transferred << " - buffer write error happened while sending response. Writing stopped premature.";
412 break;
413 }
414 transferred += to_transfer;
415 }
416 }
417 if (close_connection_)
418 {
419 adaptor_.shutdown_readwrite();
420 adaptor_.close();
421 CROW_LOG_DEBUG << this << " from write (res_stream)";
422 }
423
424 res.end();
425 res.clear();
426 buffers_.clear();
427 parser_.clear();
428 }
429 }
430
431 void do_read()
432 {
433 auto self = this->shared_from_this();
434 adaptor_.socket().async_read_some(
435 asio::buffer(buffer_),
436 [self](const error_code& ec, std::size_t bytes_transferred) {
437 bool error_while_reading = true;
438 if (!ec)
439 {
440 bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
441 if (ret && self->adaptor_.is_open())
442 {
443 error_while_reading = false;
444 }
445 }
446
447 if (error_while_reading)
448 {
449 self->cancel_deadline_timer();
450 self->parser_.done();
451 self->adaptor_.shutdown_read();
452 self->adaptor_.close();
453 CROW_LOG_DEBUG << self << " from read(1) with description: \"" << http_errno_description(static_cast<http_errno>(self->parser_.http_errno)) << '\"';
454 }
455 else if (self->close_connection_)
456 {
457 self->cancel_deadline_timer();
458 self->parser_.done();
459 // adaptor will close after write
460 }
461 else if (!self->need_to_call_after_handlers_)
462 {
463 self->start_deadline();
464 self->do_read();
465 }
466 else
467 {
468 // res will be completed later by user
469 self->need_to_start_read_after_complete_ = true;
470 }
471 });
472 }
473
474 void do_write()
475 {
476 auto self = this->shared_from_this();
477 asio::async_write(
478 adaptor_.socket(), buffers_,
479 [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
480 self->res.clear();
481 self->res_body_copy_.clear();
482 if (!self->continue_requested)
483 {
484 self->parser_.clear();
485 }
486 else
487 {
488 self->continue_requested = false;
489 }
490
491 if (!ec)
492 {
493 if (self->close_connection_)
494 {
495 self->adaptor_.shutdown_write();
496 self->adaptor_.close();
497 CROW_LOG_DEBUG << self << " from write(1)";
498 }
499 }
500 else
501 {
502 CROW_LOG_DEBUG << self << " from write(2)";
503 }
504 });
505 }
506
507 inline error_code do_write_sync(std::vector<asio::const_buffer>& buffers)
508 {
509 error_code ec;
510 asio::write(adaptor_.socket(), buffers, ec);
511 if (ec)
512 {
513 // CROW_LOG_ERROR << ec << " - happened while sending buffers";
514 CROW_LOG_DEBUG << this << " from write (sync)(2)";
515 }
516
517 this->res.clear();
518 this->res_body_copy_.clear();
519 if (this->continue_requested)
520 {
521 this->continue_requested = false;
522 }
523 else
524 {
525 this->parser_.clear();
526 }
527
528 return ec;
529 }
530
531 void cancel_deadline_timer()
532 {
533 CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
534 task_timer_.cancel(task_id_);
535 }
536
537 void start_deadline(/*int timeout = 5*/)
538 {
539 cancel_deadline_timer();
540
541 auto self = this->shared_from_this();
542 task_id_ = task_timer_.schedule([self] {
543 if (!self->adaptor_.is_open())
544 {
545 return;
546 }
547 self->adaptor_.shutdown_readwrite();
548 self->adaptor_.close();
549 });
550 CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
551 }
552
553 private:
554 Adaptor adaptor_;
555 Handler* handler_;
556
557 std::array<char, 4096> buffer_;
558
559 HTTPParser<Connection> parser_;
560 std::unique_ptr<routing_handle_result> routing_handle_result_;
561 request& req_;
562 response res;
563
564 bool close_connection_ = false;
565
566 const std::string& server_name_;
567 std::vector<asio::const_buffer> buffers_;
568
569 std::string content_length_;
570 std::string date_str_;
571 std::string res_body_copy_;
572
573 detail::task_timer::identifier_type task_id_{};
574
575 bool continue_requested{};
576 bool need_to_call_after_handlers_{};
577 bool need_to_start_read_after_complete_{};
578 bool add_keep_alive_{};
579
580 std::tuple<Middlewares...>* middlewares_;
581 detail::context<Middlewares...> ctx_;
582
583 std::function<std::string()>& get_cached_date_str;
584 detail::task_timer& task_timer_;
585
586 size_t res_stream_threshold_;
587
588 std::atomic<unsigned int>& queue_length_;
589 };
590
591} // 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:89
void complete_request()
Call the after handle middleware and send the write the response to the connection.
Definition http_connection.h:260
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 ci_map &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:33
bool close_connection
Whether or not the server should shut down the TCP connection once a response is sent.
Definition http_request.h:58
bool keep_alive
Whether or not the server should send a connection: Keep-Alive header to the client.
Definition http_request.h:57
std::string remote_ip_address
The IP address from which the request was sent.
Definition http_request.h:54
bool upgrade
Whether or noth the server should change the HTTP connection to a different connection.
Definition http_request.h:59
uint16_t remote_port
The TCP port from which the request was sent (0 for Unix domain sockets).
Definition http_request.h:55
HTTP response.
Definition http_response.h:40
bool skip_body
Whether this is a response to a HEAD request.
Definition http_response.h:56
bool manual_length_header
Whether Crow should automatically add a "Content-Length" header.
Definition http_response.h:57
bool compressed
If compression is enabled and this is false, the individual response will not be compressed.
Definition http_response.h:54