26 #include <type_traits>
28 #include <condition_variable>
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"
45 #ifdef CROW_MSVC_WORKAROUND
47 #define CROW_ROUTE(app, url) app.route_dynamic(url)
48 #define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_dynamic(url)
70 #define CROW_ROUTE(app, url) app.template route<crow::black_magic::get_parameter_tag(url)>(url)
94 #define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_tagged<crow::black_magic::get_parameter_tag(url)>(url)
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)
145 #define CROW_MIDDLEWARES(app, ...) template middlewares<typename std::remove_reference<decltype(app)>::type, __VA_ARGS__>()
161 #define CROW_CATCHALL_ROUTE(app) app.catchall_route()
173 #define CROW_BP_CATCHALL_ROUTE(blueprint) blueprint.catchall_rule()
187 #ifdef CROW_ENABLE_SSL
188 using ssl_context_t = asio::ssl::context;
197 template<
typename... Middlewares>
207 #ifdef CROW_ENABLE_SSL
215 template<
typename... Ts>
217 middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
223 template<
typename Adaptor>
226 router_.handle_upgrade(req, res, adaptor);
232 return router_.handle_initial(req, res);
238 router_.handle<
self_t>(req, res, *found);
245 if (found->rule_index)
252 return router_.new_rule_dynamic(rule);
256 template<u
int64_t Tag>
257 #ifdef CROW_GCC83_WORKAROUND
258 auto&
route(
const std::string& rule)
262 #if defined CROW_CAN_USE_CPP17 && !defined CROW_GCC83_WORKAROUND
263 ->
typename std::invoke_result<decltype(&Router::new_rule_tagged<Tag>),
Router,
const std::string&>::type
264 #elif !defined CROW_GCC83_WORKAROUND
265 ->
typename std::result_of<decltype (&Router::new_rule_tagged<Tag>)(
Router,
const std::string&)>::type
268 return router_.new_rule_tagged<Tag>(rule);
274 return router_.catchall_rule();
280 max_payload_ = max_payload;
296 self_t& signal_add(
int signal_number)
298 signals_.push_back(signal_number);
302 std::vector<int> signals()
317 if (!server_started_)
321 #ifdef CROW_ENABLE_SSL
324 return ssl_server_->port();
329 return server_->port();
363 return concurrency(std::thread::hardware_concurrency());
391 crow::logger::setLogLevel(level);
400 res_stream_threshold_ = threshold;
407 return res_stream_threshold_;
413 router_.register_blueprint(blueprint);
422 template<
typename Func>
425 router_.exception_handler() = std::forward<Func>(f);
431 return router_.exception_handler();
435 template<
typename Duration,
typename Func>
438 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
443 #ifdef CROW_ENABLE_COMPRESSION
445 self_t& use_compression(compression::algorithm algorithm)
447 comp_algorithm_ = algorithm;
448 compression_used_ =
true;
452 compression::algorithm compression_algorithm()
454 return comp_algorithm_;
457 bool compression_used()
const
459 return compression_used_;
466 #if defined(__APPLE__) || defined(__MACH__)
467 if (router_.blueprints().empty())
return;
470 for (
Blueprint* bp : router_.blueprints())
472 if (bp->static_dir().empty()) {
473 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
476 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
478 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) {
479 utility::sanitize_filename(file_path_partial);
485 router_.validate_bp();
491 if (are_static_routes_added())
return;
492 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
494 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](
crow::response& res, std::string file_path_partial) {
495 utility::sanitize_filename(file_path_partial);
499 set_static_routes_added();
511 #ifndef CROW_DISABLE_STATIC_DIR
517 #ifdef CROW_ENABLE_SSL
520 router_.using_ssl =
true;
521 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(
new ssl_server_t(
this, bindaddr_, port_, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
522 ssl_server_->set_tick_function(tick_interval_, tick_function_);
523 ssl_server_->signal_clear();
524 for (
auto snum : signals_)
526 ssl_server_->signal_add(snum);
528 notify_server_start();
534 server_ = std::move(std::unique_ptr<server_t>(
new server_t(
this, bindaddr_, port_, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
535 server_->set_tick_function(tick_interval_, tick_function_);
536 for (
auto snum : signals_)
538 server_->signal_add(snum);
540 notify_server_start();
551 return std::async(std::launch::async, [&] {
559 #ifdef CROW_ENABLE_SSL
562 if (ssl_server_) { ssl_server_->stop(); }
568 std::vector<crow::websocket::connection*> websockets_to_close = websockets_;
569 for (
auto websocket : websockets_to_close)
571 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
572 websocket->close(
"Server Application Terminated");
574 if (server_) { server_->stop(); }
580 websockets_.push_back(conn);
585 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
591 CROW_LOG_DEBUG <<
"Routing:";
592 router_.debug_print();
596 #ifdef CROW_ENABLE_SSL
599 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
602 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
603 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
604 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
605 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
606 ssl_context_.set_options(
607 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
615 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
616 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
617 ssl_context_.load_verify_file(pem_filename);
618 ssl_context_.set_options(
619 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
627 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
628 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
629 ssl_context_.use_certificate_chain_file(crt_filename);
630 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
631 ssl_context_.set_options(
632 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
636 self_t& ssl(asio::ssl::context&& ctx)
639 ssl_context_ = std::move(ctx);
643 bool ssl_used()
const
649 template<
typename T,
typename... Remain>
655 std::is_base_of<T, void>::value,
656 "Define CROW_ENABLE_SSL to enable ssl support.");
660 template<
typename T,
typename... Remain>
666 std::is_base_of<T, void>::value,
667 "Define CROW_ENABLE_SSL to enable ssl support.");
677 std::is_base_of<T, void>::value,
678 "Define CROW_ENABLE_SSL to enable ssl support.");
682 bool ssl_used()
const
689 using context_t = detail::context<Middlewares...>;
690 using mw_container_t = std::tuple<Middlewares...>;
692 typename T::context& get_context(
const request& req)
694 static_assert(black_magic::contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
695 auto& ctx = *
reinterpret_cast<context_t*
>(req.middleware_context);
696 return ctx.template get<T>();
702 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
709 std::unique_lock<std::mutex> lock(start_mutex_);
710 while (!server_started_)
711 cv_started_.wait(lock);
714 server_->wait_for_start();
715 #ifdef CROW_ENABLE_SSL
716 else if (ssl_server_)
717 ssl_server_->wait_for_start();
722 template<
typename... Ts>
723 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
725 auto fwd = std::forward_as_tuple((ts)...);
726 return std::make_tuple(
727 std::forward<Middlewares>(
728 black_magic::tuple_extract<Middlewares, decltype(fwd)>(fwd))...);
732 void notify_server_start()
734 std::unique_lock<std::mutex> lock(start_mutex_);
735 server_started_ =
true;
736 cv_started_.notify_all();
739 void set_static_routes_added() {
740 static_routes_added_ =
true;
743 bool are_static_routes_added() {
744 return static_routes_added_;
748 std::uint8_t timeout_{5};
750 uint16_t concurrency_ = 2;
751 uint64_t max_payload_{UINT64_MAX};
752 std::string server_name_ = std::string(
"Crow/") + VERSION;
753 std::string bindaddr_ =
"0.0.0.0";
754 size_t res_stream_threshold_ = 1048576;
756 bool static_routes_added_{
false};
758 #ifdef CROW_ENABLE_COMPRESSION
759 compression::algorithm comp_algorithm_;
760 bool compression_used_{
false};
763 std::chrono::milliseconds tick_interval_;
764 std::function<void()> tick_function_;
766 std::tuple<Middlewares...> middlewares_;
768 #ifdef CROW_ENABLE_SSL
769 std::unique_ptr<ssl_server_t> ssl_server_;
770 bool ssl_used_{
false};
771 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
774 std::unique_ptr<server_t> server_;
776 std::vector<int> signals_{SIGINT, SIGTERM};
778 bool server_started_{
false};
779 std::condition_variable cv_started_;
780 std::mutex start_mutex_;
781 std::vector<crow::websocket::connection*> websockets_;
786 template<
typename... Middlewares>
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition: routing.h:1114
Definition: routing.h:345
The main server application class.
Definition: app.h:199
self_t & multithreaded()
Run the server on multiple threads using all available threads.
Definition: app.h:361
void stop()
Stop the server.
Definition: app.h:557
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition: app.h:436
DynamicRule & route_dynamic(const std::string &rule)
Create a dynamic route using a rule (Use CROW_ROUTE instead)
Definition: app.h:250
size_t & stream_threshold()
Get the response body size (in bytes) beyond which Crow automatically streams responses.
Definition: app.h:405
void run()
Run the server.
Definition: app.h:509
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition: app.h:278
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition: app.h:308
uint64_t websocket_max_payload()
Get the default max payload size for websockets.
Definition: app.h:285
void add_static_dir()
Go through the rules, upgrade them if possible, and add them to the list of rules.
Definition: app.h:489
self_t & ssl_file(const std::string &pem_filename)
Use .pem file for SSL.
Definition: app.h:612
self_t & concurrency(std::uint16_t concurrency)
Run the server on multiple threads using a specific number.
Definition: app.h:367
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition: app.h:334
Crow self_t
This is the crow application.
Definition: app.h:202
Server< Crow, SocketAdaptor, Middlewares... > server_t
The HTTP server.
Definition: app.h:205
auto route(const std::string &rule) -> typename std::result_of< decltype(&Router::new_rule_tagged< Tag >)(Router, const std::string &)>::type
Create a route using a rule (Use CROW_ROUTE instead)
Definition: app.h:260
void wait_for_server_start()
Wait until the server has properly started.
Definition: app.h:706
void handle_upgrade(const request &req, response &res, Adaptor &&adaptor)
Process an Upgrade request.
Definition: app.h:224
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition: app.h:348
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:230
self_t & loglevel(LogLevel level)
Set the server's log level.
Definition: app.h:389
void debug_print()
Print the routing paths defined for each HTTP method.
Definition: app.h:589
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:236
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:423
std::string bindaddr()
Get the address that Crow will handle requests on.
Definition: app.h:355
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition: app.h:599
std::uint16_t port() const
Get the port that Crow will handle requests on.
Definition: app.h:315
Server< Crow, SSLAdaptor, Middlewares... > ssl_server_t
An HTTP server that runs on SSL with an SSLAdaptor.
Definition: app.h:209
std::future< void > run_async()
Non-blocking version of run()
Definition: app.h:549
CatchallRule & catchall_route()
Create a route for any requests without a proper route (Use CROW_CATCHALL_ROUTE instead)
Definition: app.h:272
void validate()
A wrapper for validate() in the router.
Definition: app.h:503
Crow(Ts &&... ts)
Construct Crow with a subset of middleware.
Definition: app.h:216
std::uint16_t concurrency()
Get the number of threads that server is using.
Definition: app.h:376
void handle_full(request &req, response &res)
Process a fully parsed request from start to finish (primarily used for debugging)
Definition: app.h:242
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:624
self_t & server_name(std::string server_name)
Set the server name.
Definition: app.h:341
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:398
void add_blueprint()
Apply blueprints.
Definition: app.h:464
A rule that can change its parameters during runtime.
Definition: routing.h:585
Handles matching requests to existing rules and upgrade requests.
Definition: routing.h:1268
Definition: http_server.h:43
The main namespace of the library. In this namespace is defined the most important classes and functi...
Definition: socket_adaptors.h:107
A wrapper for the asio::ip::tcp::socket and asio::ssl::stream.
Definition: socket_adaptors.h:39
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