767 size_t blueprint_index{INVALID_BP_ID};
769 ParamType param = ParamType::MAX;
770 std::vector<Node> children;
772 bool IsSimpleNode()
const
774 return !rule_index &&
775 blueprint_index == INVALID_BP_ID &&
776 children.size() < 2 &&
777 param == ParamType::MAX &&
778 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
779 return x.param == ParamType::MAX;
783 Node& add_child_node()
785 children.emplace_back();
786 return children.back();
797 return head_.children.empty();
802 for (
auto& child : head_.children)
810 void optimizeNode(Node& node)
812 if (node.children.empty())
814 if (node.IsSimpleNode())
816 auto children_temp = std::move(node.children);
817 auto& child_temp = children_temp[0];
818 node.key += child_temp.key;
819 node.rule_index = child_temp.rule_index;
820 node.blueprint_index = child_temp.blueprint_index;
821 node.children = std::move(child_temp.children);
826 for (
auto& child : node.children)
833 void debug_node_print(
const Node& node,
size_t level)
835 if (node.param != ParamType::MAX)
840 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
843 case ParamType::UINT:
844 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
847 case ParamType::DOUBLE:
848 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
851 case ParamType::STRING:
852 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
855 case ParamType::PATH:
856 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
860 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
866 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
868 for (
const auto& child : node.children)
870 debug_node_print(child, level + 1);
877 CROW_LOG_DEBUG <<
"└➙ ROOT";
878 for (
const auto& child : head_.children)
879 debug_node_print(child, 1);
884 if (!head_.IsSimpleNode())
885 throw std::runtime_error(
"Internal error: Trie header should be simple!");
890 routing_handle_result find(
const std::string& req_url,
const Node& node,
size_t pos = 0, routing_params* params =
nullptr, std::vector<size_t>* blueprints =
nullptr)
const
893 routing_params empty;
894 if (params ==
nullptr)
897 std::vector<size_t> MT;
898 if (blueprints ==
nullptr)
902 std::vector<size_t> found_BP;
903 routing_params match_params;
905 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
906 found_BP = std::move(ret.blueprint_indices);
907 if (ret.rule_index && (!found || found > ret.rule_index))
909 found = ret.rule_index;
910 match_params = std::move(ret.r_params);
915 if (pos == req_url.size())
917 found_BP = std::move(*blueprints);
918 return routing_handle_result{node.rule_index, *blueprints, *params};
921 bool found_fragment =
false;
923 for (
const auto& child : node.children)
925 if (child.param != ParamType::MAX)
927 if (child.param == ParamType::INT)
929 char c = req_url[pos];
930 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
934 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
935 if (errno != ERANGE && eptr != req_url.data() + pos)
937 found_fragment =
true;
938 params->int_params.push_back(value);
939 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
940 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
942 params->int_params.pop_back();
943 if (!blueprints->empty()) blueprints->pop_back();
948 else if (child.param == ParamType::UINT)
950 char c = req_url[pos];
951 if ((c >=
'0' && c <=
'9') || c ==
'+')
955 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
956 if (errno != ERANGE && eptr != req_url.data() + pos)
958 found_fragment =
true;
959 params->uint_params.push_back(value);
960 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
961 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
963 params->uint_params.pop_back();
964 if (!blueprints->empty()) blueprints->pop_back();
969 else if (child.param == ParamType::DOUBLE)
971 char c = req_url[pos];
972 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
976 double value = strtod(req_url.data() + pos, &eptr);
977 if (errno != ERANGE && eptr != req_url.data() + pos)
979 found_fragment =
true;
980 params->double_params.push_back(value);
981 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
982 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
984 params->double_params.pop_back();
985 if (!blueprints->empty()) blueprints->pop_back();
990 else if (child.param == ParamType::STRING)
993 for (; epos < req_url.size(); epos++)
995 if (req_url[epos] ==
'/')
1001 found_fragment =
true;
1002 params->string_params.push_back(req_url.substr(pos, epos - pos));
1003 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1004 auto ret = find(req_url, child, epos, params, blueprints);
1006 params->string_params.pop_back();
1007 if (!blueprints->empty()) blueprints->pop_back();
1011 else if (child.param == ParamType::PATH)
1013 size_t epos = req_url.size();
1017 found_fragment =
true;
1018 params->string_params.push_back(req_url.substr(pos, epos - pos));
1019 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1020 auto ret = find(req_url, child, epos, params, blueprints);
1022 params->string_params.pop_back();
1023 if (!blueprints->empty()) blueprints->pop_back();
1030 const std::string& fragment = child.key;
1031 if (req_url.compare(pos, fragment.size(), fragment) == 0)
1033 found_fragment =
true;
1034 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1035 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
1037 if (!blueprints->empty()) blueprints->pop_back();
1042 if (!found_fragment)
1043 found_BP = std::move(*blueprints);
1045 return routing_handle_result{found, found_BP, match_params};
1048 routing_handle_result find(
const std::string& req_url)
const
1050 return find(req_url, head_);
1054 void add(
const std::string& url,
size_t rule_index,
unsigned bp_prefix_length = 0,
size_t blueprint_index = INVALID_BP_ID)
1058 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1060 for (
unsigned i = 0; i < url.size(); i++)
1065 static struct ParamTraits
1071 {ParamType::INT,
"<int>"},
1072 {ParamType::UINT,
"<uint>"},
1073 {ParamType::DOUBLE,
"<float>"},
1074 {ParamType::DOUBLE,
"<double>"},
1075 {ParamType::STRING,
"<str>"},
1076 {ParamType::STRING,
"<string>"},
1077 {ParamType::PATH,
"<path>"},
1080 for (
const auto& x : paramTraits)
1082 if (url.compare(i, x.name.size(), x.name) == 0)
1085 for (
auto& child : idx->children)
1087 if (child.param == x.type)
1098 auto new_node_idx = &idx->add_child_node();
1099 new_node_idx->param = x.type;
1111 bool piece_found =
false;
1112 for (
auto& child : idx->children)
1114 if (child.key[0] == c)
1123 auto new_node_idx = &idx->add_child_node();
1124 new_node_idx->key = c;
1126 if (has_blueprint && i == bp_prefix_length)
1127 new_node_idx->blueprint_index = blueprint_index;
1134 if (idx->rule_index)
1135 throw std::runtime_error(
"handler already exists for " + url);
1136 idx->rule_index = rule_index;
1307 Router() : using_ssl(
false)
1310 DynamicRule& new_rule_dynamic(
const std::string& rule)
1313 all_rules_.emplace_back(ruleObject);
1318 template<u
int64_t N>
1319 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1321 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1323 return new_rule<RuleT>(rule);
1326 template<
typename RuleT=StaticRule>
1327 auto& new_rule(
const std::string& rule)
1329 auto ruleObject =
new RuleT(rule);
1330 all_rules_.emplace_back(ruleObject);
1337 return catchall_rule_;
1340 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1342 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1345 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const size_t& BP_index, std::vector<Blueprint*>& blueprints)
1347 bool has_trailing_slash =
false;
1348 std::string rule_without_trailing_slash;
1349 if (rule.size() > 1 && rule.back() ==
'/')
1351 has_trailing_slash =
true;
1352 rule_without_trailing_slash = rule;
1353 rule_without_trailing_slash.pop_back();
1356 ruleObject->mw_indices_.pack();
1358 ruleObject->foreach_method([&](
int method) {
1359 per_methods_[method].rules.emplace_back(ruleObject);
1360 per_methods_[method].trie.add(rule, per_methods_[method].rules.size() - 1,
1361 BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0,
1366 if (has_trailing_slash)
1368 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);
1372 ruleObject->set_added();
1375 void register_blueprint(
Blueprint& blueprint)
1377 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1379 blueprints_.emplace_back(&blueprint);
1382 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1385 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1388 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1390 for (
Blueprint* bp : blueprint->blueprints_)
1392 get_recursive_child_methods(bp, methods);
1395 else if (!blueprint->static_dir_.empty())
1396 methods.emplace_back(HTTPMethod::Get);
1397 for (
auto& rule : blueprint->all_rules_)
1399 rule->foreach_method([&methods](
unsigned method) {
1400 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1401 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1402 methods.emplace_back(method_final);
1411 validate_bp(blueprints_, blueprint_mw);
1416 for (
unsigned i = 0; i < blueprints.size(); i++)
1420 if (blueprint->is_added())
continue;
1422 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1424 std::vector<HTTPMethod> methods;
1425 get_recursive_child_methods(blueprint, methods);
1426 for (HTTPMethod x : methods)
1428 int method_index =
static_cast<int>(x);
1429 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1433 current_mw.merge_back(blueprint->mw_indices_);
1434 for (
auto& rule : blueprint->all_rules_)
1436 if (rule && !rule->is_added())
1438 auto upgraded = rule->upgrade();
1440 rule = std::move(upgraded);
1442 rule->mw_indices_.merge_front(current_mw);
1443 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1446 validate_bp(blueprint->blueprints_, current_mw);
1447 current_mw.pop_back(blueprint->mw_indices_);
1448 blueprint->set_added();
1454 for (
auto& rule : all_rules_)
1456 if (rule && !rule->is_added())
1458 auto upgraded = rule->upgrade();
1460 rule = std::move(upgraded);
1462 internal_add_rule_object(rule->rule(), rule.get());
1465 for (
auto& per_method : per_methods_)
1467 per_method.trie.validate();
1472 template<
typename Adaptor>
1473 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1475 if (req.method >= HTTPMethod::InternalMethodCount)
1478 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1479 auto& rules = per_method.rules;
1480 size_t rule_index = per_method.trie.find(req.
url).rule_index;
1484 for (
auto& method : per_methods_)
1486 if (method.trie.find(req.
url).rule_index)
1488 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1495 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1501 if (rule_index >= rules.size())
1502 throw std::runtime_error(
"Trie internal structure corrupted!");
1504 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1506 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1513 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' "
1514 <<
static_cast<uint64_t
>(req.method) <<
" / "
1515 << rules[rule_index]->get_methods();
1519 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1523 exception_handler_(res);
1529 void get_found_bp(
const std::vector<size_t>& bp_i,
const std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps,
size_t index = 0)
1539 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1541 bp_i[index] < blueprints.size() &&
1542 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1544 if (index < bp_i.size())
1547 if (verify_prefix())
1549 found_bps.push_back(blueprints[bp_i[index]]);
1550 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1554 if (found_bps.size() < 2)
1557 found_bps.push_back(blueprints_[bp_i[index]]);
1561 found_bps.pop_back();
1562 Blueprint* last_element = found_bps.back();
1563 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1565 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1571 std::vector<Blueprint*> bps_found;
1572 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1573 if (!bps_found.empty()) {
1574 for (
size_t i = bps_found.size() - 1; i > 0; i--)
1576 if (bps_found[i]->catchall_rule().has_handler()) {
1577 return bps_found[i]->catchall_rule();
1581 return catchall_rule_;
1586 const std::string EMPTY;
1588 std::vector<Blueprint*> bps_found;
1589 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1590 if (!bps_found.empty()) {
1591 for (
size_t i = bps_found.size() - 1; i > 0; i--) {
1592 if (bps_found[i]->catchall_rule().has_handler()) {
1593#ifdef CROW_ENABLE_DEBUG
1594 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1600 }
else if (catchall_rule_.has_handler()) {
1601#ifdef CROW_ENABLE_DEBUG
1602 return std::string(
"Redirected to global Catchall rule");
1610 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1612 HTTPMethod method_actual = req.method;
1614 std::unique_ptr<routing_handle_result> found{
1617 std::vector<size_t>(),
1619 HTTPMethod::InternalMethodCount)};
1622 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1624 else if (req.method == HTTPMethod::Head)
1626 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1628 if (!found->rule_index)
1630 method_actual = HTTPMethod::Get;
1631 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1632 if (!found->rule_index)
1634 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1642 found->method = method_actual;
1645 else if (req.method == HTTPMethod::Options)
1647 std::string allow =
"OPTIONS, HEAD";
1649 if (req.
url ==
"/*")
1651 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1653 if (
static_cast<int>(HTTPMethod::Head) == i)
1656 if (!per_methods_[i].trie.is_empty())
1659 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1662#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1665 res =
response(crow::status::NO_CONTENT);
1670 found->method = method_actual;
1675 bool rules_matched =
false;
1676 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1678 if (per_methods_[i].trie.find(req.
url).rule_index)
1680 rules_matched =
true;
1682 if (
static_cast<int>(HTTPMethod::Head) == i)
1686 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1691#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1694 res =
response(crow::status::NO_CONTENT);
1698 found->method = method_actual;
1703 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1712 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1714 if (!found->rule_index)
1716 for (
auto& per_method : per_methods_)
1718 if (per_method.trie.find(req.
url).rule_index)
1721 found->catch_all =
true;
1722 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" "
1723 << method_name(method_actual) <<
". " << get_error(*found);
1730 found->catch_all =
true;
1731 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << get_error(*found);
1735 found->method = method_actual;
1740 template<
typename App>
1743 if (found.catch_all) {
1744 auto catch_all = get_catch_all(found);
1745 if (catch_all.has_handler()) {
1748 catch_all.handler_(req, res);
1752 exception_handler_(res);
1757 HTTPMethod method_actual = found.method;
1758 const auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1759 const size_t rule_index = found.rule_index;
1761 if (rule_index >= rules.size())
1762 throw std::runtime_error(
"Trie internal structure corrupted!");
1763 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH) {
1764 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1769 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint64_t
>(req.
1770 method) <<
" / " << rules[rule_index]->get_methods();
1773 BaseRule &rule = *rules[rule_index];
1774 handle_rule<App>(rule, req, res, found.r_params);
1776 exception_handler_(res);
1783 template<
typename App>
1784 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1787 if (!rule.mw_indices_.empty())
1789 auto& ctx = *
reinterpret_cast<typename
App::context_t*
>(req.middleware_context);
1790 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1793 auto glob_completion_handler = std::move(res.complete_request_handler_);
1794 res.complete_request_handler_ = [] {};
1796 detail::middleware_call_helper<
decltype(crit_fwd),
1797 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1801 glob_completion_handler();
1805 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1808 detail::after_handlers_call_helper<
1810 std::tuple_size<typename App::mw_container_t>::value - 1,
1812 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1813 glob_completion_handler();
1816 rule.handle(req, res, rp);
1819 template<
typename App>
1820 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1823 rule.handle(req, res, rp);
1828 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1830 Trie& trie_ = per_methods_[i].trie;
1833 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1834 trie_.debug_print();
1839 std::vector<Blueprint*>& blueprints()
1846 return exception_handler_;
1849 static void default_exception_handler(
response& res)
1861 res.
body = e.what();
1863 catch (
const std::exception& e)
1865 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1869 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1878 std::vector<BaseRule*> rules;
1885 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1886 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1887 std::vector<Blueprint*> blueprints_;
1888 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;