6 #include <unordered_map>
10 #include <type_traits>
12 #include "crow/common.h"
13 #include "crow/http_response.h"
14 #include "crow/http_request.h"
15 #include "crow/utility.h"
16 #include "crow/logging.h"
17 #include "crow/exceptions.h"
18 #include "crow/websocket.h"
20 #include "crow/middleware.h"
25 constexpr
const uint16_t INVALID_BP_ID{((uint16_t)-1)};
32 template<
typename App>
36 template<
typename App,
typename MW,
typename... Middlewares>
39 using MwContainer =
typename App::mw_container_t;
40 static_assert(black_magic::has_type<MW, MwContainer>::value,
"Middleware must be present in app");
41 static_assert(std::is_base_of<crow::ILocalMiddleware, MW>::value,
"Middleware must extend ILocalMiddleware");
42 int idx = black_magic::tuple_index<MW, MwContainer>::value;
43 indices_.push_back(idx);
44 push<
App, Middlewares...>();
49 indices_.insert(indices_.begin(), other.indices_.cbegin(), other.indices_.cend());
54 indices_.insert(indices_.end(), other.indices_.cbegin(), other.indices_.cend());
59 indices_.resize(indices_.size() - other.indices_.size());
64 return indices_.empty();
70 std::sort(indices_.begin(), indices_.end());
71 indices_.erase(std::unique(indices_.begin(), indices_.end()), indices_.end());
74 const std::vector<int>& indices()
80 std::vector<int> indices_;
93 rule_(std::move(rule))
99 virtual void validate() = 0;
111 std::unique_ptr<BaseRule> upgrade()
113 if (rule_to_upgrade_)
114 return std::move(rule_to_upgrade_);
124 #ifdef CROW_ENABLE_SSL
132 uint32_t get_methods()
138 void foreach_method(F f)
140 for (uint32_t method = 0, method_bit = 1; method < static_cast<uint32_t>(HTTPMethod::InternalMethodCount); method++, method_bit <<= 1)
142 if (methods_ & method_bit)
147 std::string custom_templates_base;
149 const std::string& rule() {
return rule_; }
152 uint32_t methods_{1 <<
static_cast<int>(HTTPMethod::Get)};
158 std::unique_ptr<BaseRule> rule_to_upgrade_;
171 namespace routing_handler_call_helper
173 template<
typename T,
int Pos>
177 static const int pos = Pos;
180 template<
typename H1>
184 const routing_params& params;
189 template<
typename F,
int NInt,
int NU
int,
int NDouble,
int NString,
typename S1,
typename S2>
193 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
194 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>, black_magic::S<Args2...>>
196 void operator()(F cparams)
198 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<int64_t, NInt>>;
199 call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
203 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
204 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<uint64_t, Args1...>, black_magic::S<Args2...>>
206 void operator()(F cparams)
208 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<uint64_t, NUint>>;
209 call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
213 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
214 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>, black_magic::S<Args2...>>
216 void operator()(F cparams)
218 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<double, NDouble>>;
219 call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>, pushed>()(cparams);
223 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
224 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<std::string, Args1...>, black_magic::S<Args2...>>
226 void operator()(F cparams)
228 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<std::string, NString>>;
229 call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>, pushed>()(cparams);
233 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1>
234 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<>, black_magic::S<Args1...>>
236 void operator()(F cparams)
241 cparams.params.template get<typename Args1::type>(Args1::pos)...);
245 template<
typename Func,
typename... ArgsWrapped>
248 template<
typename... Args>
249 void set_(Func f,
typename std::enable_if<!std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
const request&>::value,
int>::type = 0)
252 #ifdef CROW_CAN_USE_CPP14
263 template<
typename Req,
typename... Args>
280 template<
typename... Args>
281 void set_(Func f,
typename std::enable_if<
282 std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
const request&>::value &&
283 !std::is_same<
typename std::tuple_element<1, std::tuple<Args..., void, void>>::type,
response&>::value,
295 template<
typename... Args>
296 void set_(Func f,
typename std::enable_if<
297 std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
const request&>::value &&
298 std::is_same<
typename std::tuple_element<1, std::tuple<Args..., void, void>>::type,
response&>::value,
301 handler_ = std::move(f);
304 template<
typename... Args>
308 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
311 template<
typename... Args>
315 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
318 template<
typename... Args>
322 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
327 void operator()(
request& req,
response& res,
const routing_params& params)
336 decltype(handler_)>{handler_, params, req, res});
350 template<
typename Func>
351 typename std::enable_if<black_magic::CallHelper<Func, black_magic::S<>>::value,
void>::type
354 static_assert(!std::is_same<
void, decltype(f())>::value,
355 "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
358 #ifdef CROW_CAN_USE_CPP14
369 template<
typename Func>
370 typename std::enable_if<
371 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
372 black_magic::CallHelper<Func, black_magic::S<crow::request>>::value,
376 static_assert(!std::is_same<
void, decltype(f(std::declval<crow::request>()))>::value,
377 "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
380 #ifdef CROW_CAN_USE_CPP14
391 template<
typename Func>
392 typename std::enable_if<
393 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
394 !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
395 black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
399 static_assert(std::is_same<
void, decltype(f(std::declval<crow::response&>()))>::value,
400 "Handler function with response argument should have void return type");
402 #ifdef CROW_CAN_USE_CPP14
412 template<
typename Func>
413 typename std::enable_if<
414 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
415 !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
416 !black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
420 static_assert(std::is_same<
void, decltype(f(std::declval<crow::request>(), std::declval<crow::response&>()))>::value,
421 "Handler function with response argument should have void return type");
423 handler_ = std::move(f);
428 return (handler_ !=
nullptr);
443 template<
typename App>
452 max_payload_(UINT64_MAX)
455 void validate()
override
467 new crow::websocket::Connection<SocketAdaptor, App>(req, std::move(adaptor), app_, max_payload_, subprotocols_, open_handler_, message_handler_, close_handler_, error_handler_, accept_handler_);
469 #ifdef CROW_ENABLE_SSL
472 new crow::websocket::Connection<SSLAdaptor, App>(req, std::move(adaptor), app_, max_payload_, subprotocols_, open_handler_, message_handler_, close_handler_, error_handler_, accept_handler_);
480 max_payload_override_ =
true;
484 self_t& subprotocols(
const std::vector<std::string>& subprotocols)
486 subprotocols_ = subprotocols;
490 template<
typename Func>
491 self_t& onopen(Func f)
497 template<
typename Func>
498 self_t& onmessage(Func f)
500 message_handler_ = f;
504 template<
typename Func>
505 self_t& onclose(Func f)
511 template<
typename Func>
512 self_t& onerror(Func f)
518 template<
typename Func>
519 self_t& onaccept(Func f)
531 std::function<bool(
const crow::request&,
void**)> accept_handler_;
532 uint64_t max_payload_;
533 bool max_payload_override_ =
false;
534 std::vector<std::string> subprotocols_;
546 template<
typename App>
550 static_cast<self_t*
>(
this)->rule_to_upgrade_.reset(p);
554 self_t& name(std::string name) noexcept
556 static_cast<self_t*
>(
this)->name_ = std::move(name);
557 return static_cast<self_t&
>(*this);
560 self_t& methods(HTTPMethod method)
562 static_cast<self_t*
>(
this)->methods_ = 1 <<
static_cast<int>(method);
563 return static_cast<self_t&
>(*this);
566 template<
typename... MethodArgs>
567 self_t& methods(HTTPMethod method, MethodArgs... args_method)
569 methods(args_method...);
570 static_cast<self_t*
>(
this)->methods_ |= 1 <<
static_cast<int>(method);
571 return static_cast<self_t&
>(*this);
575 template<
typename App,
typename... Middlewares>
578 static_cast<self_t*
>(
this)->mw_indices_.template push<App, Middlewares...>();
579 return static_cast<self_t&
>(*this);
591 void validate()
override
593 if (!erased_handler_)
595 throw std::runtime_error(name_ + (!name_.empty() ?
": " :
"") +
"no handler for url " + rule_);
599 void handle(
request& req,
response& res,
const routing_params& params)
override
601 if (!custom_templates_base.empty())
603 else if (mustache::detail::get_template_base_directory_ref() !=
"templates")
605 erased_handler_(req, res, params);
608 template<
typename Func>
609 void operator()(Func f)
611 #ifdef CROW_MSVC_WORKAROUND
612 using function_t = utility::function_traits<decltype(&Func::operator())>;
614 using function_t = utility::function_traits<Func>;
616 erased_handler_ = wrap(std::move(f), black_magic::gen_seq<function_t::arity>());
622 #ifdef CROW_MSVC_WORKAROUND
623 template<
typename Func,
size_t... Indices>
625 template<
typename Func,
unsigned... Indices>
628 wrap(Func f, black_magic::seq<Indices...>)
630 #ifdef CROW_MSVC_WORKAROUND
631 using function_t = utility::function_traits<decltype(&Func::operator())>;
633 using function_t = utility::function_traits<Func>;
635 if (!black_magic::is_parameter_tag_compatible(
636 black_magic::get_parameter_tag_runtime(rule_.c_str()),
637 black_magic::compute_parameter_tag_from_args_list<
638 typename function_t::template arg<Indices>...>::value))
640 throw std::runtime_error(
"route_dynamic: Handler type is mismatched with URL parameters: " + rule_);
644 typename function_t::template arg<Indices>...>(std::move(f));
648 template<
typename Func>
649 void operator()(std::string name, Func&& f)
651 name_ = std::move(name);
652 (*this).template operator()<Func>(std::forward(f));
656 std::function<void(
request&,
response&,
const routing_params&)> erased_handler_;
660 template<
typename... Args>
670 void validate()
override
672 if (rule_.at(0) !=
'/')
673 throw std::runtime_error(
"Internal error: Routes must start with a '/'");
677 throw std::runtime_error(name_ + (!name_.empty() ?
": " :
"") +
"no handler for url " + rule_);
681 template<
typename Func>
682 void operator()(Func&& f)
685 #ifdef CROW_CAN_USE_CPP14
691 detail::wrapped_handler_call(req, res, f, std::forward<Args>(args)...);
695 template<
typename Func>
696 void operator()(std::string name, Func&& f)
698 name_ = std::move(name);
699 (*this).template operator()<Func>(std::forward(f));
702 void handle(
request& req,
response& res,
const routing_params& params)
override
704 if (!custom_templates_base.empty())
706 else if (mustache::detail::get_template_base_directory_ref() != mustache::detail::get_global_template_base_directory_ref())
712 black_magic::S<Args...>,
721 const int RULE_SPECIAL_REDIRECT_SLASH = 1;
730 uint16_t rule_index{};
732 uint16_t blueprint_index{INVALID_BP_ID};
734 ParamType param = ParamType::MAX;
735 std::vector<Node> children;
737 bool IsSimpleNode()
const
739 return !rule_index &&
740 blueprint_index == INVALID_BP_ID &&
741 children.size() < 2 &&
742 param == ParamType::MAX &&
743 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
744 return x.param == ParamType::MAX;
748 Node& add_child_node()
750 children.emplace_back();
751 return children.back();
762 return head_.children.empty();
767 for (
auto& child : head_.children)
775 void optimizeNode(Node& node)
777 if (node.children.empty())
779 if (node.IsSimpleNode())
781 auto children_temp = std::move(node.children);
782 auto& child_temp = children_temp[0];
783 node.key += child_temp.key;
784 node.rule_index = child_temp.rule_index;
785 node.blueprint_index = child_temp.blueprint_index;
786 node.children = std::move(child_temp.children);
791 for (
auto& child : node.children)
798 void debug_node_print(
const Node& node,
int level)
800 if (node.param != ParamType::MAX)
805 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
808 case ParamType::UINT:
809 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
812 case ParamType::DOUBLE:
813 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
816 case ParamType::STRING:
817 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
820 case ParamType::PATH:
821 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
825 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
831 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
833 for (
const auto& child : node.children)
835 debug_node_print(child, level + 1);
842 CROW_LOG_DEBUG <<
"└➙ ROOT";
843 for (
const auto& child : head_.children)
844 debug_node_print(child, 1);
849 if (!head_.IsSimpleNode())
850 throw std::runtime_error(
"Internal error: Trie header should be simple!");
855 routing_handle_result find(
const std::string& req_url,
const Node& node,
unsigned pos = 0, routing_params* params =
nullptr, std::vector<uint16_t>* blueprints =
nullptr)
const
858 routing_params empty;
859 if (params ==
nullptr)
862 std::vector<uint16_t> MT;
863 if (blueprints ==
nullptr)
867 std::vector<uint16_t> found_BP;
868 routing_params match_params;
870 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
871 found_BP = std::move(ret.blueprint_indices);
872 if (ret.rule_index && (!found || found > ret.rule_index))
874 found = ret.rule_index;
875 match_params = std::move(ret.r_params);
880 if (pos == req_url.size())
882 found_BP = std::move(*blueprints);
883 return routing_handle_result{node.rule_index, *blueprints, *params};
886 bool found_fragment =
false;
888 for (
const auto& child : node.children)
890 if (child.param != ParamType::MAX)
892 if (child.param == ParamType::INT)
894 char c = req_url[pos];
895 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
899 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
900 if (errno != ERANGE && eptr != req_url.data() + pos)
902 found_fragment =
true;
903 params->int_params.push_back(value);
904 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
905 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
907 params->int_params.pop_back();
908 if (!blueprints->empty()) blueprints->pop_back();
913 else if (child.param == ParamType::UINT)
915 char c = req_url[pos];
916 if ((c >=
'0' && c <=
'9') || c ==
'+')
920 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
921 if (errno != ERANGE && eptr != req_url.data() + pos)
923 found_fragment =
true;
924 params->uint_params.push_back(value);
925 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
926 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
928 params->uint_params.pop_back();
929 if (!blueprints->empty()) blueprints->pop_back();
934 else if (child.param == ParamType::DOUBLE)
936 char c = req_url[pos];
937 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
941 double value = strtod(req_url.data() + pos, &eptr);
942 if (errno != ERANGE && eptr != req_url.data() + pos)
944 found_fragment =
true;
945 params->double_params.push_back(value);
946 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
947 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
949 params->double_params.pop_back();
950 if (!blueprints->empty()) blueprints->pop_back();
955 else if (child.param == ParamType::STRING)
958 for (; epos < req_url.size(); epos++)
960 if (req_url[epos] ==
'/')
966 found_fragment =
true;
967 params->string_params.push_back(req_url.substr(pos, epos - pos));
968 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
969 auto ret = find(req_url, child, epos, params, blueprints);
971 params->string_params.pop_back();
972 if (!blueprints->empty()) blueprints->pop_back();
976 else if (child.param == ParamType::PATH)
978 size_t epos = req_url.size();
982 found_fragment =
true;
983 params->string_params.push_back(req_url.substr(pos, epos - pos));
984 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
985 auto ret = find(req_url, child, epos, params, blueprints);
987 params->string_params.pop_back();
988 if (!blueprints->empty()) blueprints->pop_back();
995 const std::string& fragment = child.key;
996 if (req_url.compare(pos, fragment.size(), fragment) == 0)
998 found_fragment =
true;
999 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1000 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
1002 if (!blueprints->empty()) blueprints->pop_back();
1007 if (!found_fragment)
1008 found_BP = std::move(*blueprints);
1010 return routing_handle_result{found, found_BP, match_params};
1013 routing_handle_result find(
const std::string& req_url)
const
1015 return find(req_url, head_);
1019 void add(
const std::string& url, uint16_t rule_index,
unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
1023 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1025 for (
unsigned i = 0; i < url.size(); i++)
1030 static struct ParamTraits
1036 {ParamType::INT,
"<int>"},
1037 {ParamType::UINT,
"<uint>"},
1038 {ParamType::DOUBLE,
"<float>"},
1039 {ParamType::DOUBLE,
"<double>"},
1040 {ParamType::STRING,
"<str>"},
1041 {ParamType::STRING,
"<string>"},
1042 {ParamType::PATH,
"<path>"},
1045 for (
const auto& x : paramTraits)
1047 if (url.compare(i, x.name.size(), x.name) == 0)
1050 for (
auto& child : idx->children)
1052 if (child.param == x.type)
1063 auto new_node_idx = &idx->add_child_node();
1064 new_node_idx->param = x.type;
1076 bool piece_found =
false;
1077 for (
auto& child : idx->children)
1079 if (child.key[0] == c)
1088 auto new_node_idx = &idx->add_child_node();
1089 new_node_idx->key = c;
1091 if (has_blueprint && i == bp_prefix_length)
1092 new_node_idx->blueprint_index = blueprint_index;
1099 if (idx->rule_index)
1100 throw std::runtime_error(
"handler already exists for " + url);
1101 idx->rule_index = rule_index;
1118 static_dir_(prefix),
1119 templates_dir_(prefix){};
1121 Blueprint(
const std::string& prefix,
const std::string& static_dir):
1122 prefix_(prefix), static_dir_(static_dir){};
1124 Blueprint(
const std::string& prefix,
const std::string& static_dir,
const std::string& templates_dir):
1125 prefix_(prefix), static_dir_(static_dir), templates_dir_(templates_dir){};
1142 *
this = std::move(value);
1149 prefix_ = std::move(value.prefix_);
1150 static_dir_ = std::move(value.static_dir_);
1151 templates_dir_ = std::move(value.templates_dir_);
1152 all_rules_ = std::move(value.all_rules_);
1153 catchall_rule_ = std::move(value.catchall_rule_);
1154 blueprints_ = std::move(value.blueprints_);
1155 mw_indices_ = std::move(value.mw_indices_);
1161 return value.prefix() == prefix_;
1166 return value.prefix() != prefix_;
1169 std::string prefix()
const
1174 std::string static_dir()
const
1189 DynamicRule& new_rule_dynamic(
const std::string& rule)
1191 std::string new_rule =
'/' + prefix_ + rule;
1192 auto ruleObject =
new DynamicRule(std::move(new_rule));
1193 ruleObject->custom_templates_base = templates_dir_;
1194 all_rules_.emplace_back(ruleObject);
1199 template<u
int64_t N>
1200 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1202 std::string new_rule =
'/' + prefix_ + rule;
1203 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1205 auto ruleObject =
new RuleT(std::move(new_rule));
1206 ruleObject->custom_templates_base = templates_dir_;
1207 all_rules_.emplace_back(ruleObject);
1212 void register_blueprint(
Blueprint& blueprint)
1214 if (blueprints_.empty() || std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1216 apply_blueprint(blueprint);
1217 blueprints_.emplace_back(&blueprint);
1220 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in blueprint \"" + prefix_ +
'\"');
1226 return catchall_rule_;
1229 template<
typename App,
typename... Middlewares>
1232 mw_indices_.push<
App, Middlewares...>();
1236 void apply_blueprint(
Blueprint& blueprint)
1239 blueprint.prefix_ = prefix_ +
'/' + blueprint.prefix_;
1240 blueprint.static_dir_ = static_dir_ +
'/' + blueprint.static_dir_;
1241 blueprint.templates_dir_ = templates_dir_ +
'/' + blueprint.templates_dir_;
1242 for (
auto& rule : blueprint.all_rules_)
1244 std::string new_rule =
'/' + prefix_ + rule->rule_;
1245 rule->rule_ = new_rule;
1247 for (
Blueprint* bp_child : blueprint.blueprints_)
1250 apply_blueprint(bp_ref);
1254 std::string prefix_;
1255 std::string static_dir_;
1256 std::string templates_dir_;
1257 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1259 std::vector<Blueprint*> blueprints_;
1272 Router() : using_ssl(
false)
1275 DynamicRule& new_rule_dynamic(
const std::string& rule)
1278 all_rules_.emplace_back(ruleObject);
1283 template<u
int64_t N>
1284 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1286 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1288 auto ruleObject =
new RuleT(rule);
1289 all_rules_.emplace_back(ruleObject);
1296 return catchall_rule_;
1299 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1301 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1304 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
1306 bool has_trailing_slash =
false;
1307 std::string rule_without_trailing_slash;
1308 if (rule.size() > 1 && rule.back() ==
'/')
1310 has_trailing_slash =
true;
1311 rule_without_trailing_slash = rule;
1312 rule_without_trailing_slash.pop_back();
1315 ruleObject->mw_indices_.pack();
1317 ruleObject->foreach_method([&](
int method) {
1318 per_methods_[method].rules.emplace_back(ruleObject);
1319 per_methods_[method].trie.add(rule, per_methods_[method].rules.size() - 1, BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0, BP_index);
1323 if (has_trailing_slash)
1325 per_methods_[method].trie.add(rule_without_trailing_slash, RULE_SPECIAL_REDIRECT_SLASH, BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0, BP_index);
1329 ruleObject->set_added();
1332 void register_blueprint(
Blueprint& blueprint)
1334 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1336 blueprints_.emplace_back(&blueprint);
1339 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1342 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1345 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1347 for (
Blueprint* bp : blueprint->blueprints_)
1349 get_recursive_child_methods(bp, methods);
1352 else if (!blueprint->static_dir_.empty())
1353 methods.emplace_back(HTTPMethod::Get);
1354 for (
auto& rule : blueprint->all_rules_)
1356 rule->foreach_method([&methods](
unsigned method) {
1357 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1358 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1359 methods.emplace_back(method_final);
1368 validate_bp(blueprints_, blueprint_mw);
1373 for (
unsigned i = 0; i < blueprints.size(); i++)
1377 if (blueprint->is_added())
continue;
1379 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1381 std::vector<HTTPMethod> methods;
1382 get_recursive_child_methods(blueprint, methods);
1383 for (HTTPMethod x : methods)
1385 int method_index =
static_cast<int>(x);
1386 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1390 current_mw.merge_back(blueprint->mw_indices_);
1391 for (
auto& rule : blueprint->all_rules_)
1393 if (rule && !rule->is_added())
1395 auto upgraded = rule->upgrade();
1397 rule = std::move(upgraded);
1399 rule->mw_indices_.merge_front(current_mw);
1400 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1403 validate_bp(blueprint->blueprints_, current_mw);
1404 current_mw.pop_back(blueprint->mw_indices_);
1405 blueprint->set_added();
1411 for (
auto& rule : all_rules_)
1413 if (rule && !rule->is_added())
1415 auto upgraded = rule->upgrade();
1417 rule = std::move(upgraded);
1419 internal_add_rule_object(rule->rule(), rule.get());
1422 for (
auto& per_method : per_methods_)
1424 per_method.trie.validate();
1429 template<
typename Adaptor>
1430 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1432 if (req.method >= HTTPMethod::InternalMethodCount)
1435 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1436 auto& rules = per_method.rules;
1437 unsigned rule_index = per_method.trie.find(req.
url).rule_index;
1441 for (
auto& method : per_methods_)
1443 if (method.trie.find(req.
url).rule_index)
1445 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1452 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1458 if (rule_index >= rules.size())
1459 throw std::runtime_error(
"Trie internal structure corrupted!");
1461 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1463 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1467 if (req.get_header_value(
"Host").empty())
1473 res.
add_header(
"Location", (using_ssl ?
"https://" :
"http://") + req.get_header_value(
"Host") + req.
url +
"/");
1479 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1483 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1487 exception_handler_(res);
1493 void get_found_bp(std::vector<uint16_t>& bp_i, std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
1503 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1505 bp_i[index] < blueprints.size() &&
1506 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1508 if (index < bp_i.size())
1511 if (verify_prefix())
1513 found_bps.push_back(blueprints[bp_i[index]]);
1514 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1518 if (found_bps.size() < 2)
1521 found_bps.push_back(blueprints_[bp_i[index]]);
1525 found_bps.pop_back();
1526 Blueprint* last_element = found_bps.back();
1527 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1529 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1538 std::vector<Blueprint*> bps_found;
1539 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1540 for (
int i = bps_found.size() - 1; i > 0; i--)
1542 std::vector<uint16_t> bpi = found.blueprint_indices;
1543 if (bps_found[i]->catchall_rule().has_handler())
1547 bps_found[i]->catchall_rule().handler_(req, res);
1551 exception_handler_(res);
1553 #ifdef CROW_ENABLE_DEBUG
1554 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1556 return std::string();
1560 if (catchall_rule_.has_handler())
1564 catchall_rule_.handler_(req, res);
1568 exception_handler_(res);
1570 #ifdef CROW_ENABLE_DEBUG
1571 return std::string(
"Redirected to global Catchall rule");
1573 return std::string();
1576 return std::string();
1579 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1581 HTTPMethod method_actual = req.method;
1583 std::unique_ptr<routing_handle_result> found{
1586 std::vector<uint16_t>(),
1588 HTTPMethod::InternalMethodCount)};
1591 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1593 else if (req.method == HTTPMethod::Head)
1595 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1597 if (!found->rule_index)
1599 method_actual = HTTPMethod::Get;
1600 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1601 if (!found->rule_index)
1603 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1604 res = response(404);
1611 found->method = method_actual;
1614 else if (req.method == HTTPMethod::Options)
1616 std::string allow =
"OPTIONS, HEAD, ";
1618 if (req.
url ==
"/*")
1620 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1622 if (
static_cast<int>(HTTPMethod::Head) == i)
1625 if (!per_methods_[i].trie.is_empty())
1627 allow += method_name(
static_cast<HTTPMethod
>(i)) +
", ";
1630 allow = allow.substr(0, allow.size() - 2);
1631 res = response(204);
1634 found->method = method_actual;
1639 bool rules_matched =
false;
1640 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1642 if (per_methods_[i].trie.find(req.
url).rule_index)
1644 rules_matched =
true;
1646 if (
static_cast<int>(HTTPMethod::Head) == i)
1649 allow += method_name(
static_cast<HTTPMethod
>(i)) +
", ";
1654 allow = allow.substr(0, allow.size() - 2);
1655 res = response(204);
1658 found->method = method_actual;
1663 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1664 res = response(404);
1672 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1674 if (!found->rule_index)
1676 for (
auto& per_method : per_methods_)
1678 if (per_method.trie.find(req.
url).rule_index)
1680 const std::string error_message(
get_error(405, *found, req, res));
1681 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(method_actual) <<
". " << error_message;
1688 const std::string error_message(
get_error(404, *found, req, res));
1689 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << error_message;
1694 found->method = method_actual;
1699 template<
typename App>
1700 void handle(request& req, response& res, routing_handle_result found)
1702 HTTPMethod method_actual = found.method;
1703 auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1704 unsigned rule_index = found.rule_index;
1706 if (rule_index >= rules.size())
1707 throw std::runtime_error(
"Trie internal structure corrupted!");
1709 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1711 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.url;
1712 res = response(301);
1715 if (req.get_header_value(
"Host").empty())
1717 res.add_header(
"Location", req.url +
"/");
1721 res.add_header(
"Location", (using_ssl ?
"https://" :
"http://") + req.get_header_value(
"Host") + req.url +
"/");
1727 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1731 auto& rule = rules[rule_index];
1732 handle_rule<App>(rule, req, res, found.r_params);
1736 exception_handler_(res);
1742 template<
typename App>
1743 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1746 if (!rule->mw_indices_.empty())
1748 auto& ctx = *
reinterpret_cast<typename App::context_t*
>(req.middleware_context);
1749 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1750 detail::middleware_call_criteria_dynamic<false> crit_fwd(rule->mw_indices_.indices());
1752 auto glob_completion_handler = std::move(res.complete_request_handler_);
1753 res.complete_request_handler_ = [] {};
1755 detail::middleware_call_helper<decltype(crit_fwd),
1756 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1760 glob_completion_handler();
1764 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1765 detail::middleware_call_criteria_dynamic<true> crit_bwd(rule->mw_indices_.indices());
1767 detail::after_handlers_call_helper<
1769 std::tuple_size<typename App::mw_container_t>::value - 1,
1770 typename App::context_t,
1771 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1772 glob_completion_handler();
1775 rule->handle(req, res, rp);
1778 template<
typename App>
1779 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1782 rule->handle(req, res, rp);
1787 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1789 Trie& trie_ = per_methods_[i].trie;
1790 if (!trie_.is_empty())
1792 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1793 trie_.debug_print();
1798 std::vector<Blueprint*>& blueprints()
1805 return exception_handler_;
1808 static void default_exception_handler(response& res)
1811 res = response(500);
1817 catch (
const bad_request& e)
1819 res = response (400);
1820 res.body = e.what();
1822 catch (
const std::exception& e)
1824 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1828 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1833 CatchallRule catchall_rule_;
1837 std::vector<BaseRule*> rules;
1844 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1845 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1846 std::vector<Blueprint*> blueprints_;
1847 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;
A base class for all rules.
Definition: routing.h:90
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conce...
Definition: routing.h:1114
Definition: routing.h:345
The main server application class.
Definition: app.h:199
self_t & websocket_max_payload(uint64_t max_payload)
Set the default max payload size for websockets.
Definition: app.h:278
A rule that can change its parameters during runtime.
Definition: routing.h:585
Handles matching requests to existing rules and upgrade requests.
Definition: routing.h:1268
std::string get_error(unsigned short code, routing_handle_result &found, const request &req, response &res)
Is used to handle errors, you insert the error code, found route, request, and response....
Definition: routing.h:1535
Default rule created when CROW_ROUTE is called.
Definition: routing.h:662
A search tree.
Definition: routing.h:726
bool is_empty()
Check whether or not the trie is empty.
Definition: routing.h:760
A rule dealing with websockets.
Definition: routing.h:445
self_t & max_payload(uint64_t max_payload)
Override the global payload limit for this single WebSocket rule.
Definition: routing.h:477
A websocket connection.
Definition: websocket.h:106
This file includes the definition of the crow::mustache namespace and its members.
void set_base(const std::string &path)
Defines the templates directory path at route level. By default is templates/.
Definition: mustache.h:738
The main namespace of the library. In this namespace is defined the most important classes and functi...
Crow< Middlewares... > App
Alias of Crow<Middlewares...>. Useful if you want a instance of an Crow application that require Midd...
Definition: app.h:787
Allows the user to assign parameters using functions.
Definition: routing.h:543
self_t & middlewares()
Enable local middleware for this handler.
Definition: routing.h:576
Definition: socket_adaptors.h:107
A wrapper for the asio::ip::tcp::socket and asio::ssl::stream.
Definition: socket_adaptors.h:39
Definition: routing.h:729
Typesafe wrapper for storing lists of middleware as their indices in the App.
Definition: routing.h:31
Definition: routing.h:306
Definition: routing.h:265
Definition: routing.h:247
Definition: routing.h:175
Definition: routing.h:182
Definition: routing.h:191
An HTTP request.
Definition: http_request.h:36
std::string url
The endpoint without any parameters.
Definition: http_request.h:39
HTTP response.
Definition: http_response.h:34
void add_header(std::string key, std::string value)
Add a new header to the response.
Definition: http_response.h:58
bool skip_body
Whether this is a response to a HEAD request.
Definition: http_response.h:47
int code
The Status code for the response.
Definition: http_response.h:40
void set_header(std::string key, std::string value)
Set the value of an existing header in the response.
Definition: http_response.h:51
void end()
Set the response completion flag and call the handler (to send the response).
Definition: http_response.h:237
A base class for websocket connection.
Definition: websocket.h:62