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>
208#ifdef CROW_ENABLE_SSL
216 template<
typename... Ts>
218 middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
224 template<
typename Adaptor>
227 router_.handle_upgrade(req, res, adaptor);
233 return router_.handle_initial(req, res);
239 router_.handle<
self_t>(req, res, *found);
246 if (found->rule_index)
253 return router_.new_rule_dynamic(rule);
257 template<u
int64_t Tag>
259 ->
typename std::invoke_result<
decltype(&Router::new_rule_tagged<Tag>),
Router,
const std::string&>::type
261 return router_.new_rule_tagged<Tag>(rule);
267 return router_.catchall_rule();
273 max_payload_ = max_payload;
289 self_t& signal_add(
int signal_number)
291 signals_.push_back(signal_number);
295 std::vector<int> signals()
310 if (!server_started_)
314#ifdef CROW_ENABLE_SSL
317 return ssl_server_->port();
322 return server_->port();
370 return concurrency(std::thread::hardware_concurrency());
398 crow::logger::setLogLevel(level);
407 res_stream_threshold_ = threshold;
414 return res_stream_threshold_;
420 router_.register_blueprint(blueprint);
429 template<
typename Func>
432 router_.exception_handler() = std::forward<Func>(f);
438 return router_.exception_handler();
442 template<
typename Duration,
typename Func>
445 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
450#ifdef CROW_ENABLE_COMPRESSION
452 self_t& use_compression(compression::algorithm algorithm)
454 comp_algorithm_ = algorithm;
455 compression_used_ =
true;
459 compression::algorithm compression_algorithm()
461 return comp_algorithm_;
464 bool compression_used()
const
466 return compression_used_;
473#if defined(__APPLE__) || defined(__MACH__)
474 if (router_.blueprints().empty())
return;
477 for (
Blueprint* bp : router_.blueprints())
479 if (bp->static_dir().empty()) {
480 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
483 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
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);
492 router_.validate_bp();
498 if (are_static_routes_added())
return;
499 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
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);
506 set_static_routes_added();
518#ifndef CROW_DISABLE_STATIC_DIR
524#ifdef CROW_ENABLE_SSL
529 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
531 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
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_)
541 ssl_server_->signal_add(snum);
543 notify_server_start();
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_)
556 unix_server_->signal_add(snum);
558 notify_server_start();
564 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
566 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
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_)
574 server_->signal_add(snum);
576 notify_server_start();
588 return std::async(std::launch::async, [&] {
596#ifdef CROW_ENABLE_SSL
599 if (ssl_server_) { ssl_server_->stop(); }
605 if (server_) { server_->stop(); }
606 if (unix_server_) { unix_server_->stop(); }
610 void close_websockets()
612 for (
auto websocket : websockets_)
614 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
615 websocket->close(
"Websocket Closed");
622 websockets_.push_back(conn);
627 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
633 CROW_LOG_DEBUG <<
"Routing:";
634 router_.debug_print();
638#ifdef CROW_ENABLE_SSL
641 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
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);
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);
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);
678 self_t& ssl(asio::ssl::context&& ctx)
681 ssl_context_ = std::move(ctx);
685 bool ssl_used()
const
691 template<
typename T,
typename... Remain>
697 std::is_base_of<T, void>::value,
698 "Define CROW_ENABLE_SSL to enable ssl support.");
702 template<
typename T,
typename... Remain>
708 std::is_base_of<T, void>::value,
709 "Define CROW_ENABLE_SSL to enable ssl support.");
719 std::is_base_of<T, void>::value,
720 "Define CROW_ENABLE_SSL to enable ssl support.");
724 bool ssl_used()
const
731 using context_t = detail::context<Middlewares...>;
732 using mw_container_t = std::tuple<Middlewares...>;
734 typename T::context& get_context(
const request& req)
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>();
744 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
750 std::cv_status status = std::cv_status::no_timeout;
751 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
753 std::unique_lock<std::mutex> lock(start_mutex_);
754 while (!server_started_ && (status == std::cv_status::no_timeout))
756 status = cv_started_.wait_until(lock, wait_until);
759 if (status == std::cv_status::no_timeout)
762 status = server_->wait_for_start(wait_until);
763 }
else if (unix_server_) {
764 status = unix_server_->wait_for_start(wait_until);
766#ifdef CROW_ENABLE_SSL
767 else if (ssl_server_)
769 status = ssl_server_->wait_for_start(wait_until);
777 template<
typename... Ts>
778 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
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))...);
787 void notify_server_start()
789 std::unique_lock<std::mutex> lock(start_mutex_);
790 server_started_ =
true;
791 cv_started_.notify_all();
794 void set_static_routes_added() {
795 static_routes_added_ =
true;
798 bool are_static_routes_added() {
799 return static_routes_added_;
803 std::uint8_t timeout_{5};
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;
812 bool static_routes_added_{
false};
814#ifdef CROW_ENABLE_COMPRESSION
815 compression::algorithm comp_algorithm_;
816 bool compression_used_{
false};
819 std::chrono::milliseconds tick_interval_;
820 std::function<void()> tick_function_;
822 std::tuple<Middlewares...> middlewares_;
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};
830 std::unique_ptr<server_t> server_;
831 std::unique_ptr<unix_server_t> unix_server_;
833 std::vector<int> signals_{SIGINT, SIGTERM};
835 bool server_started_{
false};
836 std::condition_variable cv_started_;
837 std::mutex start_mutex_;
838 std::vector<crow::websocket::connection*> websockets_;
843 template<
typename... Middlewares>
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition routing.h:1101
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