768 size_t blueprint_index{INVALID_BP_ID};
770 ParamType param = ParamType::MAX;
771 std::vector<Node> children;
773 bool IsSimpleNode()
const
775 return !rule_index &&
776 blueprint_index == INVALID_BP_ID &&
777 children.size() < 2 &&
778 param == ParamType::MAX &&
779 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
780 return x.param == ParamType::MAX;
784 Node& add_child_node()
786 children.emplace_back();
787 return children.back();
798 return head_.children.empty();
803 for (
auto& child : head_.children)
811 void optimizeNode(Node& node)
813 if (node.children.empty())
815 if (node.IsSimpleNode())
817 auto children_temp = std::move(node.children);
818 auto& child_temp = children_temp[0];
819 node.key += child_temp.key;
820 node.rule_index = child_temp.rule_index;
821 node.blueprint_index = child_temp.blueprint_index;
822 node.children = std::move(child_temp.children);
827 for (
auto& child : node.children)
834 void debug_node_print(
const Node& node,
size_t level)
836 if (node.param != ParamType::MAX)
841 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
844 case ParamType::UINT:
845 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
848 case ParamType::DOUBLE:
849 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
852 case ParamType::STRING:
853 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
856 case ParamType::PATH:
857 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
861 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
867 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
869 for (
const auto& child : node.children)
871 debug_node_print(child, level + 1);
878 CROW_LOG_DEBUG <<
"└➙ ROOT";
879 for (
const auto& child : head_.children)
880 debug_node_print(child, 1);
885 if (!head_.IsSimpleNode())
886 throw std::runtime_error(
"Internal error: Trie header should be simple!");
891 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
894 routing_params empty;
895 if (params ==
nullptr)
898 std::vector<size_t> MT;
899 if (blueprints ==
nullptr)
903 std::vector<size_t> found_BP;
904 routing_params match_params;
906 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
907 found_BP = std::move(ret.blueprint_indices);
908 if (ret.rule_index && (!found || found > ret.rule_index))
910 found = ret.rule_index;
911 match_params = std::move(ret.r_params);
916 if (pos == req_url.size())
918 found_BP = std::move(*blueprints);
919 return routing_handle_result{node.rule_index, *blueprints, *params};
922 bool found_fragment =
false;
924 for (
const auto& child : node.children)
926 if (child.param != ParamType::MAX)
928 if (child.param == ParamType::INT)
930 char c = req_url[pos];
931 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
935 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
936 if (errno != ERANGE && eptr != req_url.data() + pos)
938 found_fragment =
true;
939 params->int_params.push_back(value);
940 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
941 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
943 params->int_params.pop_back();
944 if (!blueprints->empty()) blueprints->pop_back();
949 else if (child.param == ParamType::UINT)
951 char c = req_url[pos];
952 if ((c >=
'0' && c <=
'9') || c ==
'+')
956 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
957 if (errno != ERANGE && eptr != req_url.data() + pos)
959 found_fragment =
true;
960 params->uint_params.push_back(value);
961 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
962 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
964 params->uint_params.pop_back();
965 if (!blueprints->empty()) blueprints->pop_back();
970 else if (child.param == ParamType::DOUBLE)
972 char c = req_url[pos];
973 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
977 double value = strtod(req_url.data() + pos, &eptr);
978 if (errno != ERANGE && eptr != req_url.data() + pos)
980 found_fragment =
true;
981 params->double_params.push_back(value);
982 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
983 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
985 params->double_params.pop_back();
986 if (!blueprints->empty()) blueprints->pop_back();
991 else if (child.param == ParamType::STRING)
994 for (; epos < req_url.size(); epos++)
996 if (req_url[epos] ==
'/')
1002 found_fragment =
true;
1003 params->string_params.push_back(req_url.substr(pos, epos - pos));
1004 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1005 auto ret = find(req_url, child, epos, params, blueprints);
1007 params->string_params.pop_back();
1008 if (!blueprints->empty()) blueprints->pop_back();
1012 else if (child.param == ParamType::PATH)
1014 size_t epos = req_url.size();
1018 found_fragment =
true;
1019 params->string_params.push_back(req_url.substr(pos, epos - pos));
1020 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1021 auto ret = find(req_url, child, epos, params, blueprints);
1023 params->string_params.pop_back();
1024 if (!blueprints->empty()) blueprints->pop_back();
1031 const std::string& fragment = child.key;
1032 if (req_url.compare(pos, fragment.size(), fragment) == 0)
1034 found_fragment =
true;
1035 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1036 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
1038 if (!blueprints->empty()) blueprints->pop_back();
1043 if (!found_fragment)
1044 found_BP = std::move(*blueprints);
1046 return routing_handle_result{found, found_BP, match_params};
1049 routing_handle_result find(
const std::string& req_url)
const
1051 return find(req_url, head_);
1055 void add(
const std::string& url,
size_t rule_index,
unsigned bp_prefix_length = 0,
size_t blueprint_index = INVALID_BP_ID)
1059 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1061 for (
unsigned i = 0; i < url.size(); i++)
1066 static struct ParamTraits
1072 {ParamType::INT,
"<int>"},
1073 {ParamType::UINT,
"<uint>"},
1074 {ParamType::DOUBLE,
"<float>"},
1075 {ParamType::DOUBLE,
"<double>"},
1076 {ParamType::STRING,
"<str>"},
1077 {ParamType::STRING,
"<string>"},
1078 {ParamType::PATH,
"<path>"},
1081 for (
const auto& x : paramTraits)
1083 if (url.compare(i, x.name.size(), x.name) == 0)
1086 for (
auto& child : idx->children)
1088 if (child.param == x.type)
1099 auto new_node_idx = &idx->add_child_node();
1100 new_node_idx->param = x.type;
1112 bool piece_found =
false;
1113 for (
auto& child : idx->children)
1115 if (child.key[0] == c)
1124 auto new_node_idx = &idx->add_child_node();
1125 new_node_idx->key = c;
1127 if (has_blueprint && i == bp_prefix_length)
1128 new_node_idx->blueprint_index = blueprint_index;
1135 if (idx->rule_index)
1136 throw std::runtime_error(
"handler already exists for " + url);
1137 idx->rule_index = rule_index;
1308 Router() : using_ssl(
false)
1311 DynamicRule& new_rule_dynamic(
const std::string& rule)
1314 all_rules_.emplace_back(ruleObject);
1319 template<u
int64_t N>
1320 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1322 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1324 return new_rule<RuleT>(rule);
1327 template<
typename RuleT=StaticRule>
1328 auto& new_rule(
const std::string& rule)
1330 auto ruleObject =
new RuleT(rule);
1331 all_rules_.emplace_back(ruleObject);
1338 return catchall_rule_;
1341 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1343 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1346 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const size_t& BP_index, std::vector<Blueprint*>& blueprints)
1348 bool has_trailing_slash =
false;
1349 std::string rule_without_trailing_slash;
1350 if (rule.size() > 1 && rule.back() ==
'/')
1352 has_trailing_slash =
true;
1353 rule_without_trailing_slash = rule;
1354 rule_without_trailing_slash.pop_back();
1357 ruleObject->mw_indices_.pack();
1359 ruleObject->foreach_method([&](
int method) {
1360 per_methods_[method].rules.emplace_back(ruleObject);
1361 per_methods_[method].trie.add(rule, per_methods_[method].rules.size() - 1,
1362 BP_index != INVALID_BP_ID ? blueprints[BP_index]->prefix().length() : 0,
1367 if (has_trailing_slash)
1369 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);
1373 ruleObject->set_added();
1376 void register_blueprint(
Blueprint& blueprint)
1378 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1380 blueprints_.emplace_back(&blueprint);
1383 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1386 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1389 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1391 for (
Blueprint* bp : blueprint->blueprints_)
1393 get_recursive_child_methods(bp, methods);
1396 else if (!blueprint->static_dir_.empty())
1397 methods.emplace_back(HTTPMethod::Get);
1398 for (
auto& rule : blueprint->all_rules_)
1400 rule->foreach_method([&methods](
unsigned method) {
1401 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1402 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1403 methods.emplace_back(method_final);
1412 validate_bp(blueprints_, blueprint_mw);
1417 for (
unsigned i = 0; i < blueprints.size(); i++)
1421 if (blueprint->is_added())
continue;
1423 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1425 std::vector<HTTPMethod> methods;
1426 get_recursive_child_methods(blueprint, methods);
1427 for (HTTPMethod x : methods)
1429 int method_index =
static_cast<int>(x);
1430 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1434 current_mw.merge_back(blueprint->mw_indices_);
1435 for (
auto& rule : blueprint->all_rules_)
1437 if (rule && !rule->is_added())
1439 auto upgraded = rule->upgrade();
1441 rule = std::move(upgraded);
1443 rule->mw_indices_.merge_front(current_mw);
1444 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1447 validate_bp(blueprint->blueprints_, current_mw);
1448 current_mw.pop_back(blueprint->mw_indices_);
1449 blueprint->set_added();
1455 for (
auto& rule : all_rules_)
1457 if (rule && !rule->is_added())
1459 auto upgraded = rule->upgrade();
1461 rule = std::move(upgraded);
1463 internal_add_rule_object(rule->rule(), rule.get());
1466 for (
auto& per_method : per_methods_)
1468 per_method.trie.validate();
1473 template<
typename Adaptor>
1474 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1476 if (req.method >= HTTPMethod::InternalMethodCount)
1479 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1480 auto& rules = per_method.rules;
1481 size_t rule_index = per_method.trie.find(req.
url).rule_index;
1485 for (
auto& method : per_methods_)
1487 if (method.trie.find(req.
url).rule_index)
1489 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1496 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1502 if (rule_index >= rules.size())
1503 throw std::runtime_error(
"Trie internal structure corrupted!");
1505 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1507 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1514 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' "
1515 <<
static_cast<uint64_t
>(req.method) <<
" / "
1516 << rules[rule_index]->get_methods();
1520 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1524 exception_handler_(res);
1530 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)
1540 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1542 bp_i[index] < blueprints.size() &&
1543 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1545 if (index < bp_i.size())
1548 if (verify_prefix())
1550 found_bps.push_back(blueprints[bp_i[index]]);
1551 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1555 if (found_bps.size() < 2)
1558 found_bps.push_back(blueprints_[bp_i[index]]);
1562 found_bps.pop_back();
1563 Blueprint* last_element = found_bps.back();
1564 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1566 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1572 std::vector<Blueprint*> bps_found;
1573 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1574 if (!bps_found.empty()) {
1575 for (
size_t i = bps_found.size() - 1; i > 0; i--)
1577 if (bps_found[i]->catchall_rule().has_handler()) {
1578 return bps_found[i]->catchall_rule();
1582 return catchall_rule_;
1587 const std::string EMPTY;
1589 std::vector<Blueprint*> bps_found;
1590 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1591 if (!bps_found.empty()) {
1592 for (
size_t i = bps_found.size() - 1; i > 0; i--) {
1593 if (bps_found[i]->catchall_rule().has_handler()) {
1594#ifdef CROW_ENABLE_DEBUG
1595 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1601 }
else if (catchall_rule_.has_handler()) {
1602#ifdef CROW_ENABLE_DEBUG
1603 return std::string(
"Redirected to global Catchall rule");
1611 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1613 HTTPMethod method_actual = req.method;
1615 std::unique_ptr<routing_handle_result> found{
1618 std::vector<size_t>(),
1620 HTTPMethod::InternalMethodCount)};
1623 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1625 else if (req.method == HTTPMethod::Head)
1627 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1629 if (!found->rule_index)
1631 method_actual = HTTPMethod::Get;
1632 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1633 if (!found->rule_index)
1635 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1643 found->method = method_actual;
1646 else if (req.method == HTTPMethod::Options)
1648 std::string allow =
"OPTIONS, HEAD";
1650 if (req.
url ==
"/*")
1652 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1654 if (
static_cast<int>(HTTPMethod::Head) == i)
1657 if (!per_methods_[i].trie.is_empty())
1660 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1663#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1666 res =
response(crow::status::NO_CONTENT);
1671 found->method = method_actual;
1676 bool rules_matched =
false;
1677 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1679 if (per_methods_[i].trie.find(req.
url).rule_index)
1681 rules_matched =
true;
1683 if (
static_cast<int>(HTTPMethod::Head) == i)
1687 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1692#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1695 res =
response(crow::status::NO_CONTENT);
1699 found->method = method_actual;
1704 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1713 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1715 if (!found->rule_index)
1717 for (
auto& per_method : per_methods_)
1719 if (per_method.trie.find(req.
url).rule_index)
1722 found->catch_all =
true;
1723 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" "
1724 << method_name(method_actual) <<
". " << get_error(*found);
1731 found->catch_all =
true;
1732 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << get_error(*found);
1736 found->method = method_actual;
1741 template<
typename App>
1744 if (found.catch_all) {
1745 auto catch_all = get_catch_all(found);
1746 if (catch_all.has_handler()) {
1749 catch_all.handler_(req, res);
1753 exception_handler_(res);
1758 HTTPMethod method_actual = found.method;
1759 const auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1760 const size_t rule_index = found.rule_index;
1762 if (rule_index >= rules.size())
1763 throw std::runtime_error(
"Trie internal structure corrupted!");
1764 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH) {
1765 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1770 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint64_t
>(req.
1771 method) <<
" / " << rules[rule_index]->get_methods();
1774 BaseRule &rule = *rules[rule_index];
1775 handle_rule<App>(rule, req, res, found.r_params);
1777 exception_handler_(res);
1784 template<
typename App>
1785 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1788 if (!rule.mw_indices_.empty())
1790 auto& ctx = *
reinterpret_cast<typename
App::context_t*
>(req.middleware_context);
1791 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1794 auto glob_completion_handler = std::move(res.complete_request_handler_);
1795 res.complete_request_handler_ = [] {};
1797 detail::middleware_call_helper<
decltype(crit_fwd),
1798 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1802 glob_completion_handler();
1806 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1809 detail::after_handlers_call_helper<
1811 std::tuple_size<typename App::mw_container_t>::value - 1,
1813 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1814 glob_completion_handler();
1817 rule.handle(req, res, rp);
1820 template<
typename App>
1821 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1824 rule.handle(req, res, rp);
1829 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1831 Trie& trie_ = per_methods_[i].trie;
1834 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1835 trie_.debug_print();
1840 std::vector<Blueprint*>& blueprints()
1847 return exception_handler_;
1850 static void default_exception_handler(
response& res)
1862 res.
body = e.what();
1864 catch (
const std::exception& e)
1866 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1870 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1879 std::vector<BaseRule*> rules;
1886 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1887 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1888 std::vector<Blueprint*> blueprints_;
1889 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;