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
231 template<
typename... Ts>
233 middlewares_(make_middleware_tuple(std::forward<Ts>(ts)...))
239 template<
typename Adaptor>
242 router_.handle_upgrade(req, res, adaptor);
248 return router_.handle_initial(req, res);
254 router_.handle<
self_t>(req, res, *found);
261 if (found->rule_index || found->catch_all)
268 return router_.new_rule_dynamic(rule);
272 template<u
int64_t Tag>
274 ->
typename std::invoke_result<
decltype(&Router::new_rule_tagged<Tag>),
Router,
const std::string&>::type
276 return router_.new_rule_tagged<Tag>(rule);
299 rt([=,localFile=std::string(internalPath)](
crow::response& resp) ->
void {
310 return router_.catchall_rule();
316 max_payload_ = max_payload;
332 self_t& signal_add(
int signal_number)
334 signals_.push_back(signal_number);
338 std::vector<int> signals()
353 if (!server_started_)
357#ifdef CROW_ENABLE_SSL
360 return ssl_server_->port();
365 return server_->port();
423 return concurrency(std::thread::hardware_concurrency());
451 crow::logger::setLogLevel(level);
460 res_stream_threshold_ = threshold;
467 return res_stream_threshold_;
473 router_.register_blueprint(blueprint);
482 template<
typename Func>
485 router_.exception_handler() = std::forward<Func>(f);
491 return router_.exception_handler();
495 template<
typename Duration,
typename Func>
498 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
503#ifdef CROW_ENABLE_COMPRESSION
505 self_t& use_compression(compression::algorithm algorithm)
507 comp_algorithm_ = algorithm;
508 compression_used_ =
true;
512 compression::algorithm compression_algorithm()
514 return comp_algorithm_;
517 bool compression_used()
const
519 return compression_used_;
526#if defined(__APPLE__) || defined(__MACH__)
527 if (router_.blueprints().empty())
return;
530 for (
Blueprint* bp : router_.blueprints())
532 if (bp->static_dir().empty()) {
533 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
536 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
538 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) {
539 utility::sanitize_filename(file_path_partial);
545 router_.validate_bp();
551 if (are_static_routes_added())
return;
552 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
554 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](
crow::response& res, std::string file_path_partial) {
555 utility::sanitize_filename(file_path_partial);
559 set_static_routes_added();
571#ifndef CROW_DISABLE_STATIC_DIR
577#ifdef CROW_ENABLE_SSL
582 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
584 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
587 tcp::endpoint endpoint(addr, port_);
588 router_.using_ssl =
true;
589 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(
new ssl_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
590 ssl_server_->set_tick_function(tick_interval_, tick_function_);
591 ssl_server_->signal_clear();
592 for (
auto snum : signals_)
594 ssl_server_->signal_add(snum);
596 notify_server_start();
604 UnixSocketAcceptor::endpoint endpoint(bindaddr_);
605 unix_server_ = std::move(std::unique_ptr<unix_server_t>(
new unix_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
606 unix_server_->set_tick_function(tick_interval_, tick_function_);
607 for (
auto snum : signals_)
609 unix_server_->signal_add(snum);
611 notify_server_start();
617 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
619 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
622 TCPAcceptor::endpoint endpoint(addr, port_);
623 server_ = std::move(std::unique_ptr<server_t>(
new server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
624 server_->set_tick_function(tick_interval_, tick_function_);
625 for (
auto snum : signals_)
627 server_->signal_add(snum);
629 notify_server_start();
641 return std::async(std::launch::async, [&] {
649#ifdef CROW_ENABLE_SSL
652 if (ssl_server_) { ssl_server_->stop(); }
658 if (server_) { server_->stop(); }
659 if (unix_server_) { unix_server_->stop(); }
663 void close_websockets()
665 std::lock_guard<std::mutex> lock{websockets_mutex_};
666 for (
auto websocket : websockets_)
668 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
669 websocket->close(
"Websocket Closed");
674 void add_websocket(std::shared_ptr<websocket::connection> conn)
676 std::lock_guard<std::mutex> lock{websockets_mutex_};
677 websockets_.push_back(conn);
680 void remove_websocket(std::shared_ptr<websocket::connection> conn)
682 std::lock_guard<std::mutex> lock{websockets_mutex_};
683 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
689 CROW_LOG_DEBUG <<
"Routing:";
690 router_.debug_print();
694#ifdef CROW_ENABLE_SSL
697 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
700 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
701 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
702 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
703 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
704 ssl_context_.set_options(
705 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
713 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
714 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
715 ssl_context_.load_verify_file(pem_filename);
716 ssl_context_.set_options(
717 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
725 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
726 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
727 ssl_context_.use_certificate_chain_file(crt_filename);
728 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
729 ssl_context_.set_options(
730 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
734 self_t& ssl(asio::ssl::context&& ctx)
737 ssl_context_ = std::move(ctx);
741 bool ssl_used()
const
747 template<
typename T,
typename... Remain>
753 std::is_base_of<T, void>::value,
754 "Define CROW_ENABLE_SSL to enable ssl support.");
758 template<
typename T,
typename... Remain>
764 std::is_base_of<T, void>::value,
765 "Define CROW_ENABLE_SSL to enable ssl support.");
775 std::is_base_of<T, void>::value,
776 "Define CROW_ENABLE_SSL to enable ssl support.");
780 bool ssl_used()
const
787 using context_t = detail::context<Middlewares...>;
788 using mw_container_t = std::tuple<Middlewares...>;
790 typename T::context& get_context(
const request& req)
792 static_assert(black_magic::contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
793 auto& ctx = *
reinterpret_cast<context_t*
>(req.middleware_context);
794 return ctx.template get<T>();
800 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
806 std::cv_status status = std::cv_status::no_timeout;
807 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
809 std::unique_lock<std::mutex> lock(start_mutex_);
810 while (!server_started_ && (status == std::cv_status::no_timeout))
812 status = cv_started_.wait_until(lock, wait_until);
815 if (status == std::cv_status::no_timeout)
818 status = server_->wait_for_start(wait_until);
819 }
else if (unix_server_) {
820 status = unix_server_->wait_for_start(wait_until);
822#ifdef CROW_ENABLE_SSL
823 else if (ssl_server_)
825 status = ssl_server_->wait_for_start(wait_until);
833 template<
typename... Ts>
834 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
836 auto fwd = std::forward_as_tuple((ts)...);
837 return std::make_tuple(
838 std::forward<Middlewares>(
839 black_magic::tuple_extract<Middlewares,
decltype(fwd)>(fwd))...);
843 void notify_server_start()
845 std::unique_lock<std::mutex> lock(start_mutex_);
846 server_started_ =
true;
847 cv_started_.notify_all();
850 void set_static_routes_added() {
851 static_routes_added_ =
true;
854 bool are_static_routes_added() {
855 return static_routes_added_;
859 std::uint8_t timeout_{5};
861 unsigned int concurrency_ = 2;
862 std::atomic_bool is_bound_ =
false;
863 uint64_t max_payload_{UINT64_MAX};
864 std::string server_name_ = std::string(
"Crow/") + VERSION;
865 std::string bindaddr_ =
"0.0.0.0";
866 bool use_unix_ =
false;
867 size_t res_stream_threshold_ = 1048576;
869 bool static_routes_added_{
false};
871#ifdef CROW_ENABLE_COMPRESSION
872 compression::algorithm comp_algorithm_;
873 bool compression_used_{
false};
876 std::chrono::milliseconds tick_interval_;
877 std::function<void()> tick_function_;
879 std::tuple<Middlewares...> middlewares_;
881#ifdef CROW_ENABLE_SSL
882 std::unique_ptr<ssl_server_t> ssl_server_;
883 bool ssl_used_{
false};
884 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
887 std::unique_ptr<server_t> server_;
888 std::unique_ptr<unix_server_t> unix_server_;
890 std::vector<int> signals_{SIGINT, SIGTERM};
892 bool server_started_{
false};
893 std::condition_variable cv_started_;
894 std::mutex start_mutex_;
895 std::mutex websockets_mutex_;
896 std::vector<std::shared_ptr<websocket::connection>> websockets_;
901 template<
typename... Middlewares>
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition routing.h:1116
The main server application class.
Definition app.h:214
void stop()
Stop the server.
Definition app.h:647
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:458
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:804
void run()
Run the server.
Definition app.h:569
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition app.h:380
uint64_t websocket_max_payload()
Get the default max payload size for websockets.
Definition app.h:321
void add_static_dir()
Go through the rules, upgrade them if possible, and add them to the list of rules.
Definition app.h:549
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:284
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:722
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:387
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition app.h:697
void handle_upgrade(const request &req, response &res, Adaptor &&adaptor)
Process an Upgrade request.
Definition app.h:240
self_t & multithreaded()
Run the server on multiple threads using all available threads.
Definition app.h:421
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition app.h:496
self_t & local_socket_path(std::string path)
Disable tcp/ip and use unix domain socket instead.
Definition app.h:407
void debug_print()
Print the routing paths defined for each HTTP method.
Definition app.h:687
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:252
std::string bindaddr()
Get the address that Crow will handle requests on.
Definition app.h:401
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition app.h:344
bool is_bound() const
Get whether address that Crow will handle requests on is bound.
Definition app.h:375
std::uint16_t port() const
Get the port that Crow will handle requests on.
Definition app.h:351
self_t & concurrency(unsigned int concurrency)
Run the server on multiple threads using a specific number.
Definition app.h:427
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:483
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition app.h:394
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:563
Crow(Ts &&... ts)
Construct Crow with a subset of middleware.
Definition app.h:232
CatchallRule & catchall_route()
Create a route for any requests without a proper route (Use CROW_CATCHALL_ROUTE instead)
Definition app.h:308
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition app.h:314
void handle_full(request &req, response &res)
Process a fully parsed request from start to finish (primarily used for debugging)
Definition app.h:258
StaticRule & static_file(std::string_view url, std::string_view internalPath)
Creates a static route for given url to internalPath.
Definition app.h:295
self_t & ssl_file(const std::string &pem_filename)
Use .pem file for SSL.
Definition app.h:710
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:246
std::string local_socket_path()
Get the unix domain socket path.
Definition app.h:415
DynamicRule & route_dynamic(const std::string &rule)
Create a dynamic route using a rule (Use CROW_ROUTE instead)
Definition app.h:266
self_t & loglevel(LogLevel level)
Set the server's log level.
Definition app.h:449
void add_blueprint()
Apply blueprints.
Definition app.h:524
void address_is_bound()
Set status variable to note that the address that Crow will handle requests on is bound.
Definition app.h:370
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:273
size_t & stream_threshold()
Get the response body size (in bytes) beyond which Crow automatically streams responses.
Definition app.h:465
std::uint16_t concurrency() const
Get the number of threads that server is using.
Definition app.h:436
std::future< void > run_async()
Non-blocking version of run()
Definition app.h:639
A rule that can change its parameters during runtime.
Definition routing.h:592
Handles matching requests to existing rules and upgrade requests.
Definition routing.h:1270
Definition http_server.h:46
Default rule created when CROW_ROUTE is called.
Definition routing.h:669
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
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