717 uint16_t rule_index{};
719 uint16_t blueprint_index{INVALID_BP_ID};
721 ParamType param = ParamType::MAX;
722 std::vector<Node> children;
724 bool IsSimpleNode()
const
726 return !rule_index &&
727 blueprint_index == INVALID_BP_ID &&
728 children.size() < 2 &&
729 param == ParamType::MAX &&
730 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
731 return x.param == ParamType::MAX;
735 Node& add_child_node()
737 children.emplace_back();
738 return children.back();
749 return head_.children.empty();
754 for (
auto& child : head_.children)
762 void optimizeNode(Node& node)
764 if (node.children.empty())
766 if (node.IsSimpleNode())
768 auto children_temp = std::move(node.children);
769 auto& child_temp = children_temp[0];
770 node.key += child_temp.key;
771 node.rule_index = child_temp.rule_index;
772 node.blueprint_index = child_temp.blueprint_index;
773 node.children = std::move(child_temp.children);
778 for (
auto& child : node.children)
785 void debug_node_print(
const Node& node,
size_t level)
787 if (node.param != ParamType::MAX)
792 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
795 case ParamType::UINT:
796 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
799 case ParamType::DOUBLE:
800 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
803 case ParamType::STRING:
804 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
807 case ParamType::PATH:
808 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
812 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
818 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
820 for (
const auto& child : node.children)
822 debug_node_print(child, level + 1);
829 CROW_LOG_DEBUG <<
"└➙ ROOT";
830 for (
const auto& child : head_.children)
831 debug_node_print(child, 1);
836 if (!head_.IsSimpleNode())
837 throw std::runtime_error(
"Internal error: Trie header should be simple!");
842 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
845 routing_params empty;
846 if (params ==
nullptr)
849 std::vector<uint16_t> MT;
850 if (blueprints ==
nullptr)
854 std::vector<uint16_t> found_BP;
855 routing_params match_params;
857 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
858 found_BP = std::move(ret.blueprint_indices);
859 if (ret.rule_index && (!found || found > ret.rule_index))
861 found = ret.rule_index;
862 match_params = std::move(ret.r_params);
867 if (pos == req_url.size())
869 found_BP = std::move(*blueprints);
870 return routing_handle_result{node.rule_index, *blueprints, *params};
873 bool found_fragment =
false;
875 for (
const auto& child : node.children)
877 if (child.param != ParamType::MAX)
879 if (child.param == ParamType::INT)
881 char c = req_url[pos];
882 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
886 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
887 if (errno != ERANGE && eptr != req_url.data() + pos)
889 found_fragment =
true;
890 params->int_params.push_back(value);
891 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
892 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
894 params->int_params.pop_back();
895 if (!blueprints->empty()) blueprints->pop_back();
900 else if (child.param == ParamType::UINT)
902 char c = req_url[pos];
903 if ((c >=
'0' && c <=
'9') || c ==
'+')
907 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
908 if (errno != ERANGE && eptr != req_url.data() + pos)
910 found_fragment =
true;
911 params->uint_params.push_back(value);
912 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
913 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
915 params->uint_params.pop_back();
916 if (!blueprints->empty()) blueprints->pop_back();
921 else if (child.param == ParamType::DOUBLE)
923 char c = req_url[pos];
924 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
928 double value = strtod(req_url.data() + pos, &eptr);
929 if (errno != ERANGE && eptr != req_url.data() + pos)
931 found_fragment =
true;
932 params->double_params.push_back(value);
933 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
934 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
936 params->double_params.pop_back();
937 if (!blueprints->empty()) blueprints->pop_back();
942 else if (child.param == ParamType::STRING)
945 for (; epos < req_url.size(); epos++)
947 if (req_url[epos] ==
'/')
953 found_fragment =
true;
954 params->string_params.push_back(req_url.substr(pos, epos - pos));
955 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
956 auto ret = find(req_url, child, epos, params, blueprints);
958 params->string_params.pop_back();
959 if (!blueprints->empty()) blueprints->pop_back();
963 else if (child.param == ParamType::PATH)
965 size_t epos = req_url.size();
969 found_fragment =
true;
970 params->string_params.push_back(req_url.substr(pos, epos - pos));
971 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
972 auto ret = find(req_url, child, epos, params, blueprints);
974 params->string_params.pop_back();
975 if (!blueprints->empty()) blueprints->pop_back();
982 const std::string& fragment = child.key;
983 if (req_url.compare(pos, fragment.size(), fragment) == 0)
985 found_fragment =
true;
986 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
987 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
989 if (!blueprints->empty()) blueprints->pop_back();
995 found_BP = std::move(*blueprints);
997 return routing_handle_result{found, found_BP, match_params};
1000 routing_handle_result find(
const std::string& req_url)
const
1002 return find(req_url, head_);
1006 void add(
const std::string& url, uint16_t rule_index,
unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
1010 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1012 for (
unsigned i = 0; i < url.size(); i++)
1017 static struct ParamTraits
1023 {ParamType::INT,
"<int>"},
1024 {ParamType::UINT,
"<uint>"},
1025 {ParamType::DOUBLE,
"<float>"},
1026 {ParamType::DOUBLE,
"<double>"},
1027 {ParamType::STRING,
"<str>"},
1028 {ParamType::STRING,
"<string>"},
1029 {ParamType::PATH,
"<path>"},
1032 for (
const auto& x : paramTraits)
1034 if (url.compare(i, x.name.size(), x.name) == 0)
1037 for (
auto& child : idx->children)
1039 if (child.param == x.type)
1050 auto new_node_idx = &idx->add_child_node();
1051 new_node_idx->param = x.type;
1063 bool piece_found =
false;
1064 for (
auto& child : idx->children)
1066 if (child.key[0] == c)
1075 auto new_node_idx = &idx->add_child_node();
1076 new_node_idx->key = c;
1078 if (has_blueprint && i == bp_prefix_length)
1079 new_node_idx->blueprint_index = blueprint_index;
1086 if (idx->rule_index)
1087 throw std::runtime_error(
"handler already exists for " + url);
1088 idx->rule_index = rule_index;
1260 Router() : using_ssl(
false)
1263 DynamicRule& new_rule_dynamic(
const std::string& rule)
1266 all_rules_.emplace_back(ruleObject);
1271 template<u
int64_t N>
1272 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1274 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1276 auto ruleObject =
new RuleT(rule);
1277 all_rules_.emplace_back(ruleObject);
1284 return catchall_rule_;
1287 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1289 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1292 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
1294 bool has_trailing_slash =
false;
1295 std::string rule_without_trailing_slash;
1296 if (rule.size() > 1 && rule.back() ==
'/')
1298 has_trailing_slash =
true;
1299 rule_without_trailing_slash = rule;
1300 rule_without_trailing_slash.pop_back();
1303 ruleObject->mw_indices_.pack();
1305 ruleObject->foreach_method([&](
int method) {
1306 per_methods_[method].rules.emplace_back(ruleObject);
1307 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);
1311 if (has_trailing_slash)
1313 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);
1317 ruleObject->set_added();
1320 void register_blueprint(
Blueprint& blueprint)
1322 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1324 blueprints_.emplace_back(&blueprint);
1327 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1330 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1333 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1335 for (
Blueprint* bp : blueprint->blueprints_)
1337 get_recursive_child_methods(bp, methods);
1340 else if (!blueprint->static_dir_.empty())
1341 methods.emplace_back(HTTPMethod::Get);
1342 for (
auto& rule : blueprint->all_rules_)
1344 rule->foreach_method([&methods](
unsigned method) {
1345 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1346 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1347 methods.emplace_back(method_final);
1356 validate_bp(blueprints_, blueprint_mw);
1361 for (
unsigned i = 0; i < blueprints.size(); i++)
1365 if (blueprint->is_added())
continue;
1367 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1369 std::vector<HTTPMethod> methods;
1370 get_recursive_child_methods(blueprint, methods);
1371 for (HTTPMethod x : methods)
1373 int method_index =
static_cast<int>(x);
1374 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1378 current_mw.merge_back(blueprint->mw_indices_);
1379 for (
auto& rule : blueprint->all_rules_)
1381 if (rule && !rule->is_added())
1383 auto upgraded = rule->upgrade();
1385 rule = std::move(upgraded);
1387 rule->mw_indices_.merge_front(current_mw);
1388 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1391 validate_bp(blueprint->blueprints_, current_mw);
1392 current_mw.pop_back(blueprint->mw_indices_);
1393 blueprint->set_added();
1399 for (
auto& rule : all_rules_)
1401 if (rule && !rule->is_added())
1403 auto upgraded = rule->upgrade();
1405 rule = std::move(upgraded);
1407 internal_add_rule_object(rule->rule(), rule.get());
1410 for (
auto& per_method : per_methods_)
1412 per_method.trie.validate();
1417 template<
typename Adaptor>
1418 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1420 if (req.method >= HTTPMethod::InternalMethodCount)
1423 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1424 auto& rules = per_method.rules;
1425 unsigned rule_index = per_method.trie.find(req.
url).rule_index;
1429 for (
auto& method : per_methods_)
1431 if (method.trie.find(req.
url).rule_index)
1433 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1440 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1446 if (rule_index >= rules.size())
1447 throw std::runtime_error(
"Trie internal structure corrupted!");
1449 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1451 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1458 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1462 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1466 exception_handler_(res);
1472 void get_found_bp(std::vector<uint16_t>& bp_i, std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
1482 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1484 bp_i[index] < blueprints.size() &&
1485 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1487 if (index < bp_i.size())
1490 if (verify_prefix())
1492 found_bps.push_back(blueprints[bp_i[index]]);
1493 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1497 if (found_bps.size() < 2)
1500 found_bps.push_back(blueprints_[bp_i[index]]);
1504 found_bps.pop_back();
1505 Blueprint* last_element = found_bps.back();
1506 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1508 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1517 std::vector<Blueprint*> bps_found;
1518 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1519 for (
int i = bps_found.size() - 1; i > 0; i--)
1521 std::vector<uint16_t> bpi = found.blueprint_indices;
1522 if (bps_found[i]->catchall_rule().has_handler())
1526 bps_found[i]->catchall_rule().handler_(req, res);
1530 exception_handler_(res);
1532#ifdef CROW_ENABLE_DEBUG
1533 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1535 return std::string();
1539 if (catchall_rule_.has_handler())
1543 catchall_rule_.handler_(req, res);
1547 exception_handler_(res);
1549#ifdef CROW_ENABLE_DEBUG
1550 return std::string(
"Redirected to global Catchall rule");
1552 return std::string();
1555 return std::string();
1558 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1560 HTTPMethod method_actual = req.method;
1562 std::unique_ptr<routing_handle_result> found{
1565 std::vector<uint16_t>(),
1567 HTTPMethod::InternalMethodCount)};
1570 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1572 else if (req.method == HTTPMethod::Head)
1574 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1576 if (!found->rule_index)
1578 method_actual = HTTPMethod::Get;
1579 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1580 if (!found->rule_index)
1582 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1583 res = response(404);
1590 found->method = method_actual;
1593 else if (req.method == HTTPMethod::Options)
1595 std::string allow =
"OPTIONS, HEAD";
1597 if (req.
url ==
"/*")
1599 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1601 if (
static_cast<int>(HTTPMethod::Head) == i)
1604 if (!per_methods_[i].trie.is_empty())
1607 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1610#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1611 res = response(crow::status::OK);
1613 res = response(crow::status::NO_CONTENT);
1618 found->method = method_actual;
1623 bool rules_matched =
false;
1624 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1626 if (per_methods_[i].trie.find(req.
url).rule_index)
1628 rules_matched =
true;
1630 if (
static_cast<int>(HTTPMethod::Head) == i)
1634 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1639#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1640 res = response(crow::status::OK);
1642 res = response(crow::status::NO_CONTENT);
1646 found->method = method_actual;
1651 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1652 res = response(404);
1660 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1662 if (!found->rule_index)
1664 for (
auto& per_method : per_methods_)
1666 if (per_method.trie.find(req.
url).rule_index)
1668 const std::string error_message(
get_error(405, *found, req, res));
1669 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(method_actual) <<
". " << error_message;
1676 const std::string error_message(
get_error(404, *found, req, res));
1677 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << error_message;
1682 found->method = method_actual;
1687 template<
typename App>
1688 void handle(request& req, response& res, routing_handle_result found)
1690 HTTPMethod method_actual = found.method;
1691 auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1692 unsigned rule_index = found.rule_index;
1694 if (rule_index >= rules.size())
1695 throw std::runtime_error(
"Trie internal structure corrupted!");
1697 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1699 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.url;
1700 res = response(301);
1701 res.add_header(
"Location", req.url +
"/");
1706 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1710 BaseRule& rule = *rules[rule_index];
1711 handle_rule<App>(rule, req, res, found.r_params);
1715 exception_handler_(res);
1721 template<
typename App>
1722 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1725 if (!rule.mw_indices_.empty())
1727 auto& ctx = *
reinterpret_cast<typename App::context_t*
>(req.middleware_context);
1728 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1729 detail::middleware_call_criteria_dynamic<false> crit_fwd(rule.mw_indices_.indices());
1731 auto glob_completion_handler = std::move(res.complete_request_handler_);
1732 res.complete_request_handler_ = [] {};
1734 detail::middleware_call_helper<
decltype(crit_fwd),
1735 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1739 glob_completion_handler();
1743 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1744 detail::middleware_call_criteria_dynamic<true> crit_bwd(rule.mw_indices_.indices());
1746 detail::after_handlers_call_helper<
1748 std::tuple_size<typename App::mw_container_t>::value - 1,
1749 typename App::context_t,
1750 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1751 glob_completion_handler();
1754 rule.handle(req, res, rp);
1757 template<
typename App>
1758 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1761 rule.handle(req, res, rp);
1766 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1768 Trie& trie_ = per_methods_[i].trie;
1769 if (!trie_.is_empty())
1771 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1772 trie_.debug_print();
1777 std::vector<Blueprint*>& blueprints()
1784 return exception_handler_;
1787 static void default_exception_handler(response& res)
1790 res = response(500);
1796 catch (
const bad_request& e)
1798 res = response (400);
1799 res.body = e.what();
1801 catch (
const std::exception& e)
1803 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1807 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1812 CatchallRule catchall_rule_;
1816 std::vector<BaseRule*> rules;
1823 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1824 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1825 std::vector<Blueprint*> blueprints_;
1826 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;