Crow  1.1
A C++ microframework for the web
 
Loading...
Searching...
No Matches
app.h
Go to the documentation of this file.
1/**
2 * \file crow/app.h
3 * \brief This file includes the definition of the crow::Crow class,
4 * the crow::App and crow::SimpleApp aliases, and some macros.
5 *
6 * In this file are defined:
7 * - crow::Crow
8 * - crow::App
9 * - crow::SimpleApp
10 * - \ref CROW_ROUTE
11 * - \ref CROW_BP_ROUTE
12 * - \ref CROW_WEBSOCKET_ROUTE
13 * - \ref CROW_MIDDLEWARES
14 * - \ref CROW_CATCHALL_ROUTE
15 * - \ref CROW_BP_CATCHALL_ROUTE
16 */
17
18#pragma once
19
20#include <chrono>
21#include <string>
22#include <functional>
23#include <memory>
24#include <future>
25#include <cstdint>
26#include <type_traits>
27#include <thread>
28#include <condition_variable>
29
30#include "crow/version.h"
31#include "crow/settings.h"
32#include "crow/logging.h"
33#include "crow/utility.h"
34#include "crow/routing.h"
35#include "crow/middleware_context.h"
36#include "crow/http_request.h"
37#include "crow/http_server.h"
38#include "crow/task_timer.h"
39#include "crow/websocket.h"
40#ifdef CROW_ENABLE_COMPRESSION
41#include "crow/compression.h"
42#endif // #ifdef CROW_ENABLE_COMPRESSION
43
44
45#ifdef CROW_MSVC_WORKAROUND
46
47#define CROW_ROUTE(app, url) app.route_dynamic(url) // See the documentation in the comment below.
48#define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_dynamic(url) // See the documentation in the comment below.
49
50#else // #ifdef CROW_MSVC_WORKAROUND
51
52/**
53 * \def CROW_ROUTE(app, url)
54 * \brief Creates a route for app using a rule.
55 *
56 * It use crow::Crow::route_dynamic or crow::Crow::route to define
57 * a rule for your application. It's usage is like this:
58 *
59 * ```cpp
60 * auto app = crow::SimpleApp(); // or crow::App()
61 * CROW_ROUTE(app, "/")
62 * ([](){
63 * return "<h1>Hello, world!</h1>";
64 * });
65 * ```
66 *
67 * This is the recommended way to define routes in a crow application.
68 * \see [Page of guide "Routes"](https://crowcpp.org/master/guides/routes/).
69 */
70#define CROW_ROUTE(app, url) app.template route<crow::black_magic::get_parameter_tag(url)>(url)
71
72/**
73 * \def CROW_BP_ROUTE(blueprint, url)
74 * \brief Creates a route for a blueprint using a rule.
75 *
76 * It may use crow::Blueprint::new_rule_dynamic or
77 * crow::Blueprint::new_rule_tagged to define a new rule for
78 * an given blueprint. It's usage is similar
79 * to CROW_ROUTE macro:
80 *
81 * ```cpp
82 * crow::Blueprint my_bp();
83 * CROW_BP_ROUTE(my_bp, "/")
84 * ([](){
85 * return "<h1>Hello, world!</h1>";
86 * });
87 * ```
88 *
89 * This is the recommended way to define routes in a crow blueprint
90 * because of its compile-time capabilities.
91 *
92 * \see [Page of the guide "Blueprints"](https://crowcpp.org/master/guides/blueprints/).
93 */
94#define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_tagged<crow::black_magic::get_parameter_tag(url)>(url)
95
96/**
97 * \def CROW_WEBSOCKET_ROUTE(app, url)
98 * \brief Defines WebSocket route for app.
99 *
100 * It binds a WebSocket route to app. Easy solution to implement
101 * WebSockets in your app. The usage syntax of this macro is
102 * like this:
103 *
104 * ```cpp
105 * auto app = crow::SimpleApp(); // or crow::App()
106 * CROW_WEBSOCKET_ROUTE(app, "/ws")
107 * .onopen([&](crow::websocket::connection& conn){
108 * do_something();
109 * })
110 * .onclose([&](crow::websocket::connection& conn, const std::string& reason, uint16_t){
111 * do_something();
112 * })
113 * .onmessage([&](crow::websocket::connection&, const std::string& data, bool is_binary){
114 * if (is_binary)
115 * do_something(data);
116 * else
117 * do_something_else(data);
118 * });
119 * ```
120 *
121 * \see [Page of the guide "WebSockets"](https://crowcpp.org/master/guides/websockets/).
122 */
123#define CROW_WEBSOCKET_ROUTE(app, url) app.route<crow::black_magic::get_parameter_tag(url)>(url).websocket<std::remove_reference<decltype(app)>::type>(&app)
124
125/**
126 * \def CROW_MIDDLEWARES(app, ...)
127 * \brief Enable a Middleware for an specific route in app
128 * or blueprint.
129 *
130 * It defines the usage of a Middleware in one route. And it
131 * can be used in both crow::SimpleApp (and crow::App) instances and
132 * crow::Blueprint. Its usage syntax is like this:
133 *
134 * ```cpp
135 * auto app = crow::SimpleApp(); // or crow::App()
136 * CROW_ROUTE(app, "/with_middleware")
137 * .CROW_MIDDLEWARES(app, LocalMiddleware) // Can be used more than one
138 * ([]() { // middleware.
139 * return "Hello world!";
140 * });
141 * ```
142 *
143 * \see [Page of the guide "Middlewares"](https://crowcpp.org/master/guides/middleware/).
144 */
145#define CROW_MIDDLEWARES(app, ...) template middlewares<typename std::remove_reference<decltype(app)>::type, __VA_ARGS__>()
146
147#endif // #ifdef CROW_MSVC_WORKAROUND
148
149/**
150 * \def CROW_CATCHALL_ROUTE(app)
151 * \brief Defines a custom catchall route for app using a
152 * custom rule.
153 *
154 * It defines a handler when the client make a request for an
155 * undefined route. Instead of just reply with a `404` status
156 * code (default behavior), you can define a custom handler
157 * using this macro.
158 *
159 * \see [Page of the guide "Routes" (Catchall routes)](https://crowcpp.org/master/guides/routes/#catchall-routes).
160 */
161#define CROW_CATCHALL_ROUTE(app) app.catchall_route()
162
163/**
164 * \def CROW_BP_CATCHALL_ROUTE(blueprint)
165 * \brief Defines a custom catchall route for blueprint
166 * using a custom rule.
167 *
168 * It defines a handler when the client make a request for an
169 * undefined route in the blueprint.
170 *
171 * \see [Page of the guide "Blueprint" (Define a custom Catchall route)](https://crowcpp.org/master/guides/blueprints/#define-a-custom-catchall-route).
172 */
173#define CROW_BP_CATCHALL_ROUTE(blueprint) blueprint.catchall_rule()
174
175
176/**
177 * \namespace crow
178 * \brief The main namespace of the library. In this namespace
179 * is defined the most important classes and functions of the
180 * library.
181 *
182 * Within this namespace, the Crow class, Router class, Connection
183 * class, and other are defined.
184 */
185namespace crow
186{
187#ifdef CROW_ENABLE_SSL
188 using ssl_context_t = asio::ssl::context;
189#endif
190 /**
191 * \class Crow
192 * \brief The main server application class.
193 *
194 * Use crow::SimpleApp or crow::App<Middleware1, Middleware2, etc...> instead of
195 * directly instantiate this class.
196 */
197 template<typename... Middlewares>
198 class Crow
199 {
200 public:
201 /// \brief This is the crow application
202 using self_t = Crow;
203
204 /// \brief The HTTP server
205 using server_t = Server<Crow, TCPAcceptor, SocketAdaptor, Middlewares...>;
206 /// \brief An HTTP server that runs on unix domain socket
208#ifdef CROW_ENABLE_SSL
209 /// \brief An HTTP server that runs on SSL with an SSLAdaptor
210 using ssl_server_t = Server<Crow, TCPAcceptor, SSLAdaptor, Middlewares...>;
211#endif
212 Crow()
213 {}
214
215 /// \brief Construct Crow with a subset of middleware
216 template<typename... Ts>
217 Crow(Ts&&... ts):
218 middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
219 {}
220
221 /// \brief Process an Upgrade request
222 ///
223 /// Currently used to upgrade an HTTP connection to a WebSocket connection
224 template<typename Adaptor>
225 void handle_upgrade(const request& req, response& res, Adaptor&& adaptor)
226 {
227 router_.handle_upgrade(req, res, adaptor);
228 }
229
230 /// \brief Process only the method and URL of a request and provide a route (or an error response)
231 std::unique_ptr<routing_handle_result> handle_initial(request& req, response& res)
232 {
233 return router_.handle_initial(req, res);
234 }
235
236 /// \brief Process the fully parsed request and generate a response for it
237 void handle(request& req, response& res, std::unique_ptr<routing_handle_result>& found)
238 {
239 router_.handle<self_t>(req, res, *found);
240 }
241
242 /// \brief Process a fully parsed request from start to finish (primarily used for debugging)
243 void handle_full(request& req, response& res)
244 {
245 auto found = handle_initial(req, res);
246 if (found->rule_index)
247 handle(req, res, found);
248 }
249
250 /// \brief Create a dynamic route using a rule (**Use CROW_ROUTE instead**)
251 DynamicRule& route_dynamic(const std::string& rule)
252 {
253 return router_.new_rule_dynamic(rule);
254 }
255
256 /// \brief Create a route using a rule (**Use CROW_ROUTE instead**)
257 template<uint64_t Tag>
258 auto route(const std::string& rule)
259 -> typename std::invoke_result<decltype(&Router::new_rule_tagged<Tag>), Router, const std::string&>::type
260 {
261 return router_.new_rule_tagged<Tag>(rule);
262 }
263
264 /// \brief Create a route for any requests without a proper route (**Use CROW_CATCHALL_ROUTE instead**)
266 {
267 return router_.catchall_rule();
268 }
269
270 /// \brief Set the default max payload size for websockets
271 self_t& websocket_max_payload(uint64_t max_payload)
272 {
273 max_payload_ = max_payload;
274 return *this;
275 }
276
277 /// \brief Get the default max payload size for websockets
279 {
280 return max_payload_;
281 }
282
283 self_t& signal_clear()
284 {
285 signals_.clear();
286 return *this;
287 }
288
289 self_t& signal_add(int signal_number)
290 {
291 signals_.push_back(signal_number);
292 return *this;
293 }
294
295 std::vector<int> signals()
296 {
297 return signals_;
298 }
299
300 /// \brief Set the port that Crow will handle requests on
301 self_t& port(std::uint16_t port)
302 {
303 port_ = port;
304 return *this;
305 }
306
307 /// \brief Get the port that Crow will handle requests on
308 std::uint16_t port() const
309 {
310 if (!server_started_)
311 {
312 return port_;
313 }
314#ifdef CROW_ENABLE_SSL
315 if (ssl_used_)
316 {
317 return ssl_server_->port();
318 }
319 else
320#endif
321 {
322 return server_->port();
323 }
324 }
325
326 /// \brief Set the connection timeout in seconds (default is 5)
327 self_t& timeout(std::uint8_t timeout)
328 {
329 timeout_ = timeout;
330 return *this;
331 }
332
333 /// \brief Set the server name included in the 'Server' HTTP response header. If set to an empty string, the header will be omitted by default.
335 {
336 server_name_ = server_name;
337 return *this;
338 }
339
340 /// \brief The IP address that Crow will handle requests on (default is 0.0.0.0)
342 {
343 bindaddr_ = bindaddr;
344 return *this;
345 }
346
347 /// \brief Get the address that Crow will handle requests on
348 std::string bindaddr()
349 {
350 return bindaddr_;
351 }
352
353 /// \brief Disable tcp/ip and use unix domain socket instead
354 self_t& local_socket_path(std::string path)
355 {
356 bindaddr_ = path;
357 use_unix_ = true;
358 return *this;
359 }
360
361 /// \brief Get the unix domain socket path
362 std::string local_socket_path()
363 {
364 return bindaddr_;
365 }
366
367 /// \brief Run the server on multiple threads using all available threads
369 {
370 return concurrency(std::thread::hardware_concurrency());
371 }
372
373 /// \brief Run the server on multiple threads using a specific number
375 {
376 if (concurrency < 2) // Crow can have a minimum of 2 threads running
377 concurrency = 2;
378 concurrency_ = concurrency;
379 return *this;
380 }
381
382 /// \brief Get the number of threads that server is using
383 std::uint16_t concurrency() const
384 {
385 return concurrency_;
386 }
387
388 /// \brief Set the server's log level
389 ///
390 /// Possible values are:
391 /// - crow::LogLevel::Debug (0)
392 /// - crow::LogLevel::Info (1)
393 /// - crow::LogLevel::Warning (2)
394 /// - crow::LogLevel::Error (3)
395 /// - crow::LogLevel::Critical (4)
396 self_t& loglevel(LogLevel level)
397 {
398 crow::logger::setLogLevel(level);
399 return *this;
400 }
401
402 /// \brief Set the response body size (in bytes) beyond which Crow automatically streams responses (Default is 1MiB)
403 ///
404 /// Any streamed response is unaffected by Crow's timer, and therefore won't timeout before a response is fully sent.
405 self_t& stream_threshold(size_t threshold)
406 {
407 res_stream_threshold_ = threshold;
408 return *this;
409 }
410
411 /// \brief Get the response body size (in bytes) beyond which Crow automatically streams responses
413 {
414 return res_stream_threshold_;
415 }
416
417
418 self_t& register_blueprint(Blueprint& blueprint)
419 {
420 router_.register_blueprint(blueprint);
421 return *this;
422 }
423
424 /// \brief Set the function to call to handle uncaught exceptions generated in routes (Default generates error 500).
425 ///
426 /// The function must have the following signature: void(crow::response&).
427 /// It must set the response passed in argument to the function, which will be sent back to the client.
428 /// See Router::default_exception_handler() for the default implementation.
429 template<typename Func>
431 {
432 router_.exception_handler() = std::forward<Func>(f);
433 return *this;
434 }
435
436 std::function<void(crow::response&)>& exception_handler()
437 {
438 return router_.exception_handler();
439 }
440
441 /// \brief Set a custom duration and function to run on every tick
442 template<typename Duration, typename Func>
443 self_t& tick(Duration d, Func f)
444 {
445 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
446 tick_function_ = f;
447 return *this;
448 }
449
450#ifdef CROW_ENABLE_COMPRESSION
451
452 self_t& use_compression(compression::algorithm algorithm)
453 {
454 comp_algorithm_ = algorithm;
455 compression_used_ = true;
456 return *this;
457 }
458
459 compression::algorithm compression_algorithm()
460 {
461 return comp_algorithm_;
462 }
463
464 bool compression_used() const
465 {
466 return compression_used_;
467 }
468#endif
469
470 /// \brief Apply blueprints
472 {
473#if defined(__APPLE__) || defined(__MACH__)
474 if (router_.blueprints().empty()) return;
475#endif
476
477 for (Blueprint* bp : router_.blueprints())
478 {
479 if (bp->static_dir().empty()) {
480 CROW_LOG_ERROR << "Blueprint " << bp->prefix() << " and its sub-blueprints ignored due to empty static directory.";
481 continue;
482 }
483 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
484
485 bp->new_rule_tagged<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](crow::response& res, std::string file_path_partial) {
486 utility::sanitize_filename(file_path_partial);
487 res.set_static_file_info_unsafe(static_dir_ + file_path_partial);
488 res.end();
489 });
490 }
491
492 router_.validate_bp();
493 }
494
495 /// \brief Go through the rules, upgrade them if possible, and add them to the list of rules
497 {
498 if (are_static_routes_added()) return;
499 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
500
501 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](crow::response& res, std::string file_path_partial) {
502 utility::sanitize_filename(file_path_partial);
503 res.set_static_file_info_unsafe(static_dir_ + file_path_partial);
504 res.end();
505 });
506 set_static_routes_added();
507 }
508
509 /// \brief A wrapper for `validate()` in the router
510 void validate()
511 {
512 router_.validate();
513 }
514
515 /// \brief Run the server
516 void run()
517 {
518#ifndef CROW_DISABLE_STATIC_DIR
521#endif
522 validate();
523
524#ifdef CROW_ENABLE_SSL
525 if (ssl_used_)
526 {
527
528 error_code ec;
529 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
530 if (ec){
531 CROW_LOG_ERROR << ec.message() << " - Can not create valid ip address from string: \"" << bindaddr_ << "\"";
532 return;
533 }
534 tcp::endpoint endpoint(addr, port_);
535 router_.using_ssl = true;
536 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(new ssl_server_t(this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
537 ssl_server_->set_tick_function(tick_interval_, tick_function_);
538 ssl_server_->signal_clear();
539 for (auto snum : signals_)
540 {
541 ssl_server_->signal_add(snum);
542 }
543 notify_server_start();
544 ssl_server_->run();
545 }
546 else
547#endif
548 {
549 if (use_unix_)
550 {
551 UnixSocketAcceptor::endpoint endpoint(bindaddr_);
552 unix_server_ = std::move(std::unique_ptr<unix_server_t>(new unix_server_t(this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, nullptr)));
553 unix_server_->set_tick_function(tick_interval_, tick_function_);
554 for (auto snum : signals_)
555 {
556 unix_server_->signal_add(snum);
557 }
558 notify_server_start();
559 unix_server_->run();
560 }
561 else
562 {
563 error_code ec;
564 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
565 if (ec){
566 CROW_LOG_ERROR << ec.message() << " - Can not create valid ip address from string: \"" << bindaddr_ << "\"";
567 return;
568 }
569 TCPAcceptor::endpoint endpoint(addr, port_);
570 server_ = std::move(std::unique_ptr<server_t>(new server_t(this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, nullptr)));
571 server_->set_tick_function(tick_interval_, tick_function_);
572 for (auto snum : signals_)
573 {
574 server_->signal_add(snum);
575 }
576 notify_server_start();
577 server_->run();
578 }
579 }
580 }
581
582 /// \brief Non-blocking version of \ref run()
583 ///
584 /// The output from this method needs to be saved into a variable!
585 /// Otherwise the call will be made on the same thread.
586 std::future<void> run_async()
587 {
588 return std::async(std::launch::async, [&] {
589 this->run();
590 });
591 }
592
593 /// \brief Stop the server
594 void stop()
595 {
596#ifdef CROW_ENABLE_SSL
597 if (ssl_used_)
598 {
599 if (ssl_server_) { ssl_server_->stop(); }
600 }
601 else
602#endif
603 {
604 close_websockets();
605 if (server_) { server_->stop(); }
606 if (unix_server_) { unix_server_->stop(); }
607 }
608 }
609
610 void close_websockets()
611 {
612 for (auto websocket : websockets_)
613 {
614 CROW_LOG_INFO << "Quitting Websocket: " << websocket;
615 websocket->close("Websocket Closed");
616 }
617 }
618
619
620 void add_websocket(crow::websocket::connection* conn)
621 {
622 websockets_.push_back(conn);
623 }
624
625 void remove_websocket(crow::websocket::connection* conn)
626 {
627 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
628 }
629
630 /// \brief Print the routing paths defined for each HTTP method
632 {
633 CROW_LOG_DEBUG << "Routing:";
634 router_.debug_print();
635 }
636
637
638#ifdef CROW_ENABLE_SSL
639
640 /// \brief Use certificate and key files for SSL
641 self_t& ssl_file(const std::string& crt_filename, const std::string& key_filename)
642 {
643 ssl_used_ = true;
644 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
645 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
646 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
647 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
648 ssl_context_.set_options(
649 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
650 return *this;
651 }
652
653 /// \brief Use `.pem` file for SSL
654 self_t& ssl_file(const std::string& pem_filename)
655 {
656 ssl_used_ = true;
657 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
658 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
659 ssl_context_.load_verify_file(pem_filename);
660 ssl_context_.set_options(
661 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
662 return *this;
663 }
664
665 /// \brief Use certificate chain and key files for SSL
666 self_t& ssl_chainfile(const std::string& crt_filename, const std::string& key_filename)
667 {
668 ssl_used_ = true;
669 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
670 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
671 ssl_context_.use_certificate_chain_file(crt_filename);
672 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
673 ssl_context_.set_options(
674 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
675 return *this;
676 }
677
678 self_t& ssl(asio::ssl::context&& ctx)
679 {
680 ssl_used_ = true;
681 ssl_context_ = std::move(ctx);
682 return *this;
683 }
684
685 bool ssl_used() const
686 {
687 return ssl_used_;
688 }
689#else
690
691 template<typename T, typename... Remain>
692 self_t& ssl_file(T&&, Remain&&...)
693 {
694 // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
695 static_assert(
696 // make static_assert dependent to T; always false
697 std::is_base_of<T, void>::value,
698 "Define CROW_ENABLE_SSL to enable ssl support.");
699 return *this;
700 }
701
702 template<typename T, typename... Remain>
703 self_t& ssl_chainfile(T&&, Remain&&...)
704 {
705 // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
706 static_assert(
707 // make static_assert dependent to T; always false
708 std::is_base_of<T, void>::value,
709 "Define CROW_ENABLE_SSL to enable ssl support.");
710 return *this;
711 }
712
713 template<typename T>
714 self_t& ssl(T&&)
715 {
716 // We can't call .ssl() member function unless CROW_ENABLE_SSL is defined.
717 static_assert(
718 // make static_assert dependent to T; always false
719 std::is_base_of<T, void>::value,
720 "Define CROW_ENABLE_SSL to enable ssl support.");
721 return *this;
722 }
723
724 bool ssl_used() const
725 {
726 return false;
727 }
728#endif
729
730 // middleware
731 using context_t = detail::context<Middlewares...>;
732 using mw_container_t = std::tuple<Middlewares...>;
733 template<typename T>
734 typename T::context& get_context(const request& req)
735 {
736 static_assert(black_magic::contains<T, Middlewares...>::value, "App doesn't have the specified middleware type.");
737 auto& ctx = *reinterpret_cast<context_t*>(req.middleware_context);
738 return ctx.template get<T>();
739 }
740
741 template<typename T>
742 T& get_middleware()
743 {
744 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
745 }
746
747 /// \brief Wait until the server has properly started
748 std::cv_status wait_for_server_start(std::chrono::milliseconds wait_timeout = std::chrono::milliseconds(3000))
749 {
750 std::cv_status status = std::cv_status::no_timeout;
751 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
752 {
753 std::unique_lock<std::mutex> lock(start_mutex_);
754 while (!server_started_ && (status == std::cv_status::no_timeout))
755 {
756 status = cv_started_.wait_until(lock, wait_until);
757 }
758 }
759 if (status == std::cv_status::no_timeout)
760 {
761 if (server_) {
762 status = server_->wait_for_start(wait_until);
763 } else if (unix_server_) {
764 status = unix_server_->wait_for_start(wait_until);
765 }
766#ifdef CROW_ENABLE_SSL
767 else if (ssl_server_)
768 {
769 status = ssl_server_->wait_for_start(wait_until);
770 }
771#endif
772 }
773 return status;
774 }
775
776 private:
777 template<typename... Ts>
778 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
779 {
780 auto fwd = std::forward_as_tuple((ts)...);
781 return std::make_tuple(
782 std::forward<Middlewares>(
783 black_magic::tuple_extract<Middlewares, decltype(fwd)>(fwd))...);
784 }
785
786 /// \brief Notify anything using \ref wait_for_server_start() to proceed
787 void notify_server_start()
788 {
789 std::unique_lock<std::mutex> lock(start_mutex_);
790 server_started_ = true;
791 cv_started_.notify_all();
792 }
793
794 void set_static_routes_added() {
795 static_routes_added_ = true;
796 }
797
798 bool are_static_routes_added() {
799 return static_routes_added_;
800 }
801
802 private:
803 std::uint8_t timeout_{5};
804 uint16_t port_ = 80;
805 unsigned int concurrency_ = 2;
806 uint64_t max_payload_{UINT64_MAX};
807 std::string server_name_ = std::string("Crow/") + VERSION;
808 std::string bindaddr_ = "0.0.0.0";
809 bool use_unix_ = false;
810 size_t res_stream_threshold_ = 1048576;
811 Router router_;
812 bool static_routes_added_{false};
813
814#ifdef CROW_ENABLE_COMPRESSION
815 compression::algorithm comp_algorithm_;
816 bool compression_used_{false};
817#endif
818
819 std::chrono::milliseconds tick_interval_;
820 std::function<void()> tick_function_;
821
822 std::tuple<Middlewares...> middlewares_;
823
824#ifdef CROW_ENABLE_SSL
825 std::unique_ptr<ssl_server_t> ssl_server_;
826 bool ssl_used_{false};
827 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
828#endif
829
830 std::unique_ptr<server_t> server_;
831 std::unique_ptr<unix_server_t> unix_server_;
832
833 std::vector<int> signals_{SIGINT, SIGTERM};
834
835 bool server_started_{false};
836 std::condition_variable cv_started_;
837 std::mutex start_mutex_;
838 std::vector<crow::websocket::connection*> websockets_;
839 };
840
841 /// \brief Alias of Crow<Middlewares...>. Useful if you want
842 /// a instance of an Crow application that require Middlewares
843 template<typename... Middlewares>
844 using App = Crow<Middlewares...>;
845
846 /// \brief Alias of Crow<>. Useful if you want a instance of
847 /// an Crow application that doesn't require of Middlewares
849} // namespace crow
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition routing.h:1101
Definition routing.h:344
The main server application class.
Definition app.h:199
void stop()
Stop the server.
Definition app.h:594
self_t & stream_threshold(size_t threshold)
Set the response body size (in bytes) beyond which Crow automatically streams responses (Default is 1...
Definition app.h:405
std::cv_status wait_for_server_start(std::chrono::milliseconds wait_timeout=std::chrono::milliseconds(3000))
Wait until the server has properly started.
Definition app.h:748
void run()
Run the server.
Definition app.h:516
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition app.h:327
uint64_t websocket_max_payload()
Get the default max payload size for websockets.
Definition app.h:278
void add_static_dir()
Go through the rules, upgrade them if possible, and add them to the list of rules.
Definition app.h:496
Server< Crow, UnixSocketAcceptor, UnixSocketAdaptor, Middlewares... > unix_server_t
An HTTP server that runs on unix domain socket.
Definition app.h:207
Crow self_t
This is the crow application.
Definition app.h:202
self_t & ssl_chainfile(const std::string &crt_filename, const std::string &key_filename)
Use certificate chain and key files for SSL.
Definition app.h:666
self_t & server_name(std::string server_name)
Set the server name included in the 'Server' HTTP response header. If set to an empty string,...
Definition app.h:334
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition app.h:641
void handle_upgrade(const request &req, response &res, Adaptor &&adaptor)
Process an Upgrade request.
Definition app.h:225
self_t & multithreaded()
Run the server on multiple threads using all available threads.
Definition app.h:368
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition app.h:443
self_t & local_socket_path(std::string path)
Disable tcp/ip and use unix domain socket instead.
Definition app.h:354
void debug_print()
Print the routing paths defined for each HTTP method.
Definition app.h:631
void handle(request &req, response &res, std::unique_ptr< routing_handle_result > &found)
Process the fully parsed request and generate a response for it.
Definition app.h:237
std::string bindaddr()
Get the address that Crow will handle requests on.
Definition app.h:348
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition app.h:301
std::uint16_t port() const
Get the port that Crow will handle requests on.
Definition app.h:308
self_t & concurrency(unsigned int concurrency)
Run the server on multiple threads using a specific number.
Definition app.h:374
Server< Crow, TCPAcceptor, SSLAdaptor, Middlewares... > ssl_server_t
An HTTP server that runs on SSL with an SSLAdaptor.
Definition app.h:210
self_t & exception_handler(Func &&f)
Set the function to call to handle uncaught exceptions generated in routes (Default generates error 5...
Definition app.h:430
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition app.h:341
Server< Crow, TCPAcceptor, SocketAdaptor, Middlewares... > server_t
The HTTP server.
Definition app.h:205
void validate()
A wrapper for validate() in the router.
Definition app.h:510
Crow(Ts &&... ts)
Construct Crow with a subset of middleware.
Definition app.h:217
CatchallRule & catchall_route()
Create a route for any requests without a proper route (Use CROW_CATCHALL_ROUTE instead)
Definition app.h:265
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition app.h:271
void handle_full(request &req, response &res)
Process a fully parsed request from start to finish (primarily used for debugging)
Definition app.h:243
self_t & ssl_file(const std::string &pem_filename)
Use .pem file for SSL.
Definition app.h:654
std::unique_ptr< routing_handle_result > handle_initial(request &req, response &res)
Process only the method and URL of a request and provide a route (or an error response)
Definition app.h:231
std::string local_socket_path()
Get the unix domain socket path.
Definition app.h:362
DynamicRule & route_dynamic(const std::string &rule)
Create a dynamic route using a rule (Use CROW_ROUTE instead)
Definition app.h:251
self_t & loglevel(LogLevel level)
Set the server's log level.
Definition app.h:396
void add_blueprint()
Apply blueprints.
Definition app.h:471
auto route(const std::string &rule) -> typename std::invoke_result< decltype(&Router::new_rule_tagged< Tag >), Router, const std::string & >::type
Create a route using a rule (Use CROW_ROUTE instead)
Definition app.h:258
size_t & stream_threshold()
Get the response body size (in bytes) beyond which Crow automatically streams responses.
Definition app.h:412
std::uint16_t concurrency() const
Get the number of threads that server is using.
Definition app.h:383
std::future< void > run_async()
Non-blocking version of run()
Definition app.h:586
A rule that can change its parameters during runtime.
Definition routing.h:578
Handles matching requests to existing rules and upgrade requests.
Definition routing.h:1256
Definition http_server.h:45
The main namespace of the library. In this namespace is defined the most important classes and functi...
Definition socket_adaptors.h:184
A wrapper for the asio::ip::tcp::socket and asio::ssl::stream.
Definition socket_adaptors.h:40
Definition socket_acceptors.h:31
Definition socket_acceptors.h:61
Definition socket_adaptors.h:112
An HTTP request.
Definition http_request.h:36
HTTP response.
Definition http_response.h:34
void end()
Set the response completion flag and call the handler (to send the response).
Definition http_response.h:237
void set_static_file_info_unsafe(std::string path)
Return a static file as the response body without sanitizing the path (use set_static_file_info inste...
Definition http_response.h:295
A base class for websocket connection.
Definition websocket.h:62