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)
84#define CROW_STATIC_FILE(app, url, internalPath) app.static_file(url, internalPath)
109#define CROW_BP_ROUTE(blueprint, url) blueprint.new_rule_tagged<crow::black_magic::get_parameter_tag(url)>(url)
138#define CROW_WEBSOCKET_ROUTE(app, url) app.route<crow::black_magic::get_parameter_tag(url)>(url).websocket<std::remove_reference<decltype(app)>::type>(&app)
160#define CROW_MIDDLEWARES(app, ...) template middlewares<typename std::remove_reference<decltype(app)>::type, __VA_ARGS__>()
176#define CROW_CATCHALL_ROUTE(app) app.catchall_route()
188#define CROW_BP_CATCHALL_ROUTE(blueprint) blueprint.catchall_rule()
202#ifdef CROW_ENABLE_SSL
203 using ssl_context_t = asio::ssl::context;
212 template<
typename... Middlewares>
223#ifdef CROW_ENABLE_SSL
257 template<
typename... Ts>
259 middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
265 template<
typename Adaptor>
268 router_.handle_upgrade(req, res, adaptor);
274 return router_.handle_initial(req, res);
280 router_.handle<
self_t>(req, res, *found);
287 if (found->rule_index || found->catch_all)
294 return router_.new_rule_dynamic(rule);
298 template<u
int64_t Tag>
300 ->
typename std::invoke_result<
decltype(&Router::new_rule_tagged<Tag>),
Router,
const std::string&>::type
302 return router_.new_rule_tagged<Tag>(rule);
325 rt([=,localFile=std::string(internalPath)](
crow::response& resp) ->
void {
336 return router_.catchall_rule();
342 max_payload_ = max_payload;
358 self_t& signal_add(
int signal_number)
360 signals_.push_back(signal_number);
364 std::vector<int> signals()
379 if (!server_started_)
383#ifdef CROW_ENABLE_SSL
386 return ssl_server_->port();
391 return server_->port();
449 return concurrency(std::thread::hardware_concurrency());
477 crow::logger::setLogLevel(level);
484 tcp_socket_options_.no_delay = enabled;
491 return tcp_socket_options_;
498 websocket_tcp_socket_options_.no_delay = enabled;
505 return websocket_tcp_socket_options_;
513 res_stream_threshold_ = threshold;
520 return res_stream_threshold_;
526 router_.register_blueprint(blueprint);
535 template<
typename Func>
538 router_.exception_handler() = std::forward<Func>(f);
544 return router_.exception_handler();
548 template<
typename Duration,
typename Func>
551 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
556#ifdef CROW_ENABLE_COMPRESSION
558 self_t& use_compression(compression::algorithm algorithm)
560 comp_algorithm_ = algorithm;
561 compression_used_ =
true;
565 compression::algorithm compression_algorithm()
567 return comp_algorithm_;
570 bool compression_used()
const
572 return compression_used_;
579#if defined(__APPLE__) || defined(__MACH__)
580 if (router_.blueprints().empty())
return;
583 for (
Blueprint* bp : router_.blueprints())
585 if (bp->static_dir().empty()) {
586 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
589 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
591 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) {
592 utility::sanitize_filename(file_path_partial);
598 router_.validate_bp();
604 if (are_static_routes_added())
return;
605 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
607 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](
crow::response& res, std::string file_path_partial) {
608 utility::sanitize_filename(file_path_partial);
612 set_static_routes_added();
624#ifndef CROW_DISABLE_STATIC_DIR
630#ifdef CROW_ENABLE_SSL
635 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
637 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
640 tcp::endpoint endpoint(addr, port_);
641 router_.using_ssl =
true;
642 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(
new ssl_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_, tcp_socket_options_)));
643 ssl_server_->set_tick_function(tick_interval_, tick_function_);
644 ssl_server_->signal_clear();
645 for (
auto snum : signals_)
647 ssl_server_->signal_add(snum);
649 notify_server_start();
657 UnixSocketAcceptor::endpoint endpoint(bindaddr_);
658 unix_server_ = std::move(std::unique_ptr<unix_server_t>(
new unix_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
659 unix_server_->set_tick_function(tick_interval_, tick_function_);
660 for (
auto snum : signals_)
662 unix_server_->signal_add(snum);
664 notify_server_start();
670 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
672 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
675 TCPAcceptor::endpoint endpoint(addr, port_);
676 server_ = std::move(std::unique_ptr<server_t>(
new server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr, tcp_socket_options_)));
677 server_->set_tick_function(tick_interval_, tick_function_);
678 for (
auto snum : signals_)
680 server_->signal_add(snum);
682 notify_server_start();
694 return std::async(std::launch::async, [&] {
702#ifdef CROW_ENABLE_SSL
705 if (ssl_server_) { ssl_server_->stop(); }
711 if (server_) { server_->stop(); }
712 if (unix_server_) { unix_server_->stop(); }
716 void close_websockets()
718 std::lock_guard<std::mutex> lock{websockets_mutex_};
719 for (
auto websocket : websockets_)
721 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
722 websocket->close(
"Websocket Closed");
727 void add_websocket(std::shared_ptr<websocket::connection> conn)
729 std::lock_guard<std::mutex> lock{websockets_mutex_};
730 websockets_.push_back(conn);
733 void remove_websocket(std::shared_ptr<websocket::connection> conn)
735 std::lock_guard<std::mutex> lock{websockets_mutex_};
736 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
742 CROW_LOG_DEBUG <<
"Routing:";
743 router_.debug_print();
747#ifdef CROW_ENABLE_SSL
750 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
753 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
754 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
755 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
756 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
757 ssl_context_.set_options(
758 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
766 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
767 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
768 ssl_context_.load_verify_file(pem_filename);
769 ssl_context_.set_options(
770 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
778 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
779 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
780 ssl_context_.use_certificate_chain_file(crt_filename);
781 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
782 ssl_context_.set_options(
783 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
787 self_t& ssl(asio::ssl::context&& ctx)
790 ssl_context_ = std::move(ctx);
794 bool ssl_used()
const
800 template<
typename T,
typename... Remain>
806 std::is_base_of<T, void>::value,
807 "Define CROW_ENABLE_SSL to enable ssl support.");
811 template<
typename T,
typename... Remain>
817 std::is_base_of<T, void>::value,
818 "Define CROW_ENABLE_SSL to enable ssl support.");
828 std::is_base_of<T, void>::value,
829 "Define CROW_ENABLE_SSL to enable ssl support.");
833 bool ssl_used()
const
840 using context_t = detail::context<Middlewares...>;
841 using mw_container_t = std::tuple<Middlewares...>;
843 typename T::context& get_context(
const request& req)
845 static_assert(black_magic::contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
846 auto& ctx = *
reinterpret_cast<context_t*
>(req.middleware_context);
847 return ctx.template get<T>();
853 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
859 std::cv_status status = std::cv_status::no_timeout;
860 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
862 std::unique_lock<std::mutex> lock(start_mutex_);
863 while (!server_started_ && (status == std::cv_status::no_timeout))
865 status = cv_started_.wait_until(lock, wait_until);
868 if (status == std::cv_status::no_timeout)
871 status = server_->wait_for_start(wait_until);
872 }
else if (unix_server_) {
873 status = unix_server_->wait_for_start(wait_until);
875#ifdef CROW_ENABLE_SSL
876 else if (ssl_server_)
878 status = ssl_server_->wait_for_start(wait_until);
886 template<
typename... Ts>
887 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
889 auto fwd = std::forward_as_tuple((ts)...);
890 return std::make_tuple(
891 std::forward<Middlewares>(
892 black_magic::tuple_extract<Middlewares,
decltype(fwd)>(fwd))...);
896 void notify_server_start()
898 std::unique_lock<std::mutex> lock(start_mutex_);
899 server_started_ =
true;
900 cv_started_.notify_all();
903 void set_static_routes_added() {
904 static_routes_added_ =
true;
907 bool are_static_routes_added() {
908 return static_routes_added_;
912 std::uint8_t timeout_{5};
914 unsigned int concurrency_ = 2;
915 std::atomic_bool is_bound_ =
false;
916 uint64_t max_payload_{UINT64_MAX};
917 std::string server_name_ = std::string(
"Crow/") + VERSION;
918 std::string bindaddr_ =
"0.0.0.0";
919 bool use_unix_ =
false;
920 detail::socket::tcp_socket_options tcp_socket_options_{};
921 detail::socket::tcp_socket_options websocket_tcp_socket_options_{};
922 size_t res_stream_threshold_ = 1048576;
924 bool static_routes_added_{
false};
926#ifdef CROW_ENABLE_COMPRESSION
927 compression::algorithm comp_algorithm_;
928 bool compression_used_{
false};
931 std::chrono::milliseconds tick_interval_;
932 std::function<void()> tick_function_;
934 std::tuple<Middlewares...> middlewares_;
936#ifdef CROW_ENABLE_SSL
937 std::unique_ptr<ssl_server_t> ssl_server_;
938 bool ssl_used_{
false};
939 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
942 std::unique_ptr<server_t> server_;
943 std::unique_ptr<unix_server_t> unix_server_;
945 std::vector<int> signals_{SIGINT, SIGTERM};
947 bool server_started_{
false};
948 std::condition_variable cv_started_;
949 std::mutex start_mutex_;
950 std::mutex websockets_mutex_;
951 std::vector<std::shared_ptr<websocket::connection>> websockets_;
956 template<
typename... Middlewares>
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition routing.h:1150
The main server application class.
Definition app.h:214
void stop()
Stop the server.
Definition app.h:700
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:511
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:857
void run()
Run the server.
Definition app.h:622
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition app.h:406
uint64_t websocket_max_payload()
Get the default max payload size for websockets.
Definition app.h:347
void add_static_dir()
Go through the rules, upgrade them if possible, and add them to the list of rules.
Definition app.h:602
Server< Crow, UnixSocketAcceptor, UnixSocketAdaptor, Middlewares... > unix_server_t
An HTTP server that runs on unix domain socket.
Definition app.h:222
StaticRule & route_static(const std::string &url)
Create a static route to given url.
Definition app.h:310
Crow self_t
This is the crow application.
Definition app.h:217
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:775
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:413
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition app.h:750
void handle_upgrade(const request &req, response &res, Adaptor &&adaptor)
Process an Upgrade request.
Definition app.h:266
self_t & websocket_tcp_nodelay(bool enabled=true)
Enable or disable TCP_NODELAY for WebSocket connections. We also have to differentiate between socket...
Definition app.h:496
self_t & multithreaded()
Run the server on multiple threads using all available threads.
Definition app.h:447
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition app.h:549
self_t & local_socket_path(std::string path)
Disable tcp/ip and use unix domain socket instead.
Definition app.h:433
void debug_print()
Print the routing paths defined for each HTTP method.
Definition app.h:740
self_t & tcp_nodelay(bool enabled=true)
Enable or disable TCP_NODELAY for accepted TCP connections.
Definition app.h:482
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:278
std::string bindaddr()
Get the address that Crow will handle requests on.
Definition app.h:427
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition app.h:370
bool is_bound() const
Get whether address that Crow will handle requests on is bound.
Definition app.h:401
std::uint16_t port() const
Get the port that Crow will handle requests on.
Definition app.h:377
self_t & concurrency(unsigned int concurrency)
Run the server on multiple threads using a specific number.
Definition app.h:453
Server< Crow, TCPAcceptor, SSLAdaptor, Middlewares... > ssl_server_t
An HTTP server that runs on SSL with an SSLAdaptor.
Definition app.h:225
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:536
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition app.h:420
Server< Crow, TCPAcceptor, SocketAdaptor, Middlewares... > server_t
The HTTP server.
Definition app.h:220
void validate()
A wrapper for validate() in the router.
Definition app.h:616
Crow(Ts &&... ts)
Construct Crow with a subset of middleware.
Definition app.h:258
CatchallRule & catchall_route()
Create a route for any requests without a proper route (Use CROW_CATCHALL_ROUTE instead)
Definition app.h:334
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition app.h:340
void handle_full(request &req, response &res)
Process a fully parsed request from start to finish (primarily used for debugging)
Definition app.h:284
StaticRule & static_file(std::string_view url, std::string_view internalPath)
Creates a static route for given url to internalPath.
Definition app.h:321
self_t & ssl_file(const std::string &pem_filename)
Use .pem file for SSL.
Definition app.h:763
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:272
std::string local_socket_path()
Get the unix domain socket path.
Definition app.h:441
DynamicRule & route_dynamic(const std::string &rule)
Create a dynamic route using a rule (Use CROW_ROUTE instead)
Definition app.h:292
self_t & loglevel(LogLevel level)
Set the server's log level.
Definition app.h:475
void add_blueprint()
Apply blueprints.
Definition app.h:577
void address_is_bound()
Set status variable to note that the address that Crow will handle requests on is bound.
Definition app.h:396
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:299
size_t & stream_threshold()
Get the response body size (in bytes) beyond which Crow automatically streams responses.
Definition app.h:518
std::uint16_t concurrency() const
Get the number of threads that server is using.
Definition app.h:462
detail::socket::tcp_socket_options websocket_tcp_socket_options() const
Get the TCP_NODELAY setting for WebSocket connections.
Definition app.h:503
detail::socket::tcp_socket_options tcp_socket_options() const
Get the TCP_NODELAY setting for HTTP connections.
Definition app.h:489
std::future< void > run_async()
Non-blocking version of run()
Definition app.h:692
A rule that can change its parameters during runtime.
Definition routing.h:625
Handles matching requests to existing rules and upgrade requests.
Definition routing.h:1304
Definition http_server.h:47
Default rule created when CROW_ROUTE is called.
Definition routing.h:703
A rule dealing with websockets.
Definition routing.h:425
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:62
Definition socket_adaptors.h:112
Definition tcp_socket_options.h:29
An HTTP request.
Definition http_request.h:47
HTTP response.
Definition http_response.h:40
void set_static_file_info(std::string path, std::string content_type="")
Return a static file as the response body, the content_type may be specified explicitly.
Definition http_response.h:301
void set_static_file_info_unsafe(std::string path, std::string content_type="")
Definition http_response.h:309
void end()
Set the response completion flag and call the handler (to send the response).
Definition http_response.h:250