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>
258 ->
typename std::invoke_result<
decltype(&Router::new_rule_tagged<Tag>),
Router,
const std::string&>::type
260 return router_.new_rule_tagged<Tag>(rule);
266 return router_.catchall_rule();
272 max_payload_ = max_payload;
288 self_t& signal_add(
int signal_number)
290 signals_.push_back(signal_number);
294 std::vector<int> signals()
309 if (!server_started_)
313#ifdef CROW_ENABLE_SSL
316 return ssl_server_->port();
321 return server_->port();
355 return concurrency(std::thread::hardware_concurrency());
383 crow::logger::setLogLevel(level);
392 res_stream_threshold_ = threshold;
399 return res_stream_threshold_;
405 router_.register_blueprint(blueprint);
414 template<
typename Func>
417 router_.exception_handler() = std::forward<Func>(f);
423 return router_.exception_handler();
427 template<
typename Duration,
typename Func>
430 tick_interval_ = std::chrono::duration_cast<std::chrono::milliseconds>(d);
435#ifdef CROW_ENABLE_COMPRESSION
437 self_t& use_compression(compression::algorithm algorithm)
439 comp_algorithm_ = algorithm;
440 compression_used_ =
true;
444 compression::algorithm compression_algorithm()
446 return comp_algorithm_;
449 bool compression_used()
const
451 return compression_used_;
458#if defined(__APPLE__) || defined(__MACH__)
459 if (router_.blueprints().empty())
return;
462 for (
Blueprint* bp : router_.blueprints())
464 if (bp->static_dir().empty()) {
465 CROW_LOG_ERROR <<
"Blueprint " << bp->prefix() <<
" and its sub-blueprints ignored due to empty static directory.";
468 auto static_dir_ = crow::utility::normalize_path(bp->static_dir());
470 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) {
471 utility::sanitize_filename(file_path_partial);
477 router_.validate_bp();
483 if (are_static_routes_added())
return;
484 auto static_dir_ = crow::utility::normalize_path(CROW_STATIC_DIRECTORY);
486 route<crow::black_magic::get_parameter_tag(CROW_STATIC_ENDPOINT)>(CROW_STATIC_ENDPOINT)([static_dir_](
crow::response& res, std::string file_path_partial) {
487 utility::sanitize_filename(file_path_partial);
491 set_static_routes_added();
503#ifndef CROW_DISABLE_STATIC_DIR
510 asio::ip::address addr = asio::ip::make_address(bindaddr_,ec);
512 CROW_LOG_ERROR << ec.message() <<
" - Can not create valid ip address from string: \"" << bindaddr_ <<
"\"";
515 tcp::endpoint endpoint(addr, port_);
516#ifdef CROW_ENABLE_SSL
519 router_.using_ssl =
true;
520 ssl_server_ = std::move(std::unique_ptr<ssl_server_t>(
new ssl_server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_, &ssl_context_)));
521 ssl_server_->set_tick_function(tick_interval_, tick_function_);
522 ssl_server_->signal_clear();
523 for (
auto snum : signals_)
525 ssl_server_->signal_add(snum);
527 notify_server_start();
533 server_ = std::move(std::unique_ptr<server_t>(
new server_t(
this, endpoint, server_name_, &middlewares_, concurrency_, timeout_,
nullptr)));
534 server_->set_tick_function(tick_interval_, tick_function_);
535 for (
auto snum : signals_)
537 server_->signal_add(snum);
539 notify_server_start();
550 return std::async(std::launch::async, [&] {
558#ifdef CROW_ENABLE_SSL
561 if (ssl_server_) { ssl_server_->stop(); }
567 std::vector<crow::websocket::connection*> websockets_to_close = websockets_;
568 for (
auto websocket : websockets_to_close)
570 CROW_LOG_INFO <<
"Quitting Websocket: " << websocket;
571 websocket->close(
"Server Application Terminated");
573 if (server_) { server_->stop(); }
579 websockets_.push_back(conn);
584 websockets_.erase(std::remove(websockets_.begin(), websockets_.end(), conn), websockets_.end());
590 CROW_LOG_DEBUG <<
"Routing:";
591 router_.debug_print();
595#ifdef CROW_ENABLE_SSL
598 self_t&
ssl_file(
const std::string& crt_filename,
const std::string& key_filename)
601 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
602 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
603 ssl_context_.use_certificate_file(crt_filename, ssl_context_t::pem);
604 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
605 ssl_context_.set_options(
606 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
614 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
615 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
616 ssl_context_.load_verify_file(pem_filename);
617 ssl_context_.set_options(
618 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
626 ssl_context_.set_verify_mode(asio::ssl::verify_peer);
627 ssl_context_.set_verify_mode(asio::ssl::verify_client_once);
628 ssl_context_.use_certificate_chain_file(crt_filename);
629 ssl_context_.use_private_key_file(key_filename, ssl_context_t::pem);
630 ssl_context_.set_options(
631 asio::ssl::context::default_workarounds | asio::ssl::context::no_sslv2 | asio::ssl::context::no_sslv3);
635 self_t& ssl(asio::ssl::context&& ctx)
638 ssl_context_ = std::move(ctx);
642 bool ssl_used()
const
648 template<
typename T,
typename... Remain>
654 std::is_base_of<T, void>::value,
655 "Define CROW_ENABLE_SSL to enable ssl support.");
659 template<
typename T,
typename... Remain>
665 std::is_base_of<T, void>::value,
666 "Define CROW_ENABLE_SSL to enable ssl support.");
676 std::is_base_of<T, void>::value,
677 "Define CROW_ENABLE_SSL to enable ssl support.");
681 bool ssl_used()
const
688 using context_t = detail::context<Middlewares...>;
689 using mw_container_t = std::tuple<Middlewares...>;
691 typename T::context& get_context(
const request& req)
693 static_assert(black_magic::contains<T, Middlewares...>::value,
"App doesn't have the specified middleware type.");
694 auto& ctx = *
reinterpret_cast<context_t*
>(req.middleware_context);
695 return ctx.template get<T>();
701 return utility::get_element_by_type<T, Middlewares...>(middlewares_);
707 std::cv_status status = std::cv_status::no_timeout;
708 auto wait_until = std::chrono::steady_clock::now() + wait_timeout;
710 std::unique_lock<std::mutex> lock(start_mutex_);
711 while (!server_started_ && (status == std::cv_status::no_timeout))
713 status = cv_started_.wait_until(lock, wait_until);
717 if (status == std::cv_status::no_timeout)
721 status = server_->wait_for_start(wait_until);
723#ifdef CROW_ENABLE_SSL
724 else if (ssl_server_)
726 status = ssl_server_->wait_for_start(wait_until);
734 template<
typename... Ts>
735 std::tuple<Middlewares...> make_middleware_tuple(Ts&&... ts)
737 auto fwd = std::forward_as_tuple((ts)...);
738 return std::make_tuple(
739 std::forward<Middlewares>(
740 black_magic::tuple_extract<Middlewares,
decltype(fwd)>(fwd))...);
744 void notify_server_start()
746 std::unique_lock<std::mutex> lock(start_mutex_);
747 server_started_ =
true;
748 cv_started_.notify_all();
751 void set_static_routes_added() {
752 static_routes_added_ =
true;
755 bool are_static_routes_added() {
756 return static_routes_added_;
760 std::uint8_t timeout_{5};
762 uint16_t concurrency_ = 2;
763 uint64_t max_payload_{UINT64_MAX};
764 std::string server_name_ = std::string(
"Crow/") + VERSION;
765 std::string bindaddr_ =
"0.0.0.0";
766 size_t res_stream_threshold_ = 1048576;
768 bool static_routes_added_{
false};
770#ifdef CROW_ENABLE_COMPRESSION
771 compression::algorithm comp_algorithm_;
772 bool compression_used_{
false};
775 std::chrono::milliseconds tick_interval_;
776 std::function<void()> tick_function_;
778 std::tuple<Middlewares...> middlewares_;
780#ifdef CROW_ENABLE_SSL
781 std::unique_ptr<ssl_server_t> ssl_server_;
782 bool ssl_used_{
false};
783 ssl_context_t ssl_context_{asio::ssl::context::sslv23};
786 std::unique_ptr<server_t> server_;
788 std::vector<int> signals_{SIGINT, SIGTERM};
790 bool server_started_{
false};
791 std::condition_variable cv_started_;
792 std::mutex start_mutex_;
793 std::vector<crow::websocket::connection*> websockets_;
798 template<
typename... Middlewares>
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition routing.h:1091
The main server application class.
Definition app.h:199
void stop()
Stop the server.
Definition app.h:556
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:390
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:705
void run()
Run the server.
Definition app.h:501
self_t & timeout(std::uint8_t timeout)
Set the connection timeout in seconds (default is 5)
Definition app.h:326
uint64_t websocket_max_payload()
Get the default max payload size for websockets.
Definition app.h:277
void add_static_dir()
Go through the rules, upgrade them if possible, and add them to the list of rules.
Definition app.h:481
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:623
Server< Crow, SocketAdaptor, Middlewares... > server_t
The HTTP server.
Definition app.h:205
self_t & server_name(std::string server_name)
Set the server name.
Definition app.h:333
self_t & ssl_file(const std::string &crt_filename, const std::string &key_filename)
Use certificate and key files for SSL.
Definition app.h:598
void handle_upgrade(const request &req, response &res, Adaptor &&adaptor)
Process an Upgrade request.
Definition app.h:224
self_t & multithreaded()
Run the server on multiple threads using all available threads.
Definition app.h:353
self_t & tick(Duration d, Func f)
Set a custom duration and function to run on every tick.
Definition app.h:428
void debug_print()
Print the routing paths defined for each HTTP method.
Definition app.h:588
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
std::string bindaddr()
Get the address that Crow will handle requests on.
Definition app.h:347
self_t & port(std::uint16_t port)
Set the port that Crow will handle requests on.
Definition app.h:300
std::uint16_t port() const
Get the port that Crow will handle requests on.
Definition app.h:307
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:415
Server< Crow, SSLAdaptor, Middlewares... > ssl_server_t
An HTTP server that runs on SSL with an SSLAdaptor.
Definition app.h:209
self_t & bindaddr(std::string bindaddr)
The IP address that Crow will handle requests on (default is 0.0.0.0)
Definition app.h:340
void validate()
A wrapper for validate() in the router.
Definition app.h:495
Crow(Ts &&... ts)
Construct Crow with a subset of middleware.
Definition app.h:216
CatchallRule & catchall_route()
Create a route for any requests without a proper route (Use CROW_CATCHALL_ROUTE instead)
Definition app.h:264
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition app.h:270
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_file(const std::string &pem_filename)
Use .pem file for SSL.
Definition app.h:611
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
DynamicRule & route_dynamic(const std::string &rule)
Create a dynamic route using a rule (Use CROW_ROUTE instead)
Definition app.h:250
self_t & loglevel(LogLevel level)
Set the server's log level.
Definition app.h:381
self_t & concurrency(std::uint16_t concurrency)
Run the server on multiple threads using a specific number.
Definition app.h:359
void add_blueprint()
Apply blueprints.
Definition app.h:456
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:257
size_t & stream_threshold()
Get the response body size (in bytes) beyond which Crow automatically streams responses.
Definition app.h:397
std::uint16_t concurrency() const
Get the number of threads that server is using.
Definition app.h:368
std::future< void > run_async()
Non-blocking version of run()
Definition app.h:548
A rule that can change its parameters during runtime.
Definition routing.h:568
Handles matching requests to existing rules and upgrade requests.
Definition routing.h:1245
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