730 uint16_t rule_index{};
732 uint16_t blueprint_index{INVALID_BP_ID};
734 ParamType param = ParamType::MAX;
735 std::vector<Node> children;
737 bool IsSimpleNode()
const
739 return !rule_index &&
740 blueprint_index == INVALID_BP_ID &&
741 children.size() < 2 &&
742 param == ParamType::MAX &&
743 std::all_of(std::begin(children), std::end(children), [](
const Node& x) {
744 return x.param == ParamType::MAX;
748 Node& add_child_node()
750 children.emplace_back();
751 return children.back();
762 return head_.children.empty();
767 for (
auto& child : head_.children)
775 void optimizeNode(Node& node)
777 if (node.children.empty())
779 if (node.IsSimpleNode())
781 auto children_temp = std::move(node.children);
782 auto& child_temp = children_temp[0];
783 node.key += child_temp.key;
784 node.rule_index = child_temp.rule_index;
785 node.blueprint_index = child_temp.blueprint_index;
786 node.children = std::move(child_temp.children);
791 for (
auto& child : node.children)
798 void debug_node_print(
const Node& node,
size_t level)
800 if (node.param != ParamType::MAX)
805 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
808 case ParamType::UINT:
809 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
812 case ParamType::DOUBLE:
813 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
816 case ParamType::STRING:
817 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
820 case ParamType::PATH:
821 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
825 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ "
831 CROW_LOG_DEBUG << std::string(3 * level,
' ') <<
"└➝ " << node.key;
833 for (
const auto& child : node.children)
835 debug_node_print(child, level + 1);
842 CROW_LOG_DEBUG <<
"└➙ ROOT";
843 for (
const auto& child : head_.children)
844 debug_node_print(child, 1);
849 if (!head_.IsSimpleNode())
850 throw std::runtime_error(
"Internal error: Trie header should be simple!");
855 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
858 routing_params empty;
859 if (params ==
nullptr)
862 std::vector<uint16_t> MT;
863 if (blueprints ==
nullptr)
867 std::vector<uint16_t> found_BP;
868 routing_params match_params;
870 auto update_found = [&found, &found_BP, &match_params](routing_handle_result& ret) {
871 found_BP = std::move(ret.blueprint_indices);
872 if (ret.rule_index && (!found || found > ret.rule_index))
874 found = ret.rule_index;
875 match_params = std::move(ret.r_params);
880 if (pos == req_url.size())
882 found_BP = std::move(*blueprints);
883 return routing_handle_result{node.rule_index, *blueprints, *params};
886 bool found_fragment =
false;
888 for (
const auto& child : node.children)
890 if (child.param != ParamType::MAX)
892 if (child.param == ParamType::INT)
894 char c = req_url[pos];
895 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-')
899 long long int value = strtoll(req_url.data() + pos, &eptr, 10);
900 if (errno != ERANGE && eptr != req_url.data() + pos)
902 found_fragment =
true;
903 params->int_params.push_back(value);
904 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
905 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
907 params->int_params.pop_back();
908 if (!blueprints->empty()) blueprints->pop_back();
913 else if (child.param == ParamType::UINT)
915 char c = req_url[pos];
916 if ((c >=
'0' && c <=
'9') || c ==
'+')
920 unsigned long long int value = strtoull(req_url.data() + pos, &eptr, 10);
921 if (errno != ERANGE && eptr != req_url.data() + pos)
923 found_fragment =
true;
924 params->uint_params.push_back(value);
925 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
926 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
928 params->uint_params.pop_back();
929 if (!blueprints->empty()) blueprints->pop_back();
934 else if (child.param == ParamType::DOUBLE)
936 char c = req_url[pos];
937 if ((c >=
'0' && c <=
'9') || c ==
'+' || c ==
'-' || c ==
'.')
941 double value = strtod(req_url.data() + pos, &eptr);
942 if (errno != ERANGE && eptr != req_url.data() + pos)
944 found_fragment =
true;
945 params->double_params.push_back(value);
946 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
947 auto ret = find(req_url, child, eptr - req_url.data(), params, blueprints);
949 params->double_params.pop_back();
950 if (!blueprints->empty()) blueprints->pop_back();
955 else if (child.param == ParamType::STRING)
958 for (; epos < req_url.size(); epos++)
960 if (req_url[epos] ==
'/')
966 found_fragment =
true;
967 params->string_params.push_back(req_url.substr(pos, epos - pos));
968 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
969 auto ret = find(req_url, child, epos, params, blueprints);
971 params->string_params.pop_back();
972 if (!blueprints->empty()) blueprints->pop_back();
976 else if (child.param == ParamType::PATH)
978 size_t epos = req_url.size();
982 found_fragment =
true;
983 params->string_params.push_back(req_url.substr(pos, epos - pos));
984 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
985 auto ret = find(req_url, child, epos, params, blueprints);
987 params->string_params.pop_back();
988 if (!blueprints->empty()) blueprints->pop_back();
995 const std::string& fragment = child.key;
996 if (req_url.compare(pos, fragment.size(), fragment) == 0)
998 found_fragment =
true;
999 if (child.blueprint_index != INVALID_BP_ID) blueprints->push_back(child.blueprint_index);
1000 auto ret = find(req_url, child, pos + fragment.size(), params, blueprints);
1002 if (!blueprints->empty()) blueprints->pop_back();
1007 if (!found_fragment)
1008 found_BP = std::move(*blueprints);
1010 return routing_handle_result{found, found_BP, match_params};
1013 routing_handle_result find(
const std::string& req_url)
const
1015 return find(req_url, head_);
1019 void add(
const std::string& url, uint16_t rule_index,
unsigned bp_prefix_length = 0, uint16_t blueprint_index = INVALID_BP_ID)
1023 bool has_blueprint = bp_prefix_length != 0 && blueprint_index != INVALID_BP_ID;
1025 for (
unsigned i = 0; i < url.size(); i++)
1030 static struct ParamTraits
1036 {ParamType::INT,
"<int>"},
1037 {ParamType::UINT,
"<uint>"},
1038 {ParamType::DOUBLE,
"<float>"},
1039 {ParamType::DOUBLE,
"<double>"},
1040 {ParamType::STRING,
"<str>"},
1041 {ParamType::STRING,
"<string>"},
1042 {ParamType::PATH,
"<path>"},
1045 for (
const auto& x : paramTraits)
1047 if (url.compare(i, x.name.size(), x.name) == 0)
1050 for (
auto& child : idx->children)
1052 if (child.param == x.type)
1063 auto new_node_idx = &idx->add_child_node();
1064 new_node_idx->param = x.type;
1076 bool piece_found =
false;
1077 for (
auto& child : idx->children)
1079 if (child.key[0] == c)
1088 auto new_node_idx = &idx->add_child_node();
1089 new_node_idx->key = c;
1091 if (has_blueprint && i == bp_prefix_length)
1092 new_node_idx->blueprint_index = blueprint_index;
1099 if (idx->rule_index)
1100 throw std::runtime_error(
"handler already exists for " + url);
1101 idx->rule_index = rule_index;
1272 Router() : using_ssl(
false)
1275 DynamicRule& new_rule_dynamic(
const std::string& rule)
1278 all_rules_.emplace_back(ruleObject);
1283 template<u
int64_t N>
1284 typename black_magic::arguments<N>::type::template rebind<TaggedRule>& new_rule_tagged(
const std::string& rule)
1286 using RuleT =
typename black_magic::arguments<N>::type::template rebind<TaggedRule>;
1288 auto ruleObject =
new RuleT(rule);
1289 all_rules_.emplace_back(ruleObject);
1296 return catchall_rule_;
1299 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject)
1301 internal_add_rule_object(rule, ruleObject, INVALID_BP_ID, blueprints_);
1304 void internal_add_rule_object(
const std::string& rule,
BaseRule* ruleObject,
const uint16_t& BP_index, std::vector<Blueprint*>& blueprints)
1306 bool has_trailing_slash =
false;
1307 std::string rule_without_trailing_slash;
1308 if (rule.size() > 1 && rule.back() ==
'/')
1310 has_trailing_slash =
true;
1311 rule_without_trailing_slash = rule;
1312 rule_without_trailing_slash.pop_back();
1315 ruleObject->mw_indices_.pack();
1317 ruleObject->foreach_method([&](
int method) {
1318 per_methods_[method].rules.emplace_back(ruleObject);
1319 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);
1323 if (has_trailing_slash)
1325 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);
1329 ruleObject->set_added();
1332 void register_blueprint(
Blueprint& blueprint)
1334 if (std::find(blueprints_.begin(), blueprints_.end(), &blueprint) == blueprints_.end())
1336 blueprints_.emplace_back(&blueprint);
1339 throw std::runtime_error(
"blueprint \"" + blueprint.prefix_ +
"\" already exists in router");
1342 void get_recursive_child_methods(
Blueprint* blueprint, std::vector<HTTPMethod>& methods)
1345 if (blueprint->static_dir_.empty() && blueprint->all_rules_.empty())
1347 for (
Blueprint* bp : blueprint->blueprints_)
1349 get_recursive_child_methods(bp, methods);
1352 else if (!blueprint->static_dir_.empty())
1353 methods.emplace_back(HTTPMethod::Get);
1354 for (
auto& rule : blueprint->all_rules_)
1356 rule->foreach_method([&methods](
unsigned method) {
1357 HTTPMethod method_final =
static_cast<HTTPMethod
>(method);
1358 if (std::find(methods.begin(), methods.end(), method_final) == methods.end())
1359 methods.emplace_back(method_final);
1368 validate_bp(blueprints_, blueprint_mw);
1373 for (
unsigned i = 0; i < blueprints.size(); i++)
1377 if (blueprint->is_added())
continue;
1379 if (blueprint->static_dir_ ==
"" && blueprint->all_rules_.empty())
1381 std::vector<HTTPMethod> methods;
1382 get_recursive_child_methods(blueprint, methods);
1383 for (HTTPMethod x : methods)
1385 int method_index =
static_cast<int>(x);
1386 per_methods_[method_index].trie.add(blueprint->prefix(), 0, blueprint->prefix().length(), method_index);
1390 current_mw.merge_back(blueprint->mw_indices_);
1391 for (
auto& rule : blueprint->all_rules_)
1393 if (rule && !rule->is_added())
1395 auto upgraded = rule->upgrade();
1397 rule = std::move(upgraded);
1399 rule->mw_indices_.merge_front(current_mw);
1400 internal_add_rule_object(rule->rule(), rule.get(), i, blueprints);
1403 validate_bp(blueprint->blueprints_, current_mw);
1404 current_mw.pop_back(blueprint->mw_indices_);
1405 blueprint->set_added();
1411 for (
auto& rule : all_rules_)
1413 if (rule && !rule->is_added())
1415 auto upgraded = rule->upgrade();
1417 rule = std::move(upgraded);
1419 internal_add_rule_object(rule->rule(), rule.get());
1422 for (
auto& per_method : per_methods_)
1424 per_method.trie.validate();
1429 template<
typename Adaptor>
1430 void handle_upgrade(
const request& req,
response& res, Adaptor&& adaptor)
1432 if (req.method >= HTTPMethod::InternalMethodCount)
1435 auto& per_method = per_methods_[
static_cast<int>(req.method)];
1436 auto& rules = per_method.rules;
1437 unsigned rule_index = per_method.trie.find(req.
url).rule_index;
1441 for (
auto& method : per_methods_)
1443 if (method.trie.find(req.
url).rule_index)
1445 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" " << method_name(req.method);
1452 CROW_LOG_INFO <<
"Cannot match rules " << req.
url;
1458 if (rule_index >= rules.size())
1459 throw std::runtime_error(
"Trie internal structure corrupted!");
1461 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH)
1463 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1470 CROW_LOG_DEBUG <<
"Matched rule (upgrade) '" << rules[rule_index]->rule_ <<
"' "
1471 <<
static_cast<uint32_t
>(req.method) <<
" / "
1472 << rules[rule_index]->get_methods();
1476 rules[rule_index]->handle_upgrade(req, res, std::move(adaptor));
1480 exception_handler_(res);
1486 void get_found_bp(
const std::vector<uint16_t>& bp_i,
const std::vector<Blueprint*>& blueprints, std::vector<Blueprint*>& found_bps, uint16_t index = 0)
1496 auto verify_prefix = [&bp_i, &index, &blueprints, &found_bps]() {
1498 bp_i[index] < blueprints.size() &&
1499 blueprints[bp_i[index]]->prefix().substr(0, found_bps[index - 1]->prefix().length() + 1).compare(std::string(found_bps[index - 1]->prefix() +
'/')) == 0;
1501 if (index < bp_i.size())
1504 if (verify_prefix())
1506 found_bps.push_back(blueprints[bp_i[index]]);
1507 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1511 if (found_bps.size() < 2)
1514 found_bps.push_back(blueprints_[bp_i[index]]);
1518 found_bps.pop_back();
1519 Blueprint* last_element = found_bps.back();
1520 found_bps.push_back(last_element->blueprints_[bp_i[index]]);
1522 get_found_bp(bp_i, found_bps.back()->blueprints_, found_bps, ++index);
1528 std::vector<Blueprint*> bps_found;
1529 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1530 for (
int i = bps_found.size() - 1; i > 0; i--)
1532 std::vector<uint16_t> bpi = found.blueprint_indices;
1533 if (bps_found[i]->catchall_rule().has_handler()) {
1534 return bps_found[i]->catchall_rule();
1537 return catchall_rule_;
1542 const std::string EMPTY;
1544 std::vector<Blueprint*> bps_found;
1545 get_found_bp(found.blueprint_indices, blueprints_, bps_found);
1546 for (
int i = bps_found.size() - 1; i > 0; i--)
1548 std::vector<uint16_t> bpi = found.blueprint_indices;
1549 if (bps_found[i]->catchall_rule().has_handler())
1551#ifdef CROW_ENABLE_DEBUG
1552 return std::string(
"Redirected to Blueprint \"" + bps_found[i]->prefix() +
"\" Catchall rule");
1558 if (catchall_rule_.has_handler())
1560#ifdef CROW_ENABLE_DEBUG
1561 return std::string(
"Redirected to global Catchall rule");
1569 std::unique_ptr<routing_handle_result> handle_initial(
request& req,
response& res)
1571 HTTPMethod method_actual = req.method;
1573 std::unique_ptr<routing_handle_result> found{
1576 std::vector<uint16_t>(),
1578 HTTPMethod::InternalMethodCount)};
1581 if (CROW_UNLIKELY(req.method >= HTTPMethod::InternalMethodCount))
1583 else if (req.method == HTTPMethod::Head)
1585 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1587 if (!found->rule_index)
1589 method_actual = HTTPMethod::Get;
1590 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1591 if (!found->rule_index)
1593 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1601 found->method = method_actual;
1604 else if (req.method == HTTPMethod::Options)
1606 std::string allow =
"OPTIONS, HEAD";
1608 if (req.
url ==
"/*")
1610 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1612 if (
static_cast<int>(HTTPMethod::Head) == i)
1615 if (!per_methods_[i].trie.is_empty())
1618 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1621#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1624 res =
response(crow::status::NO_CONTENT);
1629 found->method = method_actual;
1634 bool rules_matched =
false;
1635 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1637 if (per_methods_[i].trie.find(req.
url).rule_index)
1639 rules_matched =
true;
1641 if (
static_cast<int>(HTTPMethod::Head) == i)
1645 allow.append(method_name(
static_cast<HTTPMethod
>(i)));
1650#ifdef CROW_RETURNS_OK_ON_HTTP_OPTIONS_REQUEST
1653 res =
response(crow::status::NO_CONTENT);
1657 found->method = method_actual;
1662 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url;
1671 *found = per_methods_[
static_cast<int>(method_actual)].trie.find(req.
url);
1673 if (!found->rule_index)
1675 for (
auto& per_method : per_methods_)
1677 if (per_method.trie.find(req.
url).rule_index)
1680 found->catch_all =
true;
1681 CROW_LOG_DEBUG <<
"Cannot match method " << req.
url <<
" "
1682 << method_name(method_actual) <<
". " << get_error(*found);
1689 found->catch_all =
true;
1690 CROW_LOG_DEBUG <<
"Cannot match rules " << req.
url <<
". " << get_error(*found);
1694 found->method = method_actual;
1699 template<
typename App>
1702 if (found.catch_all) {
1703 auto catch_all = get_catch_all(found);
1704 if (catch_all.has_handler()) {
1707 catch_all.handler_(req, res);
1711 exception_handler_(res);
1716 HTTPMethod method_actual = found.method;
1717 const auto& rules = per_methods_[
static_cast<int>(method_actual)].rules;
1718 const unsigned rule_index = found.rule_index;
1720 if (rule_index >= rules.size())
1721 throw std::runtime_error(
"Trie internal structure corrupted!");
1722 if (rule_index == RULE_SPECIAL_REDIRECT_SLASH) {
1723 CROW_LOG_INFO <<
"Redirecting to a url with trailing slash: " << req.
url;
1728 CROW_LOG_DEBUG <<
"Matched rule '" << rules[rule_index]->rule_ <<
"' " <<
static_cast<uint32_t
>(req.
1729 method) <<
" / " << rules[rule_index]->get_methods();
1732 BaseRule &rule = *rules[rule_index];
1733 handle_rule<App>(rule, req, res, found.r_params);
1735 exception_handler_(res);
1742 template<
typename App>
1743 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value != 0,
void>::type
1746 if (!rule.mw_indices_.empty())
1748 auto& ctx = *
reinterpret_cast<typename
App::context_t*
>(req.middleware_context);
1749 auto& container = *
reinterpret_cast<typename App::mw_container_t*
>(req.middleware_container);
1752 auto glob_completion_handler = std::move(res.complete_request_handler_);
1753 res.complete_request_handler_ = [] {};
1755 detail::middleware_call_helper<
decltype(crit_fwd),
1756 0,
typename App::context_t,
typename App::mw_container_t>(crit_fwd, container, req, res, ctx);
1760 glob_completion_handler();
1764 res.complete_request_handler_ = [&rule, &ctx, &container, &req, &res, glob_completion_handler] {
1767 detail::after_handlers_call_helper<
1769 std::tuple_size<typename App::mw_container_t>::value - 1,
1771 typename App::mw_container_t>(crit_bwd, container, ctx, req, res);
1772 glob_completion_handler();
1775 rule.handle(req, res, rp);
1778 template<
typename App>
1779 typename std::enable_if<std::tuple_size<typename App::mw_container_t>::value == 0,
void>::type
1782 rule.handle(req, res, rp);
1787 for (
int i = 0; i < static_cast<int>(HTTPMethod::InternalMethodCount); i++)
1789 Trie& trie_ = per_methods_[i].trie;
1792 CROW_LOG_DEBUG << method_name(static_cast<HTTPMethod>(i));
1793 trie_.debug_print();
1798 std::vector<Blueprint*>& blueprints()
1805 return exception_handler_;
1808 static void default_exception_handler(
response& res)
1820 res.
body = e.what();
1822 catch (
const std::exception& e)
1824 CROW_LOG_ERROR <<
"An uncaught exception occurred: " << e.what();
1828 CROW_LOG_ERROR <<
"An uncaught exception occurred. The type was unknown so no information was available.";
1837 std::vector<BaseRule*> rules;
1844 std::array<PerMethod, static_cast<int>(HTTPMethod::InternalMethodCount)> per_methods_;
1845 std::vector<std::unique_ptr<BaseRule>> all_rules_;
1846 std::vector<Blueprint*> blueprints_;
1847 std::function<void(
crow::response&)> exception_handler_ = &default_exception_handler;