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 routing_handle_result_ = handler_->handle_initial(req_, res);
115 // if no route is found for the request method, return the response without parsing or processing anything further.
116 if (!routing_handle_result_->rule_index && !routing_handle_result_->catch_all)
117 {
118 parser_.done();
119 need_to_call_after_handlers_ = true;
121 }
122 }
123
124 void handle_header()
125 {
126 // HTTP 1.1 Expect: 100-continue
127 if (req_.http_ver_major == 1 && req_.http_ver_minor == 1 && get_header_value(req_.headers, "expect") == "100-continue")
128 {
129 continue_requested = true;
130 buffers_.clear();
131 static std::string expect_100_continue = "HTTP/1.1 100 Continue\r\n\r\n";
132 buffers_.emplace_back(expect_100_continue.data(), expect_100_continue.size());
133 do_write_sync(buffers_);
134 }
135 }
136
137 void handle()
138 {
139 // 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
140 cancel_deadline_timer();
141 bool is_invalid_request = false;
142 add_keep_alive_ = false;
143
144 // Create context
145 ctx_ = detail::context<Middlewares...>();
146 req_.middleware_context = static_cast<void*>(&ctx_);
147 req_.middleware_container = static_cast<void*>(middlewares_);
148 req_.io_context = &adaptor_.get_io_context();
149 req_.remote_ip_address = adaptor_.address();
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").find("h2")==0)
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 res.write_header_into_buffer(buffers_, content_length_, add_keep_alive_, server_name_);
287 }
288
289 void do_write_static()
290 {
291 asio::write(adaptor_.socket(), buffers_);
292
293 if (res.file_info.statResult == 0)
294 {
295 std::ifstream is(res.file_info.path.c_str(), std::ios::in | std::ios::binary);
296 std::vector<asio::const_buffer> buffers{1};
297 char buf[16384];
298 is.read(buf, sizeof(buf));
299 while (is.gcount() > 0)
300 {
301 buffers[0] = asio::buffer(buf, is.gcount());
302 do_write_sync(buffers);
303 is.read(buf, sizeof(buf));
304 }
305 }
306 if (close_connection_)
307 {
308 adaptor_.shutdown_readwrite();
309 adaptor_.close();
310 CROW_LOG_DEBUG << this << " from write (static)";
311 }
312
313 res.end();
314 res.clear();
315 buffers_.clear();
316 parser_.clear();
317 }
318
319 void do_write_general()
320 {
321 if (res.body.length() < res_stream_threshold_)
322 {
323 res_body_copy_.swap(res.body);
324 buffers_.emplace_back(res_body_copy_.data(), res_body_copy_.size());
325
326 do_write_sync(buffers_);
327
328 if (need_to_start_read_after_complete_)
329 {
330 need_to_start_read_after_complete_ = false;
331 start_deadline();
332 do_read();
333 }
334 }
335 else
336 {
337 asio::write(adaptor_.socket(), buffers_); // Write the response start / headers
338 cancel_deadline_timer();
339 if (res.body.length() > 0)
340 {
341 std::vector<asio::const_buffer> buffers{1};
342 const uint8_t* data = reinterpret_cast<const uint8_t*>(res.body.data());
343 size_t length = res.body.length();
344 for (size_t transferred = 0; transferred < length;)
345 {
346 size_t to_transfer = CROW_MIN(16384UL, length - transferred);
347 buffers[0] = asio::const_buffer(data + transferred, to_transfer);
348 do_write_sync(buffers);
349 transferred += to_transfer;
350 }
351 }
352 if (close_connection_)
353 {
354 adaptor_.shutdown_readwrite();
355 adaptor_.close();
356 CROW_LOG_DEBUG << this << " from write (res_stream)";
357 }
358
359 res.end();
360 res.clear();
361 buffers_.clear();
362 parser_.clear();
363 }
364 }
365
366 void do_read()
367 {
368 auto self = this->shared_from_this();
369 adaptor_.socket().async_read_some(
370 asio::buffer(buffer_),
371 [self](const error_code& ec, std::size_t bytes_transferred) {
372 bool error_while_reading = true;
373 if (!ec)
374 {
375 bool ret = self->parser_.feed(self->buffer_.data(), bytes_transferred);
376 if (ret && self->adaptor_.is_open())
377 {
378 error_while_reading = false;
379 }
380 }
381
382 if (error_while_reading)
383 {
384 self->cancel_deadline_timer();
385 self->parser_.done();
386 self->adaptor_.shutdown_read();
387 self->adaptor_.close();
388 CROW_LOG_DEBUG << self << " from read(1) with description: \"" << http_errno_description(static_cast<http_errno>(self->parser_.http_errno)) << '\"';
389 }
390 else if (self->close_connection_)
391 {
392 self->cancel_deadline_timer();
393 self->parser_.done();
394 // adaptor will close after write
395 }
396 else if (!self->need_to_call_after_handlers_)
397 {
398 self->start_deadline();
399 self->do_read();
400 }
401 else
402 {
403 // res will be completed later by user
404 self->need_to_start_read_after_complete_ = true;
405 }
406 });
407 }
408
409 void do_write()
410 {
411 auto self = this->shared_from_this();
412 asio::async_write(
413 adaptor_.socket(), buffers_,
414 [self](const error_code& ec, std::size_t /*bytes_transferred*/) {
415 self->res.clear();
416 self->res_body_copy_.clear();
417 if (!self->continue_requested)
418 {
419 self->parser_.clear();
420 }
421 else
422 {
423 self->continue_requested = false;
424 }
425
426 if (!ec)
427 {
428 if (self->close_connection_)
429 {
430 self->adaptor_.shutdown_write();
431 self->adaptor_.close();
432 CROW_LOG_DEBUG << self << " from write(1)";
433 }
434 }
435 else
436 {
437 CROW_LOG_DEBUG << self << " from write(2)";
438 }
439 });
440 }
441
442 inline void do_write_sync(std::vector<asio::const_buffer>& buffers)
443 {
444 error_code ec;
445 asio::write(adaptor_.socket(), buffers, ec);
446
447 this->res.clear();
448 this->res_body_copy_.clear();
449 if (this->continue_requested)
450 {
451 this->continue_requested = false;
452 }
453 else
454 {
455 this->parser_.clear();
456 }
457
458 if (ec)
459 {
460 CROW_LOG_ERROR << ec << " - happened while sending buffers";
461 CROW_LOG_DEBUG << this << " from write (sync)(2)";
462 }
463 }
464
465 void cancel_deadline_timer()
466 {
467 CROW_LOG_DEBUG << this << " timer cancelled: " << &task_timer_ << ' ' << task_id_;
468 task_timer_.cancel(task_id_);
469 }
470
471 void start_deadline(/*int timeout = 5*/)
472 {
473 cancel_deadline_timer();
474
475 auto self = this->shared_from_this();
476 task_id_ = task_timer_.schedule([self] {
477 if (!self->adaptor_.is_open())
478 {
479 return;
480 }
481 self->adaptor_.shutdown_readwrite();
482 self->adaptor_.close();
483 });
484 CROW_LOG_DEBUG << this << " timer added: " << &task_timer_ << ' ' << task_id_;
485 }
486
487 private:
488 Adaptor adaptor_;
489 Handler* handler_;
490
491 std::array<char, 4096> buffer_;
492
493 HTTPParser<Connection> parser_;
494 std::unique_ptr<routing_handle_result> routing_handle_result_;
495 request& req_;
496 response res;
497
498 bool close_connection_ = false;
499
500 const std::string& server_name_;
501 std::vector<asio::const_buffer> buffers_;
502
503 std::string content_length_;
504 std::string date_str_;
505 std::string res_body_copy_;
506
507 detail::task_timer::identifier_type task_id_{};
508
509 bool continue_requested{};
510 bool need_to_call_after_handlers_{};
511 bool need_to_start_read_after_complete_{};
512 bool add_keep_alive_{};
513
514 std::tuple<Middlewares...>* middlewares_;
515 detail::context<Middlewares...> ctx_;
516
517 std::function<std::string()>& get_cached_date_str;
518 detail::task_timer& task_timer_;
519
520 size_t res_stream_threshold_;
521
522 std::atomic<unsigned int>& queue_length_;
523 };
524
525} // 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: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:40