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/websocket.h"
18 #include "crow/mustache.h"
19 #include "crow/middleware.h"
24 constexpr
const uint16_t INVALID_BP_ID{((uint16_t)-1)};
31 template<
typename App>
35 template<
typename App,
typename MW,
typename... Middlewares>
38 using MwContainer =
typename App::mw_container_t;
39 static_assert(black_magic::has_type<MW, MwContainer>::value,
"Middleware must be present in app");
40 static_assert(std::is_base_of<crow::ILocalMiddleware, MW>::value,
"Middleware must extend ILocalMiddleware");
41 int idx = black_magic::tuple_index<MW, MwContainer>::value;
42 indices_.push_back(idx);
43 push<
App, Middlewares...>();
48 indices_.insert(indices_.begin(), other.indices_.cbegin(), other.indices_.cend());
53 indices_.insert(indices_.end(), other.indices_.cbegin(), other.indices_.cend());
58 indices_.resize(indices_.size() - other.indices_.size());
63 return indices_.empty();
69 std::sort(indices_.begin(), indices_.end());
70 indices_.erase(std::unique(indices_.begin(), indices_.end()), indices_.end());
73 const std::vector<int>& indices()
79 std::vector<int> indices_;
92 rule_(std::move(rule))
98 virtual void validate() = 0;
108 std::unique_ptr<BaseRule> upgrade()
110 if (rule_to_upgrade_)
111 return std::move(rule_to_upgrade_);
121 #ifdef CROW_ENABLE_SSL
129 uint32_t get_methods()
135 void foreach_method(F f)
137 for (uint32_t method = 0, method_bit = 1; method < static_cast<uint32_t>(HTTPMethod::InternalMethodCount); method++, method_bit <<= 1)
139 if (methods_ & method_bit)
144 std::string custom_templates_base;
146 const std::string& rule() {
return rule_; }
149 uint32_t methods_{1 <<
static_cast<int>(HTTPMethod::Get)};
155 std::unique_ptr<BaseRule> rule_to_upgrade_;
168 namespace routing_handler_call_helper
170 template<
typename T,
int Pos>
174 static const int pos = Pos;
177 template<
typename H1>
181 const routing_params& params;
186 template<
typename F,
int NInt,
int NU
int,
int NDouble,
int NString,
typename S1,
typename S2>
190 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
191 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>, black_magic::S<Args2...>>
193 void operator()(F cparams)
195 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<int64_t, NInt>>;
196 call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
200 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
201 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<uint64_t, Args1...>, black_magic::S<Args2...>>
203 void operator()(F cparams)
205 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<uint64_t, NUint>>;
206 call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>, pushed>()(cparams);
210 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
211 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>, black_magic::S<Args2...>>
213 void operator()(F cparams)
215 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<double, NDouble>>;
216 call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>, pushed>()(cparams);
220 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1,
typename... Args2>
221 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<std::string, Args1...>, black_magic::S<Args2...>>
223 void operator()(F cparams)
225 using pushed =
typename black_magic::S<Args2...>::template push_back<call_pair<std::string, NString>>;
226 call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>, pushed>()(cparams);
230 template<
typename F,
int NInt,
int NUint,
int NDouble,
int NString,
typename... Args1>
231 struct call<F, NInt, NUint, NDouble, NString, black_magic::S<>, black_magic::S<Args1...>>
233 void operator()(F cparams)
238 cparams.params.template get<typename Args1::type>(Args1::pos)...);
242 template<
typename Func,
typename... ArgsWrapped>
245 template<
typename... Args>
246 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)
249 #ifdef CROW_CAN_USE_CPP14
260 template<
typename Req,
typename... Args>
277 template<
typename... Args>
278 void set_(Func f,
typename std::enable_if<
279 std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
const request&>::value &&
280 !std::is_same<
typename std::tuple_element<1, std::tuple<Args..., void, void>>::type,
response&>::value,
292 template<
typename... Args>
293 void set_(Func f,
typename std::enable_if<
294 std::is_same<
typename std::tuple_element<0, std::tuple<Args..., void>>::type,
const request&>::value &&
295 std::is_same<
typename std::tuple_element<1, std::tuple<Args..., void, void>>::type,
response&>::value,
298 handler_ = std::move(f);
301 template<
typename... Args>
305 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
308 template<
typename... Args>
312 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
315 template<
typename... Args>
319 using args_type = black_magic::S<typename black_magic::promote_t<Args>...>;
324 void operator()(
request& req,
response& res,
const routing_params& params)
333 decltype(handler_)>{handler_, params, req, res});
347 template<
typename Func>
348 typename std::enable_if<black_magic::CallHelper<Func, black_magic::S<>>::value,
void>::type
351 static_assert(!std::is_same<
void, decltype(f())>::value,
352 "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
355 #ifdef CROW_CAN_USE_CPP14
366 template<
typename Func>
367 typename std::enable_if<
368 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
369 black_magic::CallHelper<Func, black_magic::S<crow::request>>::value,
373 static_assert(!std::is_same<
void, decltype(f(std::declval<crow::request>()))>::value,
374 "Handler function cannot have void return type; valid return types: string, int, crow::response, crow::returnable");
377 #ifdef CROW_CAN_USE_CPP14
388 template<
typename Func>
389 typename std::enable_if<
390 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
391 !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
392 black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
396 static_assert(std::is_same<
void, decltype(f(std::declval<crow::response&>()))>::value,
397 "Handler function with response argument should have void return type");
399 #ifdef CROW_CAN_USE_CPP14
409 template<
typename Func>
410 typename std::enable_if<
411 !black_magic::CallHelper<Func, black_magic::S<>>::value &&
412 !black_magic::CallHelper<Func, black_magic::S<crow::request>>::value &&
413 !black_magic::CallHelper<Func, black_magic::S<crow::response&>>::value,
417 static_assert(std::is_same<
void, decltype(f(std::declval<crow::request>(), std::declval<crow::response&>()))>::value,
418 "Handler function with response argument should have void return type");
420 handler_ = std::move(f);
425 return (handler_ !=
nullptr);
440 template<
typename App>
449 max_payload_(UINT64_MAX)
452 void validate()
override
466 #ifdef CROW_ENABLE_SSL
477 max_payload_override_ =
true;
481 template<
typename Func>
482 self_t& onopen(Func f)
488 template<
typename Func>
489 self_t& onmessage(Func f)
491 message_handler_ = f;
495 template<
typename Func>
496 self_t& onclose(Func f)
502 template<
typename Func>
503 self_t& onerror(Func f)
509 template<
typename Func>
510 self_t& onaccept(Func f)
522 std::function<bool(
const crow::request&,
void**)> accept_handler_;
523 uint64_t max_payload_;
524 bool max_payload_override_ =
false;
536 template<
typename App>
540 static_cast<self_t*
>(
this)->rule_to_upgrade_.reset(p);
544 self_t& name(std::string name) noexcept
546 static_cast<self_t*
>(
this)->name_ = std::move(name);
547 return static_cast<self_t&
>(*this);
550 self_t& methods(HTTPMethod method)
552 static_cast<self_t*
>(
this)->methods_ = 1 <<
static_cast<int>(method);
553 return static_cast<self_t&
>(*this);
556 template<
typename... MethodArgs>
557 self_t& methods(HTTPMethod method, MethodArgs... args_method)
559 methods(args_method...);
560 static_cast<self_t*
>(
this)->methods_ |= 1 <<
static_cast<int>(method);
561 return static_cast<self_t&
>(*this);
565 template<
typename App,
typename... Middlewares>
568 static_cast<self_t*
>(
this)->mw_indices_.template push<App, Middlewares...>();
569 return static_cast<self_t&
>(*this);
581 void validate()
override
583 if (!erased_handler_)
585 throw std::runtime_error(name_ + (!name_.empty() ?
": " :
"") +
"no handler for url " + rule_);
589 void handle(
request& req,
response& res,
const routing_params& params)
override
591 if (!custom_templates_base.empty())
592 mustache::set_base(custom_templates_base);
593 else if (mustache::detail::get_template_base_directory_ref() !=
"templates")
594 mustache::set_base(
"templates");
595 erased_handler_(req, res, params);
598 template<
typename Func>
599 void operator()(Func f)
601 #ifdef CROW_MSVC_WORKAROUND
602 using function_t = utility::function_traits<decltype(&Func::operator())>;
604 using function_t = utility::function_traits<Func>;
606 erased_handler_ = wrap(std::move(f), black_magic::gen_seq<function_t::arity>());
612 #ifdef CROW_MSVC_WORKAROUND
613 template<
typename Func,
size_t... Indices>
615 template<
typename Func,
unsigned... Indices>
618 wrap(Func f, black_magic::seq<Indices...>)
620 #ifdef CROW_MSVC_WORKAROUND
621 using function_t = utility::function_traits<decltype(&Func::operator())>;
623 using function_t = utility::function_traits<Func>;
625 if (!black_magic::is_parameter_tag_compatible(
626 black_magic::get_parameter_tag_runtime(rule_.c_str()),
627 black_magic::compute_parameter_tag_from_args_list<
628 typename function_t::template arg<Indices>...>::value))
630 throw std::runtime_error(
"route_dynamic: Handler type is mismatched with URL parameters: " + rule_);
634 typename function_t::template arg<Indices>...>(std::move(f));
638 template<
typename Func>
639 void operator()(std::string name, Func&& f)
641 name_ = std::move(name);
642 (*this).template operator()<Func>(std::forward(f));
646 std::function<void(
request&,
response&,
const routing_params&)> erased_handler_;
650 template<
typename... Args>
660 void validate()
override
662 if (rule_.at(0) !=
'/')
663 throw std::runtime_error(
"Internal error: Routes must start with a '/'");
667 throw std::runtime_error(name_ + (!name_.empty() ?
": " :
"") +
"no handler for url " + rule_);
671 template<
typename Func>
672 void operator()(Func&& f)
675 #ifdef CROW_CAN_USE_CPP14
681 detail::wrapped_handler_call(req, res, f, std::forward<Args>(args)...);
685 template<
typename Func>
686 void operator()(std::string name, Func&& f)
688 name_ = std::move(name);
689 (*this).template operator()<Func>(std::forward(f));
692 void handle(
request& req,
response& res,
const routing_params& params)
override
694 if (!custom_templates_base.empty())
695 mustache::set_base(custom_templates_base);
696 else if (mustache::detail::get_template_base_directory_ref() != mustache::detail::get_global_template_base_directory_ref())
697 mustache::set_base(mustache::detail::get_global_template_base_directory_ref());
702 black_magic::S<Args...>,
711 const int RULE_SPECIAL_REDIRECT_SLASH = 1;
720 uint16_t rule_index{};
722 uint16_t blueprint_index{INVALID_BP_ID};
724 ParamType param = ParamType::MAX;
725 std::vector<Node> children;
727 bool IsSimpleNode()
const
729 return !rule_index &&
730 blueprint_index == INVALID_BP_ID &&
731 children.size() < 2 &&
732 param == ParamType::MAX &&
733 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
734 return x.param == ParamType::MAX;
738 Node& add_child_node()
740 children.emplace_back();
741 return children.back();
752 return head_.children.empty();
757 for (
auto& child : head_.children)
765 void optimizeNode(Node& node)
767 if (node.children.empty())
769 if (node.IsSimpleNode())
771 auto children_temp = std::move(node.children);
772 auto& child_temp = children_temp[0];
773 node.key += child_temp.key;
774 node.rule_index = child_temp.rule_index;
775 node.blueprint_index = child_temp.blueprint_index;
776 node.children = std::move(child_temp.children);
781 for (
auto& child : node.children)
788 void debug_node_print(
const Node& node,
int level)
790 if (node.param != ParamType::MAX)
795 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
798 case ParamType::UINT:
799 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
802 case ParamType::DOUBLE:
803 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
806 case ParamType::STRING:
807 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
810 case ParamType::PATH:
811 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
815 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
821 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
823 for (
const auto& child : node.children)
825 debug_node_print(child, level + 1);
832 CROW_LOG_DEBUG <<
"└➙ ROOT";
833 for (
const auto& child : head_.children)
834 debug_node_print(child, 1);
839 if (!head_.IsSimpleNode())
840 throw std::runtime_error(
"Internal error: Trie header should be simple!");
845 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
848 routing_params empty;
849 if (params ==
nullptr)
852 std::vector<uint16_t> MT;
853 if (blueprints ==
nullptr)
857 std::vector<uint16_t> found_BP;
858 routing_params match_params;
860 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
861 found_BP = std::move(ret.blueprint_indices);
862 if (ret.rule_index && (!found || found > ret.rule_index))
864 found = ret.rule_index;
865 match_params = std::move(ret.r_params);
870 if (pos == req_url.size())
872 found_BP = std::move(*blueprints);
873 return routing_handle_result{node.rule_index, *blueprints, *params};
876 bool found_fragment =
false;
878 for (
const auto& child : node.children)
880 if (child.param != ParamType::MAX)
882 if (child.param == ParamType::INT)
884 char c = req_url[pos];
885 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
889 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
890 if (errno != ERANGE && eptr != req_url.data() + pos)
892 found_fragment =
true;
893 params->int_params.push_back(value);
894 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
895 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
897 params->int_params.pop_back();
898 if (!blueprints->empty()) blueprints->pop_back();
903 else if (child.param == ParamType::UINT)
905 char c = req_url[pos];
906 if ((c >=
'0' && c <=
'9') || c ==
'+')
910 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
911 if (errno != ERANGE && eptr != req_url.data() + pos)
913 found_fragment =
true;
914 params->uint_params.push_back(value);
915 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
916 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
918 params->uint_params.pop_back();
919 if (!blueprints->empty()) blueprints->pop_back();
924 else if (child.param == ParamType::DOUBLE)
926 char c = req_url[pos];
927 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
931 double value = strtod(req_url.data() + pos, &eptr);
932 if (errno != ERANGE && eptr != req_url.data() + pos)
934 found_fragment =
true;
935 params->double_params.push_back(value);
936 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
937 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
939 params->double_params.pop_back();
940 if (!blueprints->empty()) blueprints->pop_back();
945 else if (child.param == ParamType::STRING)
948 for (; epos < req_url.size(); epos++)
950 if (req_url[epos] ==
'/')
956 found_fragment =
true;
957 params->string_params.push_back(req_url.substr(pos, epos - pos));
958 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
959 auto ret = find(req_url, child, epos, params, blueprints);
961 params->string_params.pop_back();
962 if (!blueprints->empty()) blueprints->pop_back();
966 else if (child.param == ParamType::PATH)
968 size_t epos = req_url.size();
972 found_fragment =
true;
973 params->string_params.push_back(req_url.substr(pos, epos - pos));
974 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
975 auto ret = find(req_url, child, epos, params, blueprints);
977 params->string_params.pop_back();
978 if (!blueprints->empty()) blueprints->pop_back();
985 const std::string& fragment = child.key;
986 if (req_url.compare(pos, fragment.size(), fragment) == 0)
988 found_fragment =
true;
989 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
990 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
992 if (!blueprints->empty()) blueprints->pop_back();
998 found_BP = std::move(*blueprints);
1000 return routing_handle_result{found, found_BP, match_params};
1003 routing_handle_result find(
const std::string& req_url)
const
1005 return find(req_url, head_);
1009 void add(
const std::string& url, uint16_t rule_index,
unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
1013 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1015 for (
unsigned i = 0; i < url.size(); i++)
1020 static struct ParamTraits
1026 {ParamType::INT,
"<int>"},
1027 {ParamType::UINT,
"<uint>"},
1028 {ParamType::DOUBLE,
"<float>"},
1029 {ParamType::DOUBLE,
"<double>"},
1030 {ParamType::STRING,
"<str>"},
1031 {ParamType::STRING,
"<string>"},
1032 {ParamType::PATH,
"<path>"},
1035 for (
const auto& x : paramTraits)
1037 if (url.compare(i, x.name.size(), x.name) == 0)
1040 for (
auto& child : idx->children)
1042 if (child.param == x.type)
1053 auto new_node_idx = &idx->add_child_node();
1054 new_node_idx->param = x.type;
1066 bool piece_found =
false;
1067 for (
auto& child : idx->children)
1069 if (child.key[0] == c)
1078 auto new_node_idx = &idx->add_child_node();
1079 new_node_idx->key = c;
1081 if (has_blueprint && i == bp_prefix_length)
1082 new_node_idx->blueprint_index = blueprint_index;
1089 if (idx->rule_index)
1090 throw std::runtime_error(
"handler already exists for " + url);
1091 idx->rule_index = rule_index;
1109 Blueprint(
const std::string& prefix,
const std::string& static_dir):
1110 prefix_(prefix), static_dir_(static_dir){};
1112 Blueprint(
const std::string& prefix,
const std::string& static_dir,
const std::string& templates_dir):
1113 prefix_(prefix), static_dir_(static_dir), templates_dir_(templates_dir){};
1130 *
this = std::move(value);
1137 prefix_ = std::move(value.prefix_);
1138 static_dir_ = std::move(value.static_dir_);
1139 templates_dir_ = std::move(value.templates_dir_);
1140 all_rules_ = std::move(value.all_rules_);
1141 catchall_rule_ = std::move(value.catchall_rule_);
1142 blueprints_ = std::move(value.blueprints_);
1143 mw_indices_ = std::move(value.mw_indices_);
1149 return value.prefix() == prefix_;
1154 return value.prefix() != prefix_;
1157 std::string prefix()
const
1162 std::string static_dir()
const
1175 DynamicRule& new_rule_dynamic(
const std::string& rule)
1177 std::string new_rule =
'/' + prefix_ + rule;
1178 auto ruleObject =
new DynamicRule(std::move(new_rule));
1179 ruleObject->custom_templates_base = templates_dir_;
1180 all_rules_.emplace_back(ruleObject);
1185 template<u
int64_t N>
1186 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1188 std::string new_rule =
'/' + prefix_ + rule;
1189 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1191 auto ruleObject =
new RuleT(std::move(new_rule));
1192 ruleObject->custom_templates_base = templates_dir_;
1193 all_rules_.emplace_back(ruleObject);
1198 void register_blueprint(
Blueprint& blueprint)
1200 if (blueprints_.empty() || std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1202 apply_blueprint(blueprint);
1203 blueprints_.emplace_back(&blueprint);
1206 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in blueprint \"" + prefix_ +
'\"');
1212 return catchall_rule_;
1215 template<
typename App,
typename... Middlewares>
1218 mw_indices_.push<
App, Middlewares...>();
1222 void apply_blueprint(
Blueprint& blueprint)
1225 blueprint.prefix_ = prefix_ +
'/' + blueprint.prefix_;
1226 blueprint.static_dir_ = static_dir_ +
'/' + blueprint.static_dir_;
1227 blueprint.templates_dir_ = templates_dir_ +
'/' + blueprint.templates_dir_;
1228 for (
auto& rule : blueprint.all_rules_)
1230 std::string new_rule =
'/' + prefix_ + rule->rule_;
1231 rule->rule_ = new_rule;
1233 for (
Blueprint* bp_child : blueprint.blueprints_)
1236 apply_blueprint(bp_ref);
1240 std::string prefix_;
1241 std::string static_dir_;
1242 std::string templates_dir_;
1243 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1245 std::vector<Blueprint*> blueprints_;
1259 DynamicRule& new_rule_dynamic(
const std::string& rule)
1262 all_rules_.emplace_back(ruleObject);
1267 template<u
int64_t N>
1268 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1270 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1272 auto ruleObject =
new RuleT(rule);
1273 all_rules_.emplace_back(ruleObject);
1280 return catchall_rule_;
1283 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1285 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1288 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
1290 bool has_trailing_slash =
false;
1291 std::string rule_without_trailing_slash;
1292 if (rule.size() > 1 && rule.back() ==
'/')
1294 has_trailing_slash =
true;
1295 rule_without_trailing_slash = rule;
1296 rule_without_trailing_slash.pop_back();
1299 ruleObject->mw_indices_.pack();
1301 ruleObject->foreach_method([&](
int method) {
1302 per_methods_[method].rules.emplace_back(ruleObject);
1303 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);
1307 if (has_trailing_slash)
1309 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);
1313 ruleObject->set_added();
1316 void register_blueprint(
Blueprint& blueprint)
1318 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1320 blueprints_.emplace_back(&blueprint);
1323 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1326 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1329 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1331 for (
Blueprint* bp : blueprint->blueprints_)
1333 get_recursive_child_methods(bp, methods);
1336 else if (!blueprint->static_dir_.empty())
1337 methods.emplace_back(HTTPMethod::Get);
1338 for (
auto& rule : blueprint->all_rules_)
1340 rule->foreach_method([&methods](
unsigned method) {
1341 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1342 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1343 methods.emplace_back(method_final);
1348 void validate_bp() {
1351 validate_bp(blueprints_, blueprint_mw);
1356 for (
unsigned i = 0; i < blueprints.size(); i++)
1360 if (blueprint->is_added())
continue;
1362 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1364 std::vector<HTTPMethod> methods;
1365 get_recursive_child_methods(blueprint, methods);
1366 for (HTTPMethod x : methods)
1368 int i =
static_cast<int>(x);
1369 per_methods_[i].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), i);
1373 current_mw.merge_back(blueprint->mw_indices_);
1374 for (
auto& rule : blueprint->all_rules_)
1376 if (rule && !rule->is_added())
1378 auto upgraded = rule->upgrade();
1380 rule = std::move(upgraded);
1382 rule->mw_indices_.merge_front(current_mw);
1383 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1386 validate_bp(blueprint->blueprints_, current_mw);
1387 current_mw.pop_back(blueprint->mw_indices_);
1388 blueprint->set_added();
1394 for (
auto& rule : all_rules_)
1396 if (rule && !rule->is_added())
1398 auto upgraded = rule->upgrade();
1400 rule = std::move(upgraded);
1402 internal_add_rule_object(rule->rule(), rule.get());
1405 for (
auto& per_method : per_methods_)
1407 per_method.trie.validate();
1412 template<
typename Adaptor>
1413 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1415 if (req.method >= HTTPMethod::InternalMethodCount)
1418 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1419 auto& rules = per_method.rules;
1420 unsigned rule_index = per_method.trie.find(req.
url).rule_index;
1424 for (
auto& per_method : per_methods_)
1426 if (per_method.trie.find(req.
url).rule_index)
1428 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1435 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1441 if (rule_index >= rules.size())
1442 throw std::runtime_error(
"Trie internal structure corrupted!");
1444 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1446 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1450 if (req.get_header_value(
"Host").empty())
1456 res.
add_header(
"Location",
"http://" + req.get_header_value(
"Host") + req.
url +
"/");
1462 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1466 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1470 exception_handler_(res);
1476 void get_found_bp(std::vector<uint16_t>& bp_i, std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
1486 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1488 bp_i[index] < blueprints.size() &&
1489 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1491 if (index < bp_i.size())
1494 if (verify_prefix())
1496 found_bps.push_back(blueprints[bp_i[index]]);
1497 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1501 if (found_bps.size() < 2)
1504 found_bps.push_back(blueprints_[bp_i[index]]);
1508 found_bps.pop_back();
1509 Blueprint* last_element = found_bps.back();
1510 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1512 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1521 std::vector<Blueprint*> bps_found;
1522 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1523 for (
int i = bps_found.size() - 1; i > 0; i--)
1525 std::vector<uint16_t> bpi = found.blueprint_indices;
1526 if (bps_found[i]->catchall_rule().has_handler())
1530 bps_found[i]->catchall_rule().handler_(req, res);
1534 exception_handler_(res);
1536 #ifdef CROW_ENABLE_DEBUG
1537 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1539 return std::string();
1543 if (catchall_rule_.has_handler())
1547 catchall_rule_.handler_(req, res);
1551 exception_handler_(res);
1553 #ifdef CROW_ENABLE_DEBUG
1554 return std::string(
"Redirected to global Catchall rule");
1556 return std::string();
1559 return std::string();
1562 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1564 HTTPMethod method_actual = req.method;
1566 std::unique_ptr<routing_handle_result> found{
1569 std::vector<uint16_t>(),
1571 HTTPMethod::InternalMethodCount)};
1574 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1576 else if (req.method == HTTPMethod::Head)
1578 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1580 if (!found->rule_index)
1582 method_actual = HTTPMethod::Get;
1583 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1584 if (!found->rule_index)
1586 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1587 res = response(404);
1594 found->method = method_actual;
1597 else if (req.method == HTTPMethod::Options)
1599 std::string allow =
"OPTIONS, HEAD, ";
1601 if (req.
url ==
"/*")
1603 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1605 if (
static_cast<int>(HTTPMethod::Head) == i)
1608 if (!per_methods_[i].trie.is_empty())
1610 allow += method_name(
static_cast<HTTPMethod
>(i)) +
", ";
1613 allow = allow.substr(0, allow.size() - 2);
1614 res = response(204);
1617 found->method = method_actual;
1622 bool rules_matched =
false;
1623 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1625 if (per_methods_[i].trie.find(req.
url).rule_index)
1627 rules_matched =
true;
1629 if (
static_cast<int>(HTTPMethod::Head) == i)
1632 allow += method_name(
static_cast<HTTPMethod
>(i)) +
", ";
1637 allow = allow.substr(0, allow.size() - 2);
1638 res = response(204);
1641 found->method = method_actual;
1646 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1647 res = response(404);
1655 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1657 if (!found->rule_index)
1659 for (
auto& per_method : per_methods_)
1661 if (per_method.trie.find(req.
url).rule_index)
1663 const std::string error_message(
get_error(405, *found, req, res));
1664 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(method_actual) <<
". " << error_message;
1671 const std::string error_message(
get_error(404, *found, req, res));
1672 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << error_message;
1677 found->method = method_actual;
1682 template<
typename App>
1683 void handle(request& req, response& res, routing_handle_result found)
1685 HTTPMethod method_actual = found.method;
1686 auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1687 unsigned rule_index = found.rule_index;
1689 if (rule_index >= rules.size())
1690 throw std::runtime_error(
"Trie internal structure corrupted!");
1692 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1694 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.url;
1695 res = response(301);
1698 if (req.get_header_value(
"Host").empty())
1700 res.add_header(
"Location", req.url +
"/");
1704 res.add_header(
"Location",
"http://" + req.get_header_value(
"Host") + req.url +
"/");
1710 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1714 auto& rule = rules[rule_index];
1715 handle_rule<App>(rule, req, res, found.r_params);
1719 exception_handler_(res);
1725 template<
typename App>
1726 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1729 if (!rule->mw_indices_.empty())
1731 auto& ctx = *
reinterpret_cast<typename App::context_t*
>(req.middleware_context);
1732 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1733 detail::middleware_call_criteria_dynamic<false> crit_fwd(rule->mw_indices_.indices());
1735 auto glob_completion_handler = std::move(res.complete_request_handler_);
1736 res.complete_request_handler_ = [] {};
1738 detail::middleware_call_helper<decltype(crit_fwd),
1739 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1743 glob_completion_handler();
1747 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1748 detail::middleware_call_criteria_dynamic<true> crit_bwd(rule->mw_indices_.indices());
1750 detail::after_handlers_call_helper<
1752 std::tuple_size<typename App::mw_container_t>::value - 1,
1753 typename App::context_t,
1754 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1755 glob_completion_handler();
1758 rule->handle(req, res, rp);
1761 template<
typename App>
1762 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1765 rule->handle(req, res, rp);
1770 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1772 Trie& trie_ = per_methods_[i].trie;
1773 if (!trie_.is_empty())
1775 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1776 trie_.debug_print();
1781 std::vector<Blueprint*>& blueprints()
1788 return exception_handler_;
1791 static void default_exception_handler(response& res)
1794 res = response(500);
1800 catch (
const std::exception& e)
1802 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1806 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1811 CatchallRule catchall_rule_;
1815 std::vector<BaseRule*> rules;
1822 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1823 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1824 std::vector<Blueprint*> blueprints_;
1825 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;
A base class for all rules.
Definition: routing.h:89
A blueprint can be considered a smaller section of a Crow app, specifically where the router is conec...
Definition: routing.h:1104
Definition: routing.h:342
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:575
Handles matching requests to existing rules and upgrade requests.
Definition: routing.h:1254
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:1518
Default rule created when CROW_ROUTE is called.
Definition: routing.h:652
A search tree.
Definition: routing.h:716
bool is_empty()
Check whether or not the trie is empty.
Definition: routing.h:750
A rule dealing with websockets.
Definition: routing.h:442
self_t & max_payload(uint64_t max_payload)
Override the global payload limit for this single WebSocket rule.
Definition: routing.h:474
A websocket connection.
Definition: websocket.h:81
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:771
Allows the user to assign parameters using functions.
Definition: routing.h:533
self_t & middlewares()
Enable local middleware for this handler.
Definition: routing.h:566
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:719
Typesafe wrapper for storing lists of middleware as their indices in the App.
Definition: routing.h:30
Definition: routing.h:303
Definition: routing.h:262
Definition: routing.h:244
Definition: routing.h:172
Definition: routing.h:179
Definition: routing.h:188
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:38