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_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
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 auto self = this->shared_from_this();
198 res.complete_request_handler_ = [self] {
199 self->complete_request();
200 };
201 need_to_call_after_handlers_ = true;
202 handler_->handle(req_, res, routing_handle_result_);
203 if (add_keep_alive_)
204 res.set_header("connection", "Keep-Alive");
205 }
206 else
207 {
209 }
210 }
211 else
212 {
214 }
215 }
216
217 /// Call the after handle middleware and send the write the response to the connection.
219 {
220 CROW_LOG_INFO << "Response: " << this << ' ' << req_.raw_url << ' ' << res.code << ' ' << close_connection_;
221 res.is_alive_helper_ = nullptr;
222
223 if (need_to_call_after_handlers_)
224 {
225 need_to_call_after_handlers_ = false;
226
227 // call all after_handler of middlewares
228 detail::after_handlers_call_helper<
230 (static_cast<int>(sizeof...(Middlewares)) - 1),
231 decltype(ctx_),
232 decltype(*middlewares_)>({}, *middlewares_, ctx_, req_, res);
233 }
234#ifdef CROW_ENABLE_COMPRESSION
235 if (handler_->compression_used())
236 {
237 std::string accept_encoding = req_.get_header_value("Accept-Encoding");
238 if (!accept_encoding.empty() && res.compressed)
239 {
240 switch (handler_->compression_algorithm())
241 {
242 case compression::DEFLATE:
243 if (accept_encoding.find("deflate") != std::string::npos)
244 {
245 res.body = compression::compress_string(res.body, compression::algorithm::DEFLATE);
246 res.set_header("Content-Encoding", "deflate");
247 }
248 break;
249 case compression::GZIP:
250 if (accept_encoding.find("gzip") != std::string::npos)
251 {
252 res.body = compression::compress_string(res.body, compression::algorithm::GZIP);
253 res.set_header("Content-Encoding", "gzip");
254 }
255 break;
256 default:
257 break;
258 }
259 }
260 }
261#endif
262 //if there is a redirection with a partial URL, treat the URL as a route.
263 std::string location = res.get_header_value("Location");
264 if (!location.empty() && location.find("://", 0) == std::string::npos)
265 {
266#ifdef CROW_ENABLE_SSL
267 if (handler_->ssl_used())
268 location.insert(0, "https://" + req_.get_header_value("Host"));
269 else
270#endif
271 location.insert(0, "http://" + req_.get_header_value("Host"));
272 res.set_header("location", location);
273 }
274
275 prepare_buffers();
276
277 if (res.is_static_type())
278 {
279 do_write_static();
280 }
281 else
282 {
283 do_write_general();
284 }
285 }
286
287 private:
288 void prepare_buffers()
289 {
290 res.complete_request_handler_ = nullptr;
291 res.is_alive_helper_ = nullptr;
292
293 if (!adaptor_.is_open())
294 {
295 //CROW_LOG_DEBUG << this << " delete (socket is closed) " << is_reading << ' ' << is_writing;
296 //delete this;
297 return;
298 }
299 // TODO(EDev): HTTP version in status codes should be dynamic
300 // Keep in sync with common.h/status
301 static std::unordered_map<int, std::string> statusCodes = {
302 {status::CONTINUE, "HTTP/1.1 100 Continue\r\n"},
303 {status::SWITCHING_PROTOCOLS, "HTTP/1.1 101 Switching Protocols\r\n"},
304
305 {status::OK, "HTTP/1.1 200 OK\r\n"},
306 {status::CREATED, "HTTP/1.1 201 Created\r\n"},
307 {status::ACCEPTED, "HTTP/1.1 202 Accepted\r\n"},
308 {status::NON_AUTHORITATIVE_INFORMATION, "HTTP/1.1 203 Non-Authoritative Information\r\n"},
309 {status::NO_CONTENT, "HTTP/1.1 204 No Content\r\n"},
310 {status::RESET_CONTENT, "HTTP/1.1 205 Reset Content\r\n"},
311 {status::PARTIAL_CONTENT, "HTTP/1.1 206 Partial Content\r\n"},
312
313 {status::MULTIPLE_CHOICES, "HTTP/1.1 300 Multiple Choices\r\n"},
314 {status::MOVED_PERMANENTLY, "HTTP/1.1 301 Moved Permanently\r\n"},
315 {status::FOUND, "HTTP/1.1 302 Found\r\n"},
316 {status::SEE_OTHER, "HTTP/1.1 303 See Other\r\n"},
317 {status::NOT_MODIFIED, "HTTP/1.1 304 Not Modified\r\n"},
318 {status::TEMPORARY_REDIRECT, "HTTP/1.1 307 Temporary Redirect\r\n"},
319 {status::PERMANENT_REDIRECT, "HTTP/1.1 308 Permanent Redirect\r\n"},
320
321 {status::BAD_REQUEST, "HTTP/1.1 400 Bad Request\r\n"},
322 {status::UNAUTHORIZED, "HTTP/1.1 401 Unauthorized\r\n"},
323 {status::FORBIDDEN, "HTTP/1.1 403 Forbidden\r\n"},
324 {status::NOT_FOUND, "HTTP/1.1 404 Not Found\r\n"},
325 {status::METHOD_NOT_ALLOWED, "HTTP/1.1 405 Method Not Allowed\r\n"},
326 {status::NOT_ACCEPTABLE, "HTTP/1.1 406 Not Acceptable\r\n"},
327 {status::PROXY_AUTHENTICATION_REQUIRED, "HTTP/1.1 407 Proxy Authentication Required\r\n"},
328 {status::CONFLICT, "HTTP/1.1 409 Conflict\r\n"},
329 {status::GONE, "HTTP/1.1 410 Gone\r\n"},
330 {status::PAYLOAD_TOO_LARGE, "HTTP/1.1 413 Payload Too Large\r\n"},
331 {status::UNSUPPORTED_MEDIA_TYPE, "HTTP/1.1 415 Unsupported Media Type\r\n"},
332 {status::RANGE_NOT_SATISFIABLE, "HTTP/1.1 416 Range Not Satisfiable\r\n"},
333 {status::EXPECTATION_FAILED, "HTTP/1.1 417 Expectation Failed\r\n"},
334 {status::PRECONDITION_REQUIRED, "HTTP/1.1 428 Precondition Required\r\n"},
335 {status::TOO_MANY_REQUESTS, "HTTP/1.1 429 Too Many Requests\r\n"},
336 {status::UNAVAILABLE_FOR_LEGAL_REASONS, "HTTP/1.1 451 Unavailable For Legal Reasons\r\n"},
337
338 {status::INTERNAL_SERVER_ERROR, "HTTP/1.1 500 Internal Server Error\r\n"},
339 {status::NOT_IMPLEMENTED, "HTTP/1.1 501 Not Implemented\r\n"},
340 {status::BAD_GATEWAY, "HTTP/1.1 502 Bad Gateway\r\n"},
341 {status::SERVICE_UNAVAILABLE, "HTTP/1.1 503 Service Unavailable\r\n"},
342 {status::GATEWAY_TIMEOUT, "HTTP/1.1 504 Gateway Timeout\r\n"},
343 {status::VARIANT_ALSO_NEGOTIATES, "HTTP/1.1 506 Variant Also Negotiates\r\n"},
344 };
345
346 static const std::string seperator = ": ";
347
348 buffers_.clear();
349 buffers_.reserve(4 * (res.headers.size() + 5) + 3);
350
351 if (!statusCodes.count(res.code))
352 {
353 CROW_LOG_WARNING << this << " status code "
354 << "(" << res.code << ")"
355 << " not defined, returning 500 instead";
356 res.code = 500;
357 }
358
359 auto& status = statusCodes.find(res.code)->second;
360 buffers_.emplace_back(status.data(), status.size());
361
362 if (res.code >= 400 && res.body.empty())
363 res.body = statusCodes[res.code].substr(9);
364
365 for (auto& kv : res.headers)
366 {
367 buffers_.emplace_back(kv.first.data(), kv.first.size());
368 buffers_.emplace_back(seperator.data(), seperator.size());
369 buffers_.emplace_back(kv.second.data(), kv.second.size());
370 buffers_.emplace_back(crlf.data(), crlf.size());
371 }
372
373 if (!res.manual_length_header && !res.headers.count("content-length"))
374 {
375 content_length_ = std::to_string(res.body.size());
376 static std::string content_length_tag = "Content-Length: ";
377 buffers_.emplace_back(content_length_tag.data(), content_length_tag.size());
378 buffers_.emplace_back(content_length_.data(), content_length_.size());
379 buffers_.emplace_back(crlf.data(), crlf.size());
380 }
381 if (!res.headers.count("server"))
382 {
383 static std::string server_tag = "Server: ";
384 buffers_.emplace_back(server_tag.data(), server_tag.size());
385 buffers_.emplace_back(server_name_.data(), server_name_.size());
386 buffers_.emplace_back(crlf.data(), crlf.size());
387 }
388 if (!res.headers.count("date"))
389 {
390 static std::string date_tag = "Date: ";
391 date_str_ = get_cached_date_str();
392 buffers_.emplace_back(date_tag.data(), date_tag.size());
393 buffers_.emplace_back(date_str_.data(), date_str_.size());
394 buffers_.emplace_back(crlf.data(), crlf.size());
395 }
396 if (add_keep_alive_)
397 {
398 static std::string keep_alive_tag = "Connection: Keep-Alive";
399 buffers_.emplace_back(keep_alive_tag.data(), keep_alive_tag.size());
400 buffers_.emplace_back(crlf.data(), crlf.size());
401 }
402
403 buffers_.emplace_back(crlf.data(), crlf.size());
404 }
405
406 void do_write_static()
407 {
408 asio::write(adaptor_.socket(), buffers_);
409
410 if (res.file_info.statResult == 0)
411 {
412 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
413 std::vector<asio::const_buffer> buffers{1};
414 char buf[16384];
415 is.read(buf, sizeof(buf));
416 while (is.gcount() > 0)
417 {
418 buffers[0] = asio::buffer(buf, is.gcount());
419 do_write_sync(buffers);
420 is.read(buf, sizeof(buf));
421 }
422 }
423 if (close_connection_)
424 {
425 adaptor_.shutdown_readwrite();
426 adaptor_.close();
427 CROW_LOG_DEBUG << this << " from write (static)";
428 }
429
430 res.end();
431 res.clear();
432 buffers_.clear();
433 parser_.clear();
434 }
435
436 void do_write_general()
437 {
438 if (res.body.length() < res_stream_threshold_)
439 {
440 res_body_copy_.swap(res.body);
441 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
442
443 do_write();
444
445 if (need_to_start_read_after_complete_)
446 {
447 need_to_start_read_after_complete_ = false;
448 start_deadline();
449 do_read();
450 }
451 }
452 else
453 {
454 asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
455 cancel_deadline_timer();
456 if (res.body.length() > 0)
457 {
458 std::vector<asio::const_buffer> buffers{1};
459 const uint8_t *data = reinterpret_cast<const uint8_t*>(res.body.data());
460 size_t length = res.body.length();
461 for(size_t transferred = 0; transferred < length;)
462 {
463 size_t to_transfer = CROW_MIN(16384UL, length-transferred);
464 buffers[0] = asio::const_buffer(data+transferred, to_transfer);
465 do_write_sync(buffers);
466 transferred += to_transfer;
467 }
468 }
469 if (close_connection_)
470 {
471 adaptor_.shutdown_readwrite();
472 adaptor_.close();
473 CROW_LOG_DEBUG << this << " from write (res_stream)";
474 }
475
476 res.end();
477 res.clear();
478 buffers_.clear();
479 parser_.clear();
480 }
481 }
482
483 void do_read()
484 {
485 auto self = this->shared_from_this();
486 adaptor_.socket().async_read_some(
487 asio::buffer(buffer_),
488 [self](const error_code& ec, std::size_t bytes_transferred) {
489 bool error_while_reading = true;
490 if (!ec)
491 {
492 bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
493 if (ret && self->adaptor_.is_open())
494 {
495 error_while_reading = false;
496 }
497 }
498
499 if (error_while_reading)
500 {
501 self->cancel_deadline_timer();
502 self->parser_.done();
503 self->adaptor_.shutdown_read();
504 self->adaptor_.close();
505 CROW_LOG_DEBUG << self << " from read(1) with description: \"" << http_errno_description(static_cast<http_errno>(self->parser_.http_errno)) << '\"';
506 }
507 else if (self->close_connection_)
508 {
509 self->cancel_deadline_timer();
510 self->parser_.done();
511 // adaptor will close after write
512 }
513 else if (!self->need_to_call_after_handlers_)
514 {
515 self->start_deadline();
516 self->do_read();
517 }
518 else
519 {
520 // res will be completed later by user
521 self->need_to_start_read_after_complete_ = true;
522 }
523 });
524 }
525
526 void do_write()
527 {
528 auto self = this->shared_from_this();
529 asio::async_write(
530 adaptor_.socket(), buffers_,
531 [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
532 self->res.clear();
533 self->res_body_copy_.clear();
534 if (!self->continue_requested)
535 {
536 self->parser_.clear();
537 }
538 else
539 {
540 self->continue_requested = false;
541 }
542
543 if (!ec)
544 {
545 if (self->close_connection_)
546 {
547 self->adaptor_.shutdown_write();
548 self->adaptor_.close();
549 CROW_LOG_DEBUG << self << " from write(1)";
550 }
551 }
552 else
553 {
554 CROW_LOG_DEBUG << self << " from write(2)";
555 }
556 });
557 }
558
559 inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
560 {
561
562 asio::write(adaptor_.socket(), buffers, [&](error_code ec, std::size_t) {
563 if (!ec)
564 {
565 return false;
566 }
567 else
568 {
569 CROW_LOG_ERROR << ec << " - happened while sending buffers";
570 CROW_LOG_DEBUG << this << " from write (sync)(2)";
571 return true;
572 }
573 });
574 }
575
576 void cancel_deadline_timer()
577 {
578 CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
579 task_timer_.cancel(task_id_);
580 }
581
582 void start_deadline(/*int timeout = 5*/)
583 {
584 cancel_deadline_timer();
585
586 auto self = this->shared_from_this();
587 task_id_ = task_timer_.schedule([self] {
588 if (!self->adaptor_.is_open())
589 {
590 return;
591 }
592 self->adaptor_.shutdown_readwrite();
593 self->adaptor_.close();
594 });
595 CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
596 }
597
598 private:
599 Adaptor adaptor_;
600 Handler* handler_;
601
602 std::array<char, 4096> buffer_;
603
604 HTTPParser<Connection> parser_;
605 std::unique_ptr<routing_handle_result> routing_handle_result_;
606 request& req_;
607 response res;
608
609 bool close_connection_ = false;
610
611 const std::string& server_name_;
612 std::vector<asio::const_buffer> buffers_;
613
614 std::string content_length_;
615 std::string date_str_;
616 std::string res_body_copy_;
617
618 detail::task_timer::identifier_type task_id_{};
619
620 bool continue_requested{};
621 bool need_to_call_after_handlers_{};
622 bool need_to_start_read_after_complete_{};
623 bool add_keep_alive_{};
624
625 std::tuple<Middlewares...>* middlewares_;
626 detail::context<Middlewares...> ctx_;
627
628 std::function<std::string()>& get_cached_date_str;
629 detail::task_timer& task_timer_;
630
631 size_t res_stream_threshold_;
632
633 std::atomic<unsigned int>& queue_length_;
634 };
635
636} // 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:218
A class for scheduling functions to be called after a specific amount of ticks. A tick is equal to 1 ...
Definition task_timer.h:34
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