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();
380 return concurrency(std::thread::hardware_concurrency());
408 crow::logger::setLogLevel(level);
417 res_stream_threshold_ = threshold;
424 return res_stream_threshold_;
430 router_.register_blueprint(blueprint);
439 template<
typename Func>
442 router_.exception_handler() = std::forward<Func>(f);
448 return router_.exception_handler();
452 template<
typename Duration,
typename Func>
455 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
460#ifdef CROW_ENABLE_COMPRESSION
462 self_t& use_compression(compression::algorithm algorithm)
464 comp_algorithm_ = algorithm;
465 compression_used_ =
true;
469 compression::algorithm compression_algorithm()
471 return comp_algorithm_;
474 bool compression_used()
const
476 return compression_used_;
483#if defined(__APPLE__) || defined(__MACH__)
484 if (router_.blueprints().empty())
return;
487 for (
Blueprint* bp : router_.blueprints())
489 if (bp->static_dir().empty()) {
490 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
493 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
495 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) {
496 utility::sanitize_filename(file_path_partial);
502 router_.validate_bp();
508 if (are_static_routes_added())
return;
509 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
511 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](
crow::response& res, std::string file_path_partial) {
512 utility::sanitize_filename(file_path_partial);
516 set_static_routes_added();
528#ifndef CROW_DISABLE_STATIC_DIR
534#ifdef CROW_ENABLE_SSL
539 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
541 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
544 tcp::endpoint endpoint(addr, port_);
545 router_.using_ssl =
true;
546 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(
new ssl_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
547 ssl_server_->set_tick_function(tick_interval_, tick_function_);
548 ssl_server_->signal_clear();
549 for (
auto snum : signals_)
551 ssl_server_->signal_add(snum);
553 notify_server_start();
561 UnixSocketAcceptor::endpoint endpoint(bindaddr_);
562 unix_server_ = std::move(std::unique_ptr<unix_server_t>(
new unix_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
563 unix_server_->set_tick_function(tick_interval_, tick_function_);
564 for (
auto snum : signals_)
566 unix_server_->signal_add(snum);
568 notify_server_start();
574 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
576 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
579 TCPAcceptor::endpoint endpoint(addr, port_);
580 server_ = std::move(std::unique_ptr<server_t>(
new server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
581 server_->set_tick_function(tick_interval_, tick_function_);
582 for (
auto snum : signals_)
584 server_->signal_add(snum);
586 notify_server_start();
598 return std::async(std::launch::async, [&] {
606#ifdef CROW_ENABLE_SSL
609 if (ssl_server_) { ssl_server_->stop(); }
615 if (server_) { server_->stop(); }
616 if (unix_server_) { unix_server_->stop(); }
620 void close_websockets()
622 for (
auto websocket : websockets_)
624 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
625 websocket->close(
"Websocket Closed");
632 websockets_.push_back(conn);
637 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
643 CROW_LOG_DEBUG <<
"Routing:";
644 router_.debug_print();
648#ifdef CROW_ENABLE_SSL
651 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
654 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
655 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
656 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
657 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
658 ssl_context_.set_options(
659 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
667 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
668 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
669 ssl_context_.load_verify_file(pem_filename);
670 ssl_context_.set_options(
671 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
679 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
680 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
681 ssl_context_.use_certificate_chain_file(crt_filename);
682 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
683 ssl_context_.set_options(
684 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
688 self_t& ssl(asio::ssl::context&& ctx)
691 ssl_context_ = std::move(ctx);
695 bool ssl_used()
const
701 template<
typename T,
typename... Remain>
707 std::is_base_of<T, void>::value,
708 "Define CROW_ENABLE_SSL to enable ssl support.");
712 template<
typename T,
typename... Remain>
718 std::is_base_of<T, void>::value,
719 "Define CROW_ENABLE_SSL to enable ssl support.");
729 std::is_base_of<T, void>::value,
730 "Define CROW_ENABLE_SSL to enable ssl support.");
734 bool ssl_used()
const
741 using context_t = detail::context<Middlewares...>;
742 using mw_container_t = std::tuple<Middlewares...>;
744 typename T::context& get_context(
const request& req)
746 static_assert(black_magic::contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
747 auto& ctx = *
reinterpret_cast<context_t*
>(req.middleware_context);
748 return ctx.template get<T>();
754 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
760 std::cv_status status = std::cv_status::no_timeout;
761 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
763 std::unique_lock<std::mutex> lock(start_mutex_);
764 while (!server_started_ && (status == std::cv_status::no_timeout))
766 status = cv_started_.wait_until(lock, wait_until);
769 if (status == std::cv_status::no_timeout)
772 status = server_->wait_for_start(wait_until);
773 }
else if (unix_server_) {
774 status = unix_server_->wait_for_start(wait_until);
776#ifdef CROW_ENABLE_SSL
777 else if (ssl_server_)
779 status = ssl_server_->wait_for_start(wait_until);
787 template<
typename... Ts>
788 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
790 auto fwd = std::forward_as_tuple((ts)...);
791 return std::make_tuple(
792 std::forward<Middlewares>(
793 black_magic::tuple_extract<Middlewares,
decltype(fwd)>(fwd))...);
797 void notify_server_start()
799 std::unique_lock<std::mutex> lock(start_mutex_);
800 server_started_ =
true;
801 cv_started_.notify_all();
804 void set_static_routes_added() {
805 static_routes_added_ =
true;
808 bool are_static_routes_added() {
809 return static_routes_added_;
813 std::uint8_t timeout_{5};
815 unsigned int concurrency_ = 2;
816 std::atomic_bool is_bound_ =
false;
817 uint64_t max_payload_{UINT64_MAX};
818 std::string server_name_ = std::string(
"Crow/") + VERSION;
819 std::string bindaddr_ =
"0.0.0.0";
820 bool use_unix_ =
false;
821 size_t res_stream_threshold_ = 1048576;
823 bool static_routes_added_{
false};
825#ifdef CROW_ENABLE_COMPRESSION
826 compression::algorithm comp_algorithm_;
827 bool compression_used_{
false};
830 std::chrono::milliseconds tick_interval_;
831 std::function<void()> tick_function_;
833 std::tuple<Middlewares...> middlewares_;
835#ifdef CROW_ENABLE_SSL
836 std::unique_ptr<ssl_server_t> ssl_server_;
837 bool ssl_used_{
false};
838 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
841 std::unique_ptr<server_t> server_;
842 std::unique_ptr<unix_server_t> unix_server_;
844 std::vector<int> signals_{SIGINT, SIGTERM};
846 bool server_started_{
false};
847 std::condition_variable cv_started_;
848 std::mutex start_mutex_;
849 std::vector<crow::websocket::connection*> websockets_;
854 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:604
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:415
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:758
void run()
Run the server.
Definition app.h:526
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition app.h:337
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:506
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:676
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:344
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition app.h:651
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:378
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition app.h:453
self_t & local_socket_path(std::string path)
Disable tcp/ip and use unix domain socket instead.
Definition app.h:364
void debug_print()
Print the routing paths defined for each HTTP method.
Definition app.h:641
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:358
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition app.h:301
bool is_bound() const
Get whether address that Crow will handle requests on is bound.
Definition app.h:332
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:384
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:440
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition app.h:351
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:520
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:664
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:372
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:406
void add_blueprint()
Apply blueprints.
Definition app.h:481
void address_is_bound()
Set status variable to note that the address that Crow will handle requests on is bound.
Definition app.h:327
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:422
std::uint16_t concurrency() const
Get the number of threads that server is using.
Definition app.h:393
std::future< void > run_async()
Non-blocking version of run()
Definition app.h:596
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