719 uint16_t rule_index{};
721 uint16_t blueprint_index{INVALID_BP_ID};
723 ParamType param = ParamType::MAX;
724 std::vector<Node> children;
726 bool IsSimpleNode()
const
728 return !rule_index &&
729 blueprint_index == INVALID_BP_ID &&
730 children.size() < 2 &&
731 param == ParamType::MAX &&
732 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
733 return x.param == ParamType::MAX;
737 Node& add_child_node()
739 children.emplace_back();
740 return children.back();
751 return head_.children.empty();
756 for (
auto& child : head_.children)
764 void optimizeNode(Node& node)
766 if (node.children.empty())
768 if (node.IsSimpleNode())
770 auto children_temp = std::move(node.children);
771 auto& child_temp = children_temp[0];
772 node.key += child_temp.key;
773 node.rule_index = child_temp.rule_index;
774 node.blueprint_index = child_temp.blueprint_index;
775 node.children = std::move(child_temp.children);
780 for (
auto& child : node.children)
787 void debug_node_print(
const Node& node,
size_t level)
789 if (node.param != ParamType::MAX)
794 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
797 case ParamType::UINT:
798 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
801 case ParamType::DOUBLE:
802 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
805 case ParamType::STRING:
806 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
809 case ParamType::PATH:
810 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
814 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
820 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
822 for (
const auto& child : node.children)
824 debug_node_print(child, level + 1);
831 CROW_LOG_DEBUG <<
"└➙ ROOT";
832 for (
const auto& child : head_.children)
833 debug_node_print(child, 1);
838 if (!head_.IsSimpleNode())
839 throw std::runtime_error(
"Internal error: Trie header should be simple!");
844 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
847 routing_params empty;
848 if (params ==
nullptr)
851 std::vector<uint16_t> MT;
852 if (blueprints ==
nullptr)
856 std::vector<uint16_t> found_BP;
857 routing_params match_params;
859 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
860 found_BP = std::move(ret.blueprint_indices);
861 if (ret.rule_index && (!found || found > ret.rule_index))
863 found = ret.rule_index;
864 match_params = std::move(ret.r_params);
869 if (pos == req_url.size())
871 found_BP = std::move(*blueprints);
872 return routing_handle_result{node.rule_index, *blueprints, *params};
875 bool found_fragment =
false;
877 for (
const auto& child : node.children)
879 if (child.param != ParamType::MAX)
881 if (child.param == ParamType::INT)
883 char c = req_url[pos];
884 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
888 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
889 if (errno != ERANGE && eptr != req_url.data() + pos)
891 found_fragment =
true;
892 params->int_params.push_back(value);
893 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
894 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
896 params->int_params.pop_back();
897 if (!blueprints->empty()) blueprints->pop_back();
902 else if (child.param == ParamType::UINT)
904 char c = req_url[pos];
905 if ((c >=
'0' && c <=
'9') || c ==
'+')
909 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
910 if (errno != ERANGE && eptr != req_url.data() + pos)
912 found_fragment =
true;
913 params->uint_params.push_back(value);
914 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
915 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
917 params->uint_params.pop_back();
918 if (!blueprints->empty()) blueprints->pop_back();
923 else if (child.param == ParamType::DOUBLE)
925 char c = req_url[pos];
926 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
930 double value = strtod(req_url.data() + pos, &eptr);
931 if (errno != ERANGE && eptr != req_url.data() + pos)
933 found_fragment =
true;
934 params->double_params.push_back(value);
935 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
936 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
938 params->double_params.pop_back();
939 if (!blueprints->empty()) blueprints->pop_back();
944 else if (child.param == ParamType::STRING)
947 for (; epos < req_url.size(); epos++)
949 if (req_url[epos] ==
'/')
955 found_fragment =
true;
956 params->string_params.push_back(req_url.substr(pos, epos - pos));
957 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
958 auto ret = find(req_url, child, epos, params, blueprints);
960 params->string_params.pop_back();
961 if (!blueprints->empty()) blueprints->pop_back();
965 else if (child.param == ParamType::PATH)
967 size_t epos = req_url.size();
971 found_fragment =
true;
972 params->string_params.push_back(req_url.substr(pos, epos - pos));
973 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
974 auto ret = find(req_url, child, epos, params, blueprints);
976 params->string_params.pop_back();
977 if (!blueprints->empty()) blueprints->pop_back();
984 const std::string& fragment = child.key;
985 if (req_url.compare(pos, fragment.size(), fragment) == 0)
987 found_fragment =
true;
988 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
989 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
991 if (!blueprints->empty()) blueprints->pop_back();
997 found_BP = std::move(*blueprints);
999 return routing_handle_result{found, found_BP, match_params};
1002 routing_handle_result find(
const std::string& req_url)
const
1004 return find(req_url, head_);
1008 void add(
const std::string& url, uint16_t rule_index,
unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
1012 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1014 for (
unsigned i = 0; i < url.size(); i++)
1019 static struct ParamTraits
1025 {ParamType::INT,
"<int>"},
1026 {ParamType::UINT,
"<uint>"},
1027 {ParamType::DOUBLE,
"<float>"},
1028 {ParamType::DOUBLE,
"<double>"},
1029 {ParamType::STRING,
"<str>"},
1030 {ParamType::STRING,
"<string>"},
1031 {ParamType::PATH,
"<path>"},
1034 for (
const auto& x : paramTraits)
1036 if (url.compare(i, x.name.size(), x.name) == 0)
1039 for (
auto& child : idx->children)
1041 if (child.param == x.type)
1052 auto new_node_idx = &idx->add_child_node();
1053 new_node_idx->param = x.type;
1065 bool piece_found =
false;
1066 for (
auto& child : idx->children)
1068 if (child.key[0] == c)
1077 auto new_node_idx = &idx->add_child_node();
1078 new_node_idx->key = c;
1080 if (has_blueprint && i == bp_prefix_length)
1081 new_node_idx->blueprint_index = blueprint_index;
1088 if (idx->rule_index)
1089 throw std::runtime_error(
"handler already exists for " + url);
1090 idx->rule_index = rule_index;
1262 Router() : using_ssl(
false)
1265 DynamicRule& new_rule_dynamic(
const std::string& rule)
1268 all_rules_.emplace_back(ruleObject);
1273 template<u
int64_t N>
1274 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1276 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1278 auto ruleObject =
new RuleT(rule);
1279 all_rules_.emplace_back(ruleObject);
1286 return catchall_rule_;
1289 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1291 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1294 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
1296 bool has_trailing_slash =
false;
1297 std::string rule_without_trailing_slash;
1298 if (rule.size() > 1 && rule.back() ==
'/')
1300 has_trailing_slash =
true;
1301 rule_without_trailing_slash = rule;
1302 rule_without_trailing_slash.pop_back();
1305 ruleObject->mw_indices_.pack();
1307 ruleObject->foreach_method([&](
int method) {
1308 per_methods_[method].rules.emplace_back(ruleObject);
1309 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);
1313 if (has_trailing_slash)
1315 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);
1319 ruleObject->set_added();
1322 void register_blueprint(
Blueprint& blueprint)
1324 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1326 blueprints_.emplace_back(&blueprint);
1329 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1332 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1335 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1337 for (
Blueprint* bp : blueprint->blueprints_)
1339 get_recursive_child_methods(bp, methods);
1342 else if (!blueprint->static_dir_.empty())
1343 methods.emplace_back(HTTPMethod::Get);
1344 for (
auto& rule : blueprint->all_rules_)
1346 rule->foreach_method([&methods](
unsigned method) {
1347 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1348 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1349 methods.emplace_back(method_final);
1358 validate_bp(blueprints_, blueprint_mw);
1363 for (
unsigned i = 0; i < blueprints.size(); i++)
1367 if (blueprint->is_added())
continue;
1369 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1371 std::vector<HTTPMethod> methods;
1372 get_recursive_child_methods(blueprint, methods);
1373 for (HTTPMethod x : methods)
1375 int method_index =
static_cast<int>(x);
1376 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1380 current_mw.merge_back(blueprint->mw_indices_);
1381 for (
auto& rule : blueprint->all_rules_)
1383 if (rule && !rule->is_added())
1385 auto upgraded = rule->upgrade();
1387 rule = std::move(upgraded);
1389 rule->mw_indices_.merge_front(current_mw);
1390 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1393 validate_bp(blueprint->blueprints_, current_mw);
1394 current_mw.pop_back(blueprint->mw_indices_);
1395 blueprint->set_added();
1401 for (
auto& rule : all_rules_)
1403 if (rule && !rule->is_added())
1405 auto upgraded = rule->upgrade();
1407 rule = std::move(upgraded);
1409 internal_add_rule_object(rule->rule(), rule.get());
1412 for (
auto& per_method : per_methods_)
1414 per_method.trie.validate();
1419 template<
typename Adaptor>
1420 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1422 if (req.method >= HTTPMethod::InternalMethodCount)
1425 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1426 auto& rules = per_method.rules;
1427 unsigned rule_index = per_method.trie.find(req.
url).rule_index;
1431 for (
auto& method : per_methods_)
1433 if (method.trie.find(req.
url).rule_index)
1435 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1442 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1448 if (rule_index >= rules.size())
1449 throw std::runtime_error(
"Trie internal structure corrupted!");
1451 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1453 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1460 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1464 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1468 exception_handler_(res);
1474 void get_found_bp(std::vector<uint16_t>& bp_i, std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
1484 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1486 bp_i[index] < blueprints.size() &&
1487 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1489 if (index < bp_i.size())
1492 if (verify_prefix())
1494 found_bps.push_back(blueprints[bp_i[index]]);
1495 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1499 if (found_bps.size() < 2)
1502 found_bps.push_back(blueprints_[bp_i[index]]);
1506 found_bps.pop_back();
1507 Blueprint* last_element = found_bps.back();
1508 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1510 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1519 std::vector<Blueprint*> bps_found;
1520 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1521 for (
int i = bps_found.size() - 1; i > 0; i--)
1523 std::vector<uint16_t> bpi = found.blueprint_indices;
1524 if (bps_found[i]->catchall_rule().has_handler())
1528 bps_found[i]->catchall_rule().handler_(req, res);
1532 exception_handler_(res);
1534#ifdef CROW_ENABLE_DEBUG
1535 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1537 return std::string();
1541 if (catchall_rule_.has_handler())
1545 catchall_rule_.handler_(req, res);
1549 exception_handler_(res);
1551#ifdef CROW_ENABLE_DEBUG
1552 return std::string(
"Redirected to global Catchall rule");
1554 return std::string();
1557 return std::string();
1560 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1562 HTTPMethod method_actual = req.method;
1564 std::unique_ptr<routing_handle_result> found{
1567 std::vector<uint16_t>(),
1569 HTTPMethod::InternalMethodCount)};
1572 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1574 else if (req.method == HTTPMethod::Head)
1576 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1578 if (!found->rule_index)
1580 method_actual = HTTPMethod::Get;
1581 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1582 if (!found->rule_index)
1584 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1585 res = response(404);
1592 found->method = method_actual;
1595 else if (req.method == HTTPMethod::Options)
1597 std::string allow =
"OPTIONS, HEAD";
1599 if (req.
url ==
"/*")
1601 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1603 if (
static_cast<int>(HTTPMethod::Head) == i)
1606 if (!per_methods_[i].trie.is_empty())
1609 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1612#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1613 res = response(crow::status::OK);
1615 res = response(crow::status::NO_CONTENT);
1620 found->method = method_actual;
1625 bool rules_matched =
false;
1626 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1628 if (per_methods_[i].trie.find(req.
url).rule_index)
1630 rules_matched =
true;
1632 if (
static_cast<int>(HTTPMethod::Head) == i)
1636 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1641#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1642 res = response(crow::status::OK);
1644 res = response(crow::status::NO_CONTENT);
1648 found->method = method_actual;
1653 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1654 res = response(404);
1662 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1664 if (!found->rule_index)
1666 for (
auto& per_method : per_methods_)
1668 if (per_method.trie.find(req.
url).rule_index)
1670 const std::string error_message(
get_error(405, *found, req, res));
1671 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(method_actual) <<
". " << error_message;
1678 const std::string error_message(
get_error(404, *found, req, res));
1679 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << error_message;
1684 found->method = method_actual;
1689 template<
typename App>
1690 void handle(request& req, response& res, routing_handle_result found)
1692 HTTPMethod method_actual = found.method;
1693 auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1694 unsigned rule_index = found.rule_index;
1696 if (rule_index >= rules.size())
1697 throw std::runtime_error(
"Trie internal structure corrupted!");
1699 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1701 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.url;
1702 res = response(301);
1703 res.add_header(
"Location", req.url +
"/");
1708 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.method) <<
" / " << rules[rule_index]->get_methods();
1712 BaseRule& rule = *rules[rule_index];
1713 handle_rule<App>(rule, req, res, found.r_params);
1717 exception_handler_(res);
1723 template<
typename App>
1724 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1727 if (!rule.mw_indices_.empty())
1729 auto& ctx = *
reinterpret_cast<typename App::context_t*
>(req.middleware_context);
1730 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1731 detail::middleware_call_criteria_dynamic<false> crit_fwd(rule.mw_indices_.indices());
1733 auto glob_completion_handler = std::move(res.complete_request_handler_);
1734 res.complete_request_handler_ = [] {};
1736 detail::middleware_call_helper<
decltype(crit_fwd),
1737 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1741 glob_completion_handler();
1745 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1746 detail::middleware_call_criteria_dynamic<true> crit_bwd(rule.mw_indices_.indices());
1748 detail::after_handlers_call_helper<
1750 std::tuple_size<typename App::mw_container_t>::value - 1,
1751 typename App::context_t,
1752 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1753 glob_completion_handler();
1756 rule.handle(req, res, rp);
1759 template<
typename App>
1760 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1763 rule.handle(req, res, rp);
1768 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1770 Trie& trie_ = per_methods_[i].trie;
1771 if (!trie_.is_empty())
1773 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1774 trie_.debug_print();
1779 std::vector<Blueprint*>& blueprints()
1786 return exception_handler_;
1789 static void default_exception_handler(response& res)
1792 res = response(500);
1798 catch (
const bad_request& e)
1800 res = response (400);
1801 res.body = e.what();
1803 catch (
const std::exception& e)
1805 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1809 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1814 CatchallRule catchall_rule_;
1818 std::vector<BaseRule*> rules;
1825 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1826 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1827 std::vector<Blueprint*> blueprints_;
1828 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;