blob: 613b54dc73b972363d467dab13dc19e269646410 [file] [log] [blame]
Ed Tanous7045c8d2017-04-03 10:04:37 -07001#pragma once
2
Ed Tanous3ccb3ad2023-01-13 17:40:03 -08003#include "async_resp.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07004#include "common.hpp"
Ed Tanous168e20c2021-12-13 14:39:53 -08005#include "dbus_utility.hpp"
Joseph Reynolds3bf4e632020-02-06 14:44:32 -06006#include "error_messages.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -07007#include "http_request.hpp"
8#include "http_response.hpp"
9#include "logging.hpp"
Tanousf00032d2018-11-05 01:18:10 -030010#include "privileges.hpp"
Ratan Gupta6f359562019-04-03 10:39:08 +053011#include "sessions.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070012#include "utility.hpp"
Ed Tanous3d183202023-03-10 09:21:58 -080013#include "utils/dbus_utils.hpp"
Ed Tanous2c9efc32022-07-31 22:08:26 -070014#include "verb.hpp"
Ed Tanous04e438c2020-10-03 08:06:26 -070015#include "websocket.hpp"
Ed Tanous1abe55e2018-09-05 08:30:59 -070016
Ed Tanous88a03c52022-03-14 10:16:07 -070017#include <boost/beast/ssl/ssl_stream.hpp>
Tanousf00032d2018-11-05 01:18:10 -030018#include <boost/container/flat_map.hpp>
Ed Tanous3d183202023-03-10 09:21:58 -080019#include <sdbusplus/unpack_properties.hpp>
Gunnar Mills1214b7e2020-06-04 10:11:30 -050020
Ed Tanouse0d918b2018-03-27 17:41:04 -070021#include <cerrno>
Ed Tanous7045c8d2017-04-03 10:04:37 -070022#include <cstdint>
Ed Tanouse0d918b2018-03-27 17:41:04 -070023#include <cstdlib>
Ed Tanous3dac7492017-08-02 13:46:20 -070024#include <limits>
Ed Tanous7045c8d2017-04-03 10:04:37 -070025#include <memory>
Ed Tanous2c9efc32022-07-31 22:08:26 -070026#include <optional>
Ed Tanous7045c8d2017-04-03 10:04:37 -070027#include <tuple>
Ed Tanous7045c8d2017-04-03 10:04:37 -070028#include <utility>
29#include <vector>
Ed Tanous9140a672017-04-24 17:01:32 -070030
Ed Tanous1abe55e2018-09-05 08:30:59 -070031namespace crow
32{
Tanousf00032d2018-11-05 01:18:10 -030033
Ed Tanous1abe55e2018-09-05 08:30:59 -070034class BaseRule
35{
36 public:
Ed Tanous4e23a442022-06-06 09:57:26 -070037 explicit BaseRule(const std::string& thisRule) : rule(thisRule)
Gunnar Mills1214b7e2020-06-04 10:11:30 -050038 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -070039
Ed Tanous0c0084a2019-10-24 15:57:51 -070040 virtual ~BaseRule() = default;
Ed Tanous7045c8d2017-04-03 10:04:37 -070041
Ed Tanousecd6a3a2022-01-07 09:18:40 -080042 BaseRule(const BaseRule&) = delete;
43 BaseRule(BaseRule&&) = delete;
44 BaseRule& operator=(const BaseRule&) = delete;
45 BaseRule& operator=(const BaseRule&&) = delete;
46
Ed Tanous1abe55e2018-09-05 08:30:59 -070047 virtual void validate() = 0;
48 std::unique_ptr<BaseRule> upgrade()
49 {
50 if (ruleToUpgrade)
Ed Tanous3174e4d2020-10-07 11:41:22 -070051 {
Ed Tanous1abe55e2018-09-05 08:30:59 -070052 return std::move(ruleToUpgrade);
Ed Tanous3174e4d2020-10-07 11:41:22 -070053 }
Ed Tanous1abe55e2018-09-05 08:30:59 -070054 return {};
55 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070056
Ed Tanous104f09c2022-01-25 09:56:04 -080057 virtual void handle(const Request& /*req*/,
zhanghch058d1b46d2021-04-01 11:18:24 +080058 const std::shared_ptr<bmcweb::AsyncResp>&,
59 const RoutingParams&) = 0;
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +053060#ifndef BMCWEB_ENABLE_SSL
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +053061 virtual void
62 handleUpgrade(const Request& /*req*/,
63 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
64 boost::asio::ip::tcp::socket&& /*adaptor*/)
Ed Tanous1abe55e2018-09-05 08:30:59 -070065 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +053066 asyncResp->res.result(boost::beast::http::status::not_found);
Ed Tanous1abe55e2018-09-05 08:30:59 -070067 }
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +053068#else
Ed Tanous104f09c2022-01-25 09:56:04 -080069 virtual void handleUpgrade(
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +053070 const Request& /*req*/,
71 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
Ed Tanous104f09c2022-01-25 09:56:04 -080072 boost::beast::ssl_stream<boost::asio::ip::tcp::socket>&& /*adaptor*/)
Ed Tanous1abe55e2018-09-05 08:30:59 -070073 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +053074 asyncResp->res.result(boost::beast::http::status::not_found);
Ed Tanous1abe55e2018-09-05 08:30:59 -070075 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070076#endif
77
Ed Tanous9eb808c2022-01-25 10:19:23 -080078 size_t getMethods() const
Ed Tanous1abe55e2018-09-05 08:30:59 -070079 {
80 return methodsBitfield;
81 }
Ed Tanous7045c8d2017-04-03 10:04:37 -070082
Tanousf00032d2018-11-05 01:18:10 -030083 bool checkPrivileges(const redfish::Privileges& userPrivileges)
84 {
85 // If there are no privileges assigned, assume no privileges
86 // required
87 if (privilegesSet.empty())
88 {
89 return true;
90 }
91
92 for (const redfish::Privileges& requiredPrivileges : privilegesSet)
93 {
94 if (userPrivileges.isSupersetOf(requiredPrivileges))
95 {
96 return true;
97 }
98 }
99 return false;
100 }
101
Ed Tanous2c9efc32022-07-31 22:08:26 -0700102 size_t methodsBitfield{1 << static_cast<size_t>(HttpVerb::Get)};
Ed Tanous44e45182022-07-26 16:47:23 -0700103 static_assert(std::numeric_limits<decltype(methodsBitfield)>::digits >
Ed Tanous759cf102022-07-31 16:36:52 -0700104 methodNotAllowedIndex,
Ed Tanous44e45182022-07-26 16:47:23 -0700105 "Not enough bits to store bitfield");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700106
Tanousf00032d2018-11-05 01:18:10 -0300107 std::vector<redfish::Privileges> privilegesSet;
108
Ed Tanous1abe55e2018-09-05 08:30:59 -0700109 std::string rule;
110 std::string nameStr;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700111
Ed Tanous1abe55e2018-09-05 08:30:59 -0700112 std::unique_ptr<BaseRule> ruleToUpgrade;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700113
Ed Tanous1abe55e2018-09-05 08:30:59 -0700114 friend class Router;
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500115 template <typename T>
116 friend struct RuleParameterTraits;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700117};
118
Ed Tanous1abe55e2018-09-05 08:30:59 -0700119namespace detail
120{
121namespace routing_handler_call_helper
122{
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500123template <typename T, int Pos>
124struct CallPair
Ed Tanous1abe55e2018-09-05 08:30:59 -0700125{
126 using type = T;
127 static const int pos = Pos;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700128};
129
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500130template <typename H1>
131struct CallParams
Ed Tanous1abe55e2018-09-05 08:30:59 -0700132{
133 H1& handler;
134 const RoutingParams& params;
135 const Request& req;
zhanghch058d1b46d2021-04-01 11:18:24 +0800136 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700137};
138
139template <typename F, int NInt, int NUint, int NDouble, int NString,
140 typename S1, typename S2>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700141struct Call
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500142{};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700143
144template <typename F, int NInt, int NUint, int NDouble, int NString,
145 typename... Args1, typename... Args2>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700146struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<int64_t, Args1...>,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700147 black_magic::S<Args2...>>
148{
149 void operator()(F cparams)
150 {
151 using pushed = typename black_magic::S<Args2...>::template push_back<
152 CallPair<int64_t, NInt>>;
153 Call<F, NInt + 1, NUint, NDouble, NString, black_magic::S<Args1...>,
154 pushed>()(cparams);
155 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700156};
157
158template <typename F, int NInt, int NUint, int NDouble, int NString,
159 typename... Args1, typename... Args2>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700160struct Call<F, NInt, NUint, NDouble, NString,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700161 black_magic::S<uint64_t, Args1...>, black_magic::S<Args2...>>
162{
163 void operator()(F cparams)
164 {
165 using pushed = typename black_magic::S<Args2...>::template push_back<
166 CallPair<uint64_t, NUint>>;
167 Call<F, NInt, NUint + 1, NDouble, NString, black_magic::S<Args1...>,
168 pushed>()(cparams);
169 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700170};
171
172template <typename F, int NInt, int NUint, int NDouble, int NString,
173 typename... Args1, typename... Args2>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700174struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<double, Args1...>,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700175 black_magic::S<Args2...>>
176{
177 void operator()(F cparams)
178 {
179 using pushed = typename black_magic::S<Args2...>::template push_back<
180 CallPair<double, NDouble>>;
181 Call<F, NInt, NUint, NDouble + 1, NString, black_magic::S<Args1...>,
182 pushed>()(cparams);
183 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700184};
185
186template <typename F, int NInt, int NUint, int NDouble, int NString,
187 typename... Args1, typename... Args2>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700188struct Call<F, NInt, NUint, NDouble, NString,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700189 black_magic::S<std::string, Args1...>, black_magic::S<Args2...>>
190{
191 void operator()(F cparams)
192 {
193 using pushed = typename black_magic::S<Args2...>::template push_back<
194 CallPair<std::string, NString>>;
195 Call<F, NInt, NUint, NDouble, NString + 1, black_magic::S<Args1...>,
196 pushed>()(cparams);
197 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700198};
199
200template <typename F, int NInt, int NUint, int NDouble, int NString,
201 typename... Args1>
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700202struct Call<F, NInt, NUint, NDouble, NString, black_magic::S<>,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700203 black_magic::S<Args1...>>
204{
205 void operator()(F cparams)
206 {
207 cparams.handler(
zhanghch058d1b46d2021-04-01 11:18:24 +0800208 cparams.req, cparams.asyncResp,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700209 cparams.params.template get<typename Args1::type>(Args1::pos)...);
210 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700211};
212
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500213template <typename Func, typename... ArgsWrapped>
214struct Wrapped
Ed Tanous1abe55e2018-09-05 08:30:59 -0700215{
216 template <typename... Args>
217 void set(
218 Func f,
219 typename std::enable_if<
220 !std::is_same<
221 typename std::tuple_element<0, std::tuple<Args..., void>>::type,
222 const Request&>::value,
Ed Tanous104f09c2022-01-25 09:56:04 -0800223 int>::type /*enable*/
224 = 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700225 {
Ed Tanousf94c4ec2022-01-06 12:44:41 -0800226 handler = [f = std::forward<Func>(f)](
zhanghch058d1b46d2021-04-01 11:18:24 +0800227 const Request&,
228 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
229 Args... args) { asyncResp->res.result(f(args...)); };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700230 }
231
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500232 template <typename Req, typename... Args>
233 struct ReqHandlerWrapper
Ed Tanous1abe55e2018-09-05 08:30:59 -0700234 {
Ed Tanous4e23a442022-06-06 09:57:26 -0700235 explicit ReqHandlerWrapper(Func fIn) : f(std::move(fIn))
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500236 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700237
zhanghch058d1b46d2021-04-01 11:18:24 +0800238 void operator()(const Request& req,
239 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
240 Args... args)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700241 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800242 asyncResp->res.result(f(req, args...));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700243 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700244
Ed Tanous1abe55e2018-09-05 08:30:59 -0700245 Func f;
246 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700247
Ed Tanous1abe55e2018-09-05 08:30:59 -0700248 template <typename... Args>
249 void set(
250 Func f,
251 typename std::enable_if<
252 std::is_same<
253 typename std::tuple_element<0, std::tuple<Args..., void>>::type,
254 const Request&>::value &&
255 !std::is_same<typename std::tuple_element<
256 1, std::tuple<Args..., void, void>>::type,
zhanghch058d1b46d2021-04-01 11:18:24 +0800257 const std::shared_ptr<bmcweb::AsyncResp>&>::value,
Ed Tanous104f09c2022-01-25 09:56:04 -0800258 int>::type /*enable*/
259 = 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700260 {
261 handler = ReqHandlerWrapper<Args...>(std::move(f));
262 /*handler = (
263 [f = std::move(f)]
264 (const Request& req, Response& res, Args... args){
Ed Tanousde5c9f32019-03-26 09:17:55 -0700265 res.result(f(req, args...));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700266 res.end();
267 });*/
268 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700269
Ed Tanous1abe55e2018-09-05 08:30:59 -0700270 template <typename... Args>
271 void set(
272 Func f,
273 typename std::enable_if<
274 std::is_same<
275 typename std::tuple_element<0, std::tuple<Args..., void>>::type,
276 const Request&>::value &&
277 std::is_same<typename std::tuple_element<
278 1, std::tuple<Args..., void, void>>::type,
zhanghch058d1b46d2021-04-01 11:18:24 +0800279 const std::shared_ptr<bmcweb::AsyncResp>&>::value,
Ed Tanous104f09c2022-01-25 09:56:04 -0800280 int>::type /*enable*/
281 = 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700282 {
283 handler = std::move(f);
284 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700285
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500286 template <typename... Args>
287 struct HandlerTypeHelper
Ed Tanous1abe55e2018-09-05 08:30:59 -0700288 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800289 using type = std::function<void(
Ed Tanous104f09c2022-01-25 09:56:04 -0800290 const crow::Request& /*req*/,
291 const std::shared_ptr<bmcweb::AsyncResp>&, Args...)>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700292 using args_type =
Ed Tanous988403c2020-08-24 11:29:49 -0700293 black_magic::S<typename black_magic::PromoteT<Args>...>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700294 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700295
Ed Tanous1abe55e2018-09-05 08:30:59 -0700296 template <typename... Args>
297 struct HandlerTypeHelper<const Request&, Args...>
298 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800299 using type = std::function<void(
Ed Tanous104f09c2022-01-25 09:56:04 -0800300 const crow::Request& /*req*/,
301 const std::shared_ptr<bmcweb::AsyncResp>&, Args...)>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700302 using args_type =
Ed Tanous988403c2020-08-24 11:29:49 -0700303 black_magic::S<typename black_magic::PromoteT<Args>...>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700304 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700305
Ed Tanous1abe55e2018-09-05 08:30:59 -0700306 template <typename... Args>
zhanghch058d1b46d2021-04-01 11:18:24 +0800307 struct HandlerTypeHelper<const Request&,
308 const std::shared_ptr<bmcweb::AsyncResp>&, Args...>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700309 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800310 using type = std::function<void(
Ed Tanous104f09c2022-01-25 09:56:04 -0800311 const crow::Request& /*req*/,
312 const std::shared_ptr<bmcweb::AsyncResp>&, Args...)>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700313 using args_type =
Ed Tanous988403c2020-08-24 11:29:49 -0700314 black_magic::S<typename black_magic::PromoteT<Args>...>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700315 };
316
317 typename HandlerTypeHelper<ArgsWrapped...>::type handler;
318
zhanghch058d1b46d2021-04-01 11:18:24 +0800319 void operator()(const Request& req,
320 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700321 const RoutingParams& params)
322 {
323 detail::routing_handler_call_helper::Call<
324 detail::routing_handler_call_helper::CallParams<decltype(handler)>,
325 0, 0, 0, 0, typename HandlerTypeHelper<ArgsWrapped...>::args_type,
326 black_magic::S<>>()(
327 detail::routing_handler_call_helper::CallParams<decltype(handler)>{
zhanghch058d1b46d2021-04-01 11:18:24 +0800328 handler, params, req, asyncResp});
Ed Tanous1abe55e2018-09-05 08:30:59 -0700329 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700330};
Ed Tanous1abe55e2018-09-05 08:30:59 -0700331} // namespace routing_handler_call_helper
332} // namespace detail
Ed Tanous7045c8d2017-04-03 10:04:37 -0700333
Ed Tanous1abe55e2018-09-05 08:30:59 -0700334class WebSocketRule : public BaseRule
335{
336 using self_t = WebSocketRule;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700337
Ed Tanous1abe55e2018-09-05 08:30:59 -0700338 public:
Ed Tanous4e23a442022-06-06 09:57:26 -0700339 explicit WebSocketRule(const std::string& ruleIn) : BaseRule(ruleIn)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500340 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700341
Ed Tanous1abe55e2018-09-05 08:30:59 -0700342 void validate() override
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500343 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700344
Ed Tanous104f09c2022-01-25 09:56:04 -0800345 void handle(const Request& /*req*/,
zhanghch058d1b46d2021-04-01 11:18:24 +0800346 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
Ed Tanous104f09c2022-01-25 09:56:04 -0800347 const RoutingParams& /*params*/) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700348 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800349 asyncResp->res.result(boost::beast::http::status::not_found);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700350 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700351
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +0530352#ifndef BMCWEB_ENABLE_SSL
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530353 void handleUpgrade(const Request& req,
354 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/,
Ed Tanousceac6f72018-12-02 11:58:47 -0800355 boost::asio::ip::tcp::socket&& adaptor) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700356 {
Nan Zhou93c02022022-02-24 18:21:07 -0800357 BMCWEB_LOG_DEBUG << "Websocket handles upgrade";
Ratan Gupta02453b12019-10-22 14:43:36 +0530358 std::shared_ptr<
359 crow::websocket::ConnectionImpl<boost::asio::ip::tcp::socket>>
360 myConnection = std::make_shared<
361 crow::websocket::ConnectionImpl<boost::asio::ip::tcp::socket>>(
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000362 req, std::move(adaptor), openHandler, messageHandler,
Ed Tanous863c1c22022-02-21 21:33:06 -0800363 messageExHandler, closeHandler, errorHandler);
Ratan Gupta02453b12019-10-22 14:43:36 +0530364 myConnection->start();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700365 }
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +0530366#else
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +0530367 void handleUpgrade(const Request& req,
368 const std::shared_ptr<bmcweb::AsyncResp>& /*asyncResp*/,
Ed Tanousceac6f72018-12-02 11:58:47 -0800369 boost::beast::ssl_stream<boost::asio::ip::tcp::socket>&&
370 adaptor) override
Ed Tanous1abe55e2018-09-05 08:30:59 -0700371 {
Nan Zhou93c02022022-02-24 18:21:07 -0800372 BMCWEB_LOG_DEBUG << "Websocket handles upgrade";
Ed Tanousceac6f72018-12-02 11:58:47 -0800373 std::shared_ptr<crow::websocket::ConnectionImpl<
374 boost::beast::ssl_stream<boost::asio::ip::tcp::socket>>>
375 myConnection = std::make_shared<crow::websocket::ConnectionImpl<
376 boost::beast::ssl_stream<boost::asio::ip::tcp::socket>>>(
Jan Sowinskiee52ae12020-01-09 16:28:32 +0000377 req, std::move(adaptor), openHandler, messageHandler,
Ed Tanous863c1c22022-02-21 21:33:06 -0800378 messageExHandler, closeHandler, errorHandler);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700379 myConnection->start();
380 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700381#endif
382
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500383 template <typename Func>
384 self_t& onopen(Func f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700385 {
386 openHandler = f;
387 return *this;
388 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700389
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500390 template <typename Func>
391 self_t& onmessage(Func f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700392 {
393 messageHandler = f;
394 return *this;
395 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700396
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500397 template <typename Func>
Ed Tanous863c1c22022-02-21 21:33:06 -0800398 self_t& onmessageex(Func f)
399 {
400 messageExHandler = f;
401 return *this;
402 }
403
404 template <typename Func>
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500405 self_t& onclose(Func f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700406 {
407 closeHandler = f;
408 return *this;
409 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700410
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500411 template <typename Func>
412 self_t& onerror(Func f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700413 {
414 errorHandler = f;
415 return *this;
416 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700417
Ed Tanous1abe55e2018-09-05 08:30:59 -0700418 protected:
zhanghch0577726382021-10-21 14:07:57 +0800419 std::function<void(crow::websocket::Connection&)> openHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700420 std::function<void(crow::websocket::Connection&, const std::string&, bool)>
421 messageHandler;
Ed Tanous863c1c22022-02-21 21:33:06 -0800422 std::function<void(crow::websocket::Connection&, std::string_view,
423 crow::websocket::MessageType type,
424 std::function<void()>&& whenComplete)>
425 messageExHandler;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700426 std::function<void(crow::websocket::Connection&, const std::string&)>
427 closeHandler;
428 std::function<void(crow::websocket::Connection&)> errorHandler;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700429};
430
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500431template <typename T>
432struct RuleParameterTraits
Ed Tanous1abe55e2018-09-05 08:30:59 -0700433{
434 using self_t = T;
435 WebSocketRule& websocket()
436 {
Ed Tanous271584a2019-07-09 16:24:22 -0700437 self_t* self = static_cast<self_t*>(this);
438 WebSocketRule* p = new WebSocketRule(self->rule);
439 self->ruleToUpgrade.reset(p);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700440 return *p;
441 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700442
Ed Tanous26ccae32023-02-16 10:28:44 -0800443 self_t& name(std::string_view name) noexcept
Ed Tanous1abe55e2018-09-05 08:30:59 -0700444 {
Ed Tanous271584a2019-07-09 16:24:22 -0700445 self_t* self = static_cast<self_t*>(this);
Ed Tanousf23b7292020-10-15 09:41:17 -0700446 self->nameStr = name;
Ed Tanous271584a2019-07-09 16:24:22 -0700447 return *self;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700448 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700449
Ed Tanous1abe55e2018-09-05 08:30:59 -0700450 self_t& methods(boost::beast::http::verb method)
451 {
Ed Tanous271584a2019-07-09 16:24:22 -0700452 self_t* self = static_cast<self_t*>(this);
Ed Tanous2c9efc32022-07-31 22:08:26 -0700453 std::optional<HttpVerb> verb = httpVerbFromBoost(method);
454 if (verb)
455 {
456 self->methodsBitfield = 1U << static_cast<size_t>(*verb);
457 }
Ed Tanous271584a2019-07-09 16:24:22 -0700458 return *self;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700459 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700460
Ed Tanous1abe55e2018-09-05 08:30:59 -0700461 template <typename... MethodArgs>
Ed Tanous81ce6092020-12-17 16:54:55 +0000462 self_t& methods(boost::beast::http::verb method, MethodArgs... argsMethod)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700463 {
Ed Tanous271584a2019-07-09 16:24:22 -0700464 self_t* self = static_cast<self_t*>(this);
Ed Tanous81ce6092020-12-17 16:54:55 +0000465 methods(argsMethod...);
Ed Tanous2c9efc32022-07-31 22:08:26 -0700466 std::optional<HttpVerb> verb = httpVerbFromBoost(method);
467 if (verb)
468 {
469 self->methodsBitfield |= 1U << static_cast<size_t>(*verb);
470 }
Ed Tanous271584a2019-07-09 16:24:22 -0700471 return *self;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700472 }
Tanousf00032d2018-11-05 01:18:10 -0300473
Ed Tanous44e45182022-07-26 16:47:23 -0700474 self_t& notFound()
475 {
476 self_t* self = static_cast<self_t*>(this);
477 self->methodsBitfield = 1U << notFoundIndex;
478 return *self;
479 }
480
Ed Tanous759cf102022-07-31 16:36:52 -0700481 self_t& methodNotAllowed()
482 {
483 self_t* self = static_cast<self_t*>(this);
484 self->methodsBitfield = 1U << methodNotAllowedIndex;
485 return *self;
486 }
487
Ed Tanous432a8902021-06-14 15:28:56 -0700488 self_t& privileges(
489 const std::initializer_list<std::initializer_list<const char*>>& p)
Tanousf00032d2018-11-05 01:18:10 -0300490 {
Ed Tanous271584a2019-07-09 16:24:22 -0700491 self_t* self = static_cast<self_t*>(this);
Ed Tanous432a8902021-06-14 15:28:56 -0700492 for (const std::initializer_list<const char*>& privilege : p)
Tanousf00032d2018-11-05 01:18:10 -0300493 {
Ed Tanous271584a2019-07-09 16:24:22 -0700494 self->privilegesSet.emplace_back(privilege);
Tanousf00032d2018-11-05 01:18:10 -0300495 }
Ed Tanous271584a2019-07-09 16:24:22 -0700496 return *self;
Tanousf00032d2018-11-05 01:18:10 -0300497 }
Ed Tanoused398212021-06-09 17:05:54 -0700498
499 template <size_t N, typename... MethodArgs>
500 self_t& privileges(const std::array<redfish::Privileges, N>& p)
501 {
502 self_t* self = static_cast<self_t*>(this);
503 for (const redfish::Privileges& privilege : p)
504 {
505 self->privilegesSet.emplace_back(privilege);
506 }
507 return *self;
508 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700509};
510
Ed Tanous1abe55e2018-09-05 08:30:59 -0700511class DynamicRule : public BaseRule, public RuleParameterTraits<DynamicRule>
512{
513 public:
Ed Tanous4e23a442022-06-06 09:57:26 -0700514 explicit DynamicRule(const std::string& ruleIn) : BaseRule(ruleIn)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500515 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700516
Ed Tanous1abe55e2018-09-05 08:30:59 -0700517 void validate() override
518 {
519 if (!erasedHandler)
520 {
521 throw std::runtime_error(nameStr + (!nameStr.empty() ? ": " : "") +
522 "no handler for url " + rule);
523 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700524 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700525
zhanghch058d1b46d2021-04-01 11:18:24 +0800526 void handle(const Request& req,
527 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700528 const RoutingParams& params) override
529 {
zhanghch058d1b46d2021-04-01 11:18:24 +0800530 erasedHandler(req, asyncResp, params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700531 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700532
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500533 template <typename Func>
534 void operator()(Func f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700535 {
Ed Tanousc867a832022-03-10 14:17:00 -0800536 using boost::callable_traits::args_t;
537 constexpr size_t arity = std::tuple_size<args_t<Func>>::value;
538 constexpr auto is = std::make_integer_sequence<unsigned, arity>{};
539 erasedHandler = wrap(std::move(f), is);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700540 }
541
542 // enable_if Arg1 == request && Arg2 == Response
Gunnar Mills6be0e402020-07-08 13:21:51 -0500543 // enable_if Arg1 == request && Arg2 != response
Ed Tanous1abe55e2018-09-05 08:30:59 -0700544 // enable_if Arg1 != request
545
546 template <typename Func, unsigned... Indices>
zhanghch058d1b46d2021-04-01 11:18:24 +0800547 std::function<void(const Request&,
548 const std::shared_ptr<bmcweb::AsyncResp>&,
549 const RoutingParams&)>
Ed Tanous104f09c2022-01-25 09:56:04 -0800550 wrap(Func f, std::integer_sequence<unsigned, Indices...> /*is*/)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700551 {
Ed Tanousc867a832022-03-10 14:17:00 -0800552 using function_t = crow::utility::FunctionTraits<Func>;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700553
554 if (!black_magic::isParameterTagCompatible(
Ed Tanous988403c2020-08-24 11:29:49 -0700555 black_magic::getParameterTag(rule.c_str()),
556 black_magic::computeParameterTagFromArgsList<
Ed Tanous1abe55e2018-09-05 08:30:59 -0700557 typename function_t::template arg<Indices>...>::value))
558 {
559 throw std::runtime_error("routeDynamic: Handler type is mismatched "
560 "with URL parameters: " +
561 rule);
562 }
563 auto ret = detail::routing_handler_call_helper::Wrapped<
564 Func, typename function_t::template arg<Indices>...>();
565 ret.template set<typename function_t::template arg<Indices>...>(
566 std::move(f));
567 return ret;
568 }
569
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500570 template <typename Func>
571 void operator()(std::string name, Func&& f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700572 {
573 nameStr = std::move(name);
574 (*this).template operator()<Func>(std::forward(f));
575 }
576
577 private:
zhanghch058d1b46d2021-04-01 11:18:24 +0800578 std::function<void(const Request&,
579 const std::shared_ptr<bmcweb::AsyncResp>&,
580 const RoutingParams&)>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700581 erasedHandler;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700582};
583
584template <typename... Args>
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500585class TaggedRule :
586 public BaseRule,
587 public RuleParameterTraits<TaggedRule<Args...>>
Ed Tanous1abe55e2018-09-05 08:30:59 -0700588{
589 public:
590 using self_t = TaggedRule<Args...>;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700591
Ed Tanous4e23a442022-06-06 09:57:26 -0700592 explicit TaggedRule(const std::string& ruleIn) : BaseRule(ruleIn)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500593 {}
Ed Tanous7045c8d2017-04-03 10:04:37 -0700594
Ed Tanous1abe55e2018-09-05 08:30:59 -0700595 void validate() override
596 {
597 if (!handler)
598 {
599 throw std::runtime_error(nameStr + (!nameStr.empty() ? ": " : "") +
600 "no handler for url " + rule);
601 }
602 }
603
604 template <typename Func>
605 typename std::enable_if<
606 black_magic::CallHelper<Func, black_magic::S<Args...>>::value,
607 void>::type
608 operator()(Func&& f)
609 {
610 static_assert(
611 black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
612 black_magic::CallHelper<
613 Func, black_magic::S<crow::Request, Args...>>::value,
614 "Handler type is mismatched with URL parameters");
615 static_assert(
616 !std::is_same<void, decltype(f(std::declval<Args>()...))>::value,
617 "Handler function cannot have void return type; valid return "
618 "types: "
Gunnar Mills6be0e402020-07-08 13:21:51 -0500619 "string, int, crow::response, nlohmann::json");
Ed Tanous1abe55e2018-09-05 08:30:59 -0700620
Ed Tanousf94c4ec2022-01-06 12:44:41 -0800621 handler = [f = std::forward<Func>(f)](
zhanghch058d1b46d2021-04-01 11:18:24 +0800622 const Request&,
623 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
624 Args... args) { asyncResp->res.result(f(args...)); };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700625 }
626
627 template <typename Func>
628 typename std::enable_if<
629 !black_magic::CallHelper<Func, black_magic::S<Args...>>::value &&
Ed Tanous7045c8d2017-04-03 10:04:37 -0700630 black_magic::CallHelper<
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700631 Func, black_magic::S<crow::Request, Args...>>::value,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700632 void>::type
633 operator()(Func&& f)
634 {
635 static_assert(
636 black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
637 black_magic::CallHelper<
638 Func, black_magic::S<crow::Request, Args...>>::value,
639 "Handler type is mismatched with URL parameters");
640 static_assert(
641 !std::is_same<void, decltype(f(std::declval<crow::Request>(),
642 std::declval<Args>()...))>::value,
643 "Handler function cannot have void return type; valid return "
644 "types: "
Gunnar Mills6be0e402020-07-08 13:21:51 -0500645 "string, int, crow::response,nlohmann::json");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700646
Ed Tanousf94c4ec2022-01-06 12:44:41 -0800647 handler = [f = std::forward<Func>(f)](
zhanghch058d1b46d2021-04-01 11:18:24 +0800648 const crow::Request& req,
649 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
650 Args... args) { asyncResp->res.result(f(req, args...)); };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700651 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700652
Ed Tanous1abe55e2018-09-05 08:30:59 -0700653 template <typename Func>
654 typename std::enable_if<
655 !black_magic::CallHelper<Func, black_magic::S<Args...>>::value &&
656 !black_magic::CallHelper<
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700657 Func, black_magic::S<crow::Request, Args...>>::value,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700658 void>::type
659 operator()(Func&& f)
660 {
661 static_assert(
662 black_magic::CallHelper<Func, black_magic::S<Args...>>::value ||
663 black_magic::CallHelper<
664 Func, black_magic::S<crow::Request, Args...>>::value ||
665 black_magic::CallHelper<
zhanghch058d1b46d2021-04-01 11:18:24 +0800666 Func, black_magic::S<crow::Request,
667 std::shared_ptr<bmcweb::AsyncResp>&,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700668 Args...>>::value,
669 "Handler type is mismatched with URL parameters");
670 static_assert(
zhanghch058d1b46d2021-04-01 11:18:24 +0800671 std::is_same<
672 void,
673 decltype(f(std::declval<crow::Request>(),
674 std::declval<std::shared_ptr<bmcweb::AsyncResp>&>(),
675 std::declval<Args>()...))>::value,
Tanousf00032d2018-11-05 01:18:10 -0300676 "Handler function with response argument should have void "
677 "return "
Ed Tanous1abe55e2018-09-05 08:30:59 -0700678 "type");
Ed Tanous7045c8d2017-04-03 10:04:37 -0700679
Ed Tanousf94c4ec2022-01-06 12:44:41 -0800680 handler = std::forward<Func>(f);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700681 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700682
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500683 template <typename Func>
Ed Tanous26ccae32023-02-16 10:28:44 -0800684 void operator()(std::string_view name, Func&& f)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700685 {
Ed Tanousf23b7292020-10-15 09:41:17 -0700686 nameStr = name;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700687 (*this).template operator()<Func>(std::forward(f));
688 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700689
zhanghch058d1b46d2021-04-01 11:18:24 +0800690 void handle(const Request& req,
691 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
Ed Tanous1abe55e2018-09-05 08:30:59 -0700692 const RoutingParams& params) override
693 {
694 detail::routing_handler_call_helper::Call<
695 detail::routing_handler_call_helper::CallParams<decltype(handler)>,
696 0, 0, 0, 0, black_magic::S<Args...>, black_magic::S<>>()(
697 detail::routing_handler_call_helper::CallParams<decltype(handler)>{
zhanghch058d1b46d2021-04-01 11:18:24 +0800698 handler, params, req, asyncResp});
Ed Tanous1abe55e2018-09-05 08:30:59 -0700699 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700700
Ed Tanous1abe55e2018-09-05 08:30:59 -0700701 private:
zhanghch058d1b46d2021-04-01 11:18:24 +0800702 std::function<void(const crow::Request&,
703 const std::shared_ptr<bmcweb::AsyncResp>&, Args...)>
704 handler;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700705};
706
Ed Tanous1abe55e2018-09-05 08:30:59 -0700707class Trie
708{
709 public:
710 struct Node
711 {
712 unsigned ruleIndex{};
Ed Tanous271584a2019-07-09 16:24:22 -0700713 std::array<size_t, static_cast<size_t>(ParamType::MAX)>
714 paramChildrens{};
Ed Tanousa94ac612022-02-22 11:13:24 -0800715 using ChildMap = boost::container::flat_map<
716 std::string, unsigned, std::less<>,
717 std::vector<std::pair<std::string, unsigned>>>;
718 ChildMap children;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700719
Ed Tanous1abe55e2018-09-05 08:30:59 -0700720 bool isSimpleNode() const
721 {
Ed Tanouse662eae2022-01-25 10:39:19 -0800722 return ruleIndex == 0 &&
723 std::all_of(std::begin(paramChildrens),
724 std::end(paramChildrens),
725 [](size_t x) { return x == 0U; });
Ed Tanous7045c8d2017-04-03 10:04:37 -0700726 }
Ed Tanous55c7b7a2018-05-22 15:27:24 -0700727 };
Ed Tanous7045c8d2017-04-03 10:04:37 -0700728
Ed Tanous1abe55e2018-09-05 08:30:59 -0700729 Trie() : nodes(1)
Gunnar Mills1214b7e2020-06-04 10:11:30 -0500730 {}
Ed Tanous1abe55e2018-09-05 08:30:59 -0700731
732 private:
733 void optimizeNode(Node* node)
734 {
Ed Tanous271584a2019-07-09 16:24:22 -0700735 for (size_t x : node->paramChildrens)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700736 {
Ed Tanousdbb59d42022-01-25 11:09:55 -0800737 if (x == 0U)
Ed Tanous3174e4d2020-10-07 11:41:22 -0700738 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700739 continue;
Ed Tanous3174e4d2020-10-07 11:41:22 -0700740 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700741 Node* child = &nodes[x];
742 optimizeNode(child);
Ed Tanous7045c8d2017-04-03 10:04:37 -0700743 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700744 if (node->children.empty())
Ed Tanous3174e4d2020-10-07 11:41:22 -0700745 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700746 return;
Ed Tanous3174e4d2020-10-07 11:41:22 -0700747 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700748 bool mergeWithChild = true;
Ed Tanousa94ac612022-02-22 11:13:24 -0800749 for (const Node::ChildMap::value_type& kv : node->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700750 {
751 Node* child = &nodes[kv.second];
752 if (!child->isSimpleNode())
753 {
754 mergeWithChild = false;
755 break;
Ed Tanous7045c8d2017-04-03 10:04:37 -0700756 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700757 }
758 if (mergeWithChild)
759 {
Ed Tanousa94ac612022-02-22 11:13:24 -0800760 Node::ChildMap merged;
761 for (const Node::ChildMap::value_type& kv : node->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700762 {
763 Node* child = &nodes[kv.second];
Ed Tanousa94ac612022-02-22 11:13:24 -0800764 for (const Node::ChildMap::value_type& childKv :
Tanousf00032d2018-11-05 01:18:10 -0300765 child->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700766 {
767 merged[kv.first + childKv.first] = childKv.second;
768 }
769 }
770 node->children = std::move(merged);
771 optimizeNode(node);
772 }
773 else
774 {
Ed Tanousa94ac612022-02-22 11:13:24 -0800775 for (const Node::ChildMap::value_type& kv : node->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700776 {
777 Node* child = &nodes[kv.second];
778 optimizeNode(child);
779 }
780 }
781 }
782
783 void optimize()
784 {
785 optimizeNode(head());
786 }
787
788 public:
789 void validate()
790 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700791 optimize();
792 }
793
Ed Tanous81ce6092020-12-17 16:54:55 +0000794 void findRouteIndexes(const std::string& reqUrl,
795 std::vector<unsigned>& routeIndexes,
Tanousf00032d2018-11-05 01:18:10 -0300796 const Node* node = nullptr, unsigned pos = 0) const
Ed Tanous1abe55e2018-09-05 08:30:59 -0700797 {
798 if (node == nullptr)
799 {
800 node = head();
801 }
Ed Tanousa94ac612022-02-22 11:13:24 -0800802 for (const Node::ChildMap::value_type& kv : node->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700803 {
804 const std::string& fragment = kv.first;
805 const Node* child = &nodes[kv.second];
Ed Tanous81ce6092020-12-17 16:54:55 +0000806 if (pos >= reqUrl.size())
Ed Tanous1abe55e2018-09-05 08:30:59 -0700807 {
808 if (child->ruleIndex != 0 && fragment != "/")
809 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000810 routeIndexes.push_back(child->ruleIndex);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700811 }
Ed Tanous81ce6092020-12-17 16:54:55 +0000812 findRouteIndexes(reqUrl, routeIndexes, child,
Ed Tanous271584a2019-07-09 16:24:22 -0700813 static_cast<unsigned>(pos + fragment.size()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700814 }
815 else
816 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000817 if (reqUrl.compare(pos, fragment.size(), fragment) == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700818 {
Ed Tanous271584a2019-07-09 16:24:22 -0700819 findRouteIndexes(
Ed Tanous81ce6092020-12-17 16:54:55 +0000820 reqUrl, routeIndexes, child,
Ed Tanous271584a2019-07-09 16:24:22 -0700821 static_cast<unsigned>(pos + fragment.size()));
Ed Tanous1abe55e2018-09-05 08:30:59 -0700822 }
823 }
824 }
825 }
826
827 std::pair<unsigned, RoutingParams>
Ed Tanous26ccae32023-02-16 10:28:44 -0800828 find(std::string_view reqUrl, const Node* node = nullptr,
Ed Tanous271584a2019-07-09 16:24:22 -0700829 size_t pos = 0, RoutingParams* params = nullptr) const
Ed Tanous1abe55e2018-09-05 08:30:59 -0700830 {
831 RoutingParams empty;
832 if (params == nullptr)
Ed Tanous3174e4d2020-10-07 11:41:22 -0700833 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700834 params = &empty;
Ed Tanous3174e4d2020-10-07 11:41:22 -0700835 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700836
837 unsigned found{};
838 RoutingParams matchParams;
839
840 if (node == nullptr)
Ed Tanous3174e4d2020-10-07 11:41:22 -0700841 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700842 node = head();
Ed Tanous3174e4d2020-10-07 11:41:22 -0700843 }
Ed Tanous81ce6092020-12-17 16:54:55 +0000844 if (pos == reqUrl.size())
Ed Tanous3174e4d2020-10-07 11:41:22 -0700845 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700846 return {node->ruleIndex, *params};
Ed Tanous3174e4d2020-10-07 11:41:22 -0700847 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700848
849 auto updateFound =
850 [&found, &matchParams](std::pair<unsigned, RoutingParams>& ret) {
Ed Tanous002d39b2022-05-31 08:59:27 -0700851 if (ret.first != 0U && (found == 0U || found > ret.first))
852 {
853 found = ret.first;
854 matchParams = std::move(ret.second);
855 }
856 };
Ed Tanous1abe55e2018-09-05 08:30:59 -0700857
Ed Tanouse662eae2022-01-25 10:39:19 -0800858 if (node->paramChildrens[static_cast<size_t>(ParamType::INT)] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700859 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000860 char c = reqUrl[pos];
Ed Tanous1abe55e2018-09-05 08:30:59 -0700861 if ((c >= '0' && c <= '9') || c == '+' || c == '-')
862 {
Ed Tanous543f4402022-01-06 13:12:53 -0800863 char* eptr = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700864 errno = 0;
865 long long int value =
Ed Tanous81ce6092020-12-17 16:54:55 +0000866 std::strtoll(reqUrl.data() + pos, &eptr, 10);
867 if (errno != ERANGE && eptr != reqUrl.data() + pos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700868 {
869 params->intParams.push_back(value);
Ed Tanous81ce6092020-12-17 16:54:55 +0000870 std::pair<unsigned, RoutingParams> ret =
871 find(reqUrl,
872 &nodes[node->paramChildrens[static_cast<size_t>(
873 ParamType::INT)]],
874 static_cast<size_t>(eptr - reqUrl.data()), params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700875 updateFound(ret);
876 params->intParams.pop_back();
877 }
878 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700879 }
880
Ed Tanouse662eae2022-01-25 10:39:19 -0800881 if (node->paramChildrens[static_cast<size_t>(ParamType::UINT)] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700882 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000883 char c = reqUrl[pos];
Ed Tanous1abe55e2018-09-05 08:30:59 -0700884 if ((c >= '0' && c <= '9') || c == '+')
885 {
Ed Tanous543f4402022-01-06 13:12:53 -0800886 char* eptr = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700887 errno = 0;
888 unsigned long long int value =
Ed Tanous81ce6092020-12-17 16:54:55 +0000889 std::strtoull(reqUrl.data() + pos, &eptr, 10);
890 if (errno != ERANGE && eptr != reqUrl.data() + pos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700891 {
892 params->uintParams.push_back(value);
Ed Tanous81ce6092020-12-17 16:54:55 +0000893 std::pair<unsigned, RoutingParams> ret =
894 find(reqUrl,
895 &nodes[node->paramChildrens[static_cast<size_t>(
896 ParamType::UINT)]],
897 static_cast<size_t>(eptr - reqUrl.data()), params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700898 updateFound(ret);
899 params->uintParams.pop_back();
900 }
901 }
Ed Tanous7045c8d2017-04-03 10:04:37 -0700902 }
903
Ed Tanouse662eae2022-01-25 10:39:19 -0800904 if (node->paramChildrens[static_cast<size_t>(ParamType::DOUBLE)] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700905 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000906 char c = reqUrl[pos];
Ed Tanous1abe55e2018-09-05 08:30:59 -0700907 if ((c >= '0' && c <= '9') || c == '+' || c == '-' || c == '.')
908 {
Ed Tanous543f4402022-01-06 13:12:53 -0800909 char* eptr = nullptr;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700910 errno = 0;
Ed Tanous81ce6092020-12-17 16:54:55 +0000911 double value = std::strtod(reqUrl.data() + pos, &eptr);
912 if (errno != ERANGE && eptr != reqUrl.data() + pos)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700913 {
914 params->doubleParams.push_back(value);
Ed Tanous81ce6092020-12-17 16:54:55 +0000915 std::pair<unsigned, RoutingParams> ret =
916 find(reqUrl,
917 &nodes[node->paramChildrens[static_cast<size_t>(
918 ParamType::DOUBLE)]],
919 static_cast<size_t>(eptr - reqUrl.data()), params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700920 updateFound(ret);
921 params->doubleParams.pop_back();
922 }
923 }
924 }
925
Ed Tanouse662eae2022-01-25 10:39:19 -0800926 if (node->paramChildrens[static_cast<size_t>(ParamType::STRING)] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700927 {
Ed Tanousb01bf292019-03-25 19:25:26 +0000928 size_t epos = pos;
Ed Tanous81ce6092020-12-17 16:54:55 +0000929 for (; epos < reqUrl.size(); epos++)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700930 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000931 if (reqUrl[epos] == '/')
Ed Tanous3174e4d2020-10-07 11:41:22 -0700932 {
Ed Tanous1abe55e2018-09-05 08:30:59 -0700933 break;
Ed Tanous3174e4d2020-10-07 11:41:22 -0700934 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700935 }
936
937 if (epos != pos)
938 {
939 params->stringParams.emplace_back(
Ed Tanous81ce6092020-12-17 16:54:55 +0000940 reqUrl.substr(pos, epos - pos));
Tanousf00032d2018-11-05 01:18:10 -0300941 std::pair<unsigned, RoutingParams> ret =
Ed Tanous81ce6092020-12-17 16:54:55 +0000942 find(reqUrl,
Ed Tanous271584a2019-07-09 16:24:22 -0700943 &nodes[node->paramChildrens[static_cast<size_t>(
944 ParamType::STRING)]],
Ed Tanousb01bf292019-03-25 19:25:26 +0000945 epos, params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700946 updateFound(ret);
947 params->stringParams.pop_back();
948 }
949 }
950
Ed Tanouse662eae2022-01-25 10:39:19 -0800951 if (node->paramChildrens[static_cast<size_t>(ParamType::PATH)] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700952 {
Ed Tanous81ce6092020-12-17 16:54:55 +0000953 size_t epos = reqUrl.size();
Ed Tanous1abe55e2018-09-05 08:30:59 -0700954
955 if (epos != pos)
956 {
957 params->stringParams.emplace_back(
Ed Tanous81ce6092020-12-17 16:54:55 +0000958 reqUrl.substr(pos, epos - pos));
Ed Tanous271584a2019-07-09 16:24:22 -0700959 std::pair<unsigned, RoutingParams> ret =
Ed Tanous81ce6092020-12-17 16:54:55 +0000960 find(reqUrl,
Ed Tanous271584a2019-07-09 16:24:22 -0700961 &nodes[node->paramChildrens[static_cast<size_t>(
962 ParamType::PATH)]],
963 epos, params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700964 updateFound(ret);
965 params->stringParams.pop_back();
966 }
967 }
968
Ed Tanousa94ac612022-02-22 11:13:24 -0800969 for (const Node::ChildMap::value_type& kv : node->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700970 {
971 const std::string& fragment = kv.first;
972 const Node* child = &nodes[kv.second];
973
Ed Tanous81ce6092020-12-17 16:54:55 +0000974 if (reqUrl.compare(pos, fragment.size(), fragment) == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -0700975 {
Tanousf00032d2018-11-05 01:18:10 -0300976 std::pair<unsigned, RoutingParams> ret =
Ed Tanous81ce6092020-12-17 16:54:55 +0000977 find(reqUrl, child, pos + fragment.size(), params);
Ed Tanous1abe55e2018-09-05 08:30:59 -0700978 updateFound(ret);
979 }
980 }
981
982 return {found, matchParams};
Ed Tanous7045c8d2017-04-03 10:04:37 -0700983 }
Ed Tanous1abe55e2018-09-05 08:30:59 -0700984
985 void add(const std::string& url, unsigned ruleIndex)
986 {
Ed Tanous271584a2019-07-09 16:24:22 -0700987 size_t idx = 0;
Ed Tanous1abe55e2018-09-05 08:30:59 -0700988
989 for (unsigned i = 0; i < url.size(); i++)
990 {
991 char c = url[i];
992 if (c == '<')
993 {
Tanousf00032d2018-11-05 01:18:10 -0300994 const static std::array<std::pair<ParamType, std::string>, 7>
995 paramTraits = {{
996 {ParamType::INT, "<int>"},
997 {ParamType::UINT, "<uint>"},
998 {ParamType::DOUBLE, "<float>"},
999 {ParamType::DOUBLE, "<double>"},
1000 {ParamType::STRING, "<str>"},
1001 {ParamType::STRING, "<string>"},
1002 {ParamType::PATH, "<path>"},
1003 }};
Ed Tanous1abe55e2018-09-05 08:30:59 -07001004
Tanousf00032d2018-11-05 01:18:10 -03001005 for (const std::pair<ParamType, std::string>& x : paramTraits)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001006 {
Tanousf00032d2018-11-05 01:18:10 -03001007 if (url.compare(i, x.second.size(), x.second) == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001008 {
Ed Tanous271584a2019-07-09 16:24:22 -07001009 size_t index = static_cast<size_t>(x.first);
Ed Tanouse662eae2022-01-25 10:39:19 -08001010 if (nodes[idx].paramChildrens[index] == 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001011 {
Tanousf00032d2018-11-05 01:18:10 -03001012 unsigned newNodeIdx = newNode();
Ed Tanous271584a2019-07-09 16:24:22 -07001013 nodes[idx].paramChildrens[index] = newNodeIdx;
Ed Tanous1abe55e2018-09-05 08:30:59 -07001014 }
Ed Tanous271584a2019-07-09 16:24:22 -07001015 idx = nodes[idx].paramChildrens[index];
1016 i += static_cast<unsigned>(x.second.size());
Ed Tanous1abe55e2018-09-05 08:30:59 -07001017 break;
1018 }
1019 }
1020
1021 i--;
1022 }
1023 else
1024 {
1025 std::string piece(&c, 1);
Ed Tanouse662eae2022-01-25 10:39:19 -08001026 if (nodes[idx].children.count(piece) == 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001027 {
Tanousf00032d2018-11-05 01:18:10 -03001028 unsigned newNodeIdx = newNode();
Ed Tanous1abe55e2018-09-05 08:30:59 -07001029 nodes[idx].children.emplace(piece, newNodeIdx);
1030 }
1031 idx = nodes[idx].children[piece];
1032 }
1033 }
Ed Tanouse662eae2022-01-25 10:39:19 -08001034 if (nodes[idx].ruleIndex != 0U)
Ed Tanous3174e4d2020-10-07 11:41:22 -07001035 {
Ed Tanous1abe55e2018-09-05 08:30:59 -07001036 throw std::runtime_error("handler already exists for " + url);
Ed Tanous3174e4d2020-10-07 11:41:22 -07001037 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001038 nodes[idx].ruleIndex = ruleIndex;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001039 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001040
Ed Tanous1abe55e2018-09-05 08:30:59 -07001041 private:
Ed Tanous271584a2019-07-09 16:24:22 -07001042 void debugNodePrint(Node* n, size_t level)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001043 {
Ed Tanous271584a2019-07-09 16:24:22 -07001044 for (size_t i = 0; i < static_cast<size_t>(ParamType::MAX); i++)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001045 {
Ed Tanouse662eae2022-01-25 10:39:19 -08001046 if (n->paramChildrens[i] != 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001047 {
1048 BMCWEB_LOG_DEBUG << std::string(
Ed Tanous271584a2019-07-09 16:24:22 -07001049 2U * level, ' ') /*<< "("<<n->paramChildrens[i]<<") "*/;
1050 switch (static_cast<ParamType>(i))
Ed Tanous1abe55e2018-09-05 08:30:59 -07001051 {
1052 case ParamType::INT:
1053 BMCWEB_LOG_DEBUG << "<int>";
1054 break;
1055 case ParamType::UINT:
1056 BMCWEB_LOG_DEBUG << "<uint>";
1057 break;
1058 case ParamType::DOUBLE:
1059 BMCWEB_LOG_DEBUG << "<float>";
1060 break;
1061 case ParamType::STRING:
1062 BMCWEB_LOG_DEBUG << "<str>";
1063 break;
1064 case ParamType::PATH:
1065 BMCWEB_LOG_DEBUG << "<path>";
1066 break;
Ed Tanous23a21a12020-07-25 04:45:05 +00001067 case ParamType::MAX:
Ed Tanous1abe55e2018-09-05 08:30:59 -07001068 BMCWEB_LOG_DEBUG << "<ERROR>";
1069 break;
1070 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001071
Ed Tanous1abe55e2018-09-05 08:30:59 -07001072 debugNodePrint(&nodes[n->paramChildrens[i]], level + 1);
1073 }
1074 }
Ed Tanousa94ac612022-02-22 11:13:24 -08001075 for (const Node::ChildMap::value_type& kv : n->children)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001076 {
1077 BMCWEB_LOG_DEBUG
Ed Tanous271584a2019-07-09 16:24:22 -07001078 << std::string(2U * level, ' ') /*<< "(" << kv.second << ") "*/
Ed Tanous1abe55e2018-09-05 08:30:59 -07001079 << kv.first;
1080 debugNodePrint(&nodes[kv.second], level + 1);
1081 }
1082 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001083
Ed Tanous1abe55e2018-09-05 08:30:59 -07001084 public:
1085 void debugPrint()
1086 {
Ed Tanous271584a2019-07-09 16:24:22 -07001087 debugNodePrint(head(), 0U);
Ed Tanous1abe55e2018-09-05 08:30:59 -07001088 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001089
Ed Tanous1abe55e2018-09-05 08:30:59 -07001090 private:
1091 const Node* head() const
1092 {
1093 return &nodes.front();
1094 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001095
Ed Tanous1abe55e2018-09-05 08:30:59 -07001096 Node* head()
1097 {
1098 return &nodes.front();
1099 }
1100
1101 unsigned newNode()
1102 {
1103 nodes.resize(nodes.size() + 1);
Ed Tanous271584a2019-07-09 16:24:22 -07001104 return static_cast<unsigned>(nodes.size() - 1);
Ed Tanous1abe55e2018-09-05 08:30:59 -07001105 }
1106
1107 std::vector<Node> nodes;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001108};
1109
Ed Tanous1abe55e2018-09-05 08:30:59 -07001110class Router
1111{
1112 public:
Ed Tanous0c0084a2019-10-24 15:57:51 -07001113 Router() = default;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001114
Ed Tanous1abe55e2018-09-05 08:30:59 -07001115 DynamicRule& newRuleDynamic(const std::string& rule)
1116 {
1117 std::unique_ptr<DynamicRule> ruleObject =
1118 std::make_unique<DynamicRule>(rule);
1119 DynamicRule* ptr = ruleObject.get();
Tanousf00032d2018-11-05 01:18:10 -03001120 allRules.emplace_back(std::move(ruleObject));
Ed Tanous7045c8d2017-04-03 10:04:37 -07001121
Ed Tanous1abe55e2018-09-05 08:30:59 -07001122 return *ptr;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001123 }
1124
Ed Tanous1abe55e2018-09-05 08:30:59 -07001125 template <uint64_t N>
1126 typename black_magic::Arguments<N>::type::template rebind<TaggedRule>&
1127 newRuleTagged(const std::string& rule)
1128 {
1129 using RuleT = typename black_magic::Arguments<N>::type::template rebind<
1130 TaggedRule>;
1131 std::unique_ptr<RuleT> ruleObject = std::make_unique<RuleT>(rule);
1132 RuleT* ptr = ruleObject.get();
Tanousf00032d2018-11-05 01:18:10 -03001133 allRules.emplace_back(std::move(ruleObject));
Ed Tanous1abe55e2018-09-05 08:30:59 -07001134
1135 return *ptr;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001136 }
1137
Tanousf00032d2018-11-05 01:18:10 -03001138 void internalAddRuleObject(const std::string& rule, BaseRule* ruleObject)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001139 {
Tanousf00032d2018-11-05 01:18:10 -03001140 if (ruleObject == nullptr)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001141 {
Tanousf00032d2018-11-05 01:18:10 -03001142 return;
1143 }
Ed Tanous759cf102022-07-31 16:36:52 -07001144 for (size_t method = 0, methodBit = 1; method <= methodNotAllowedIndex;
Ed Tanous2c70f802020-09-28 14:29:23 -07001145 method++, methodBit <<= 1)
Tanousf00032d2018-11-05 01:18:10 -03001146 {
Ed Tanouse662eae2022-01-25 10:39:19 -08001147 if ((ruleObject->methodsBitfield & methodBit) > 0U)
Tanousf00032d2018-11-05 01:18:10 -03001148 {
1149 perMethods[method].rules.emplace_back(ruleObject);
1150 perMethods[method].trie.add(
Ed Tanous271584a2019-07-09 16:24:22 -07001151 rule, static_cast<unsigned>(
1152 perMethods[method].rules.size() - 1U));
Tanousf00032d2018-11-05 01:18:10 -03001153 // directory case:
1154 // request to `/about' url matches `/about/' rule
1155 if (rule.size() > 2 && rule.back() == '/')
1156 {
1157 perMethods[method].trie.add(
1158 rule.substr(0, rule.size() - 1),
Ed Tanous271584a2019-07-09 16:24:22 -07001159 static_cast<unsigned>(perMethods[method].rules.size() -
1160 1));
Tanousf00032d2018-11-05 01:18:10 -03001161 }
1162 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001163 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001164 }
1165
Ed Tanous1abe55e2018-09-05 08:30:59 -07001166 void validate()
1167 {
Tanousf00032d2018-11-05 01:18:10 -03001168 for (std::unique_ptr<BaseRule>& rule : allRules)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001169 {
1170 if (rule)
1171 {
Tanousf00032d2018-11-05 01:18:10 -03001172 std::unique_ptr<BaseRule> upgraded = rule->upgrade();
Ed Tanous1abe55e2018-09-05 08:30:59 -07001173 if (upgraded)
Ed Tanous3174e4d2020-10-07 11:41:22 -07001174 {
Ed Tanous1abe55e2018-09-05 08:30:59 -07001175 rule = std::move(upgraded);
Ed Tanous3174e4d2020-10-07 11:41:22 -07001176 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001177 rule->validate();
Tanousf00032d2018-11-05 01:18:10 -03001178 internalAddRuleObject(rule->rule, rule.get());
Ed Tanous1abe55e2018-09-05 08:30:59 -07001179 }
1180 }
Tanousf00032d2018-11-05 01:18:10 -03001181 for (PerMethod& perMethod : perMethods)
1182 {
1183 perMethod.trie.validate();
1184 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001185 }
1186
Ed Tanous44e45182022-07-26 16:47:23 -07001187 struct FindRoute
1188 {
1189 BaseRule* rule = nullptr;
1190 RoutingParams params;
1191 };
1192
1193 struct FindRouteResponse
1194 {
1195 std::string allowHeader;
1196 FindRoute route;
1197 };
1198
Ed Tanous759cf102022-07-31 16:36:52 -07001199 FindRoute findRouteByIndex(std::string_view url, size_t index) const
1200 {
1201 FindRoute route;
1202 if (index >= perMethods.size())
1203 {
1204 BMCWEB_LOG_CRITICAL << "Bad index???";
1205 return route;
1206 }
1207 const PerMethod& perMethod = perMethods[index];
1208 std::pair<unsigned, RoutingParams> found = perMethod.trie.find(url);
1209 if (found.first >= perMethod.rules.size())
1210 {
1211 throw std::runtime_error("Trie internal structure corrupted!");
1212 }
1213 // Found a 404 route, switch that in
1214 if (found.first != 0U)
1215 {
1216 route.rule = perMethod.rules[found.first];
1217 route.params = std::move(found.second);
1218 }
1219 return route;
1220 }
1221
1222 FindRouteResponse findRoute(Request& req) const
Ed Tanous44e45182022-07-26 16:47:23 -07001223 {
1224 FindRouteResponse findRoute;
1225
Ed Tanous2c9efc32022-07-31 22:08:26 -07001226 std::optional<HttpVerb> verb = httpVerbFromBoost(req.method());
1227 if (!verb)
1228 {
1229 return findRoute;
1230 }
1231 size_t reqMethodIndex = static_cast<size_t>(*verb);
Ed Tanous44e45182022-07-26 16:47:23 -07001232 // Check to see if this url exists at any verb
1233 for (size_t perMethodIndex = 0; perMethodIndex <= maxVerbIndex;
1234 perMethodIndex++)
1235 {
1236 // Make sure it's safe to deference the array at that index
1237 static_assert(maxVerbIndex <
1238 std::tuple_size_v<decltype(perMethods)>);
Ed Tanous39662a32023-02-06 15:09:46 -08001239 FindRoute route =
1240 findRouteByIndex(req.url().encoded_path(), perMethodIndex);
Ed Tanous759cf102022-07-31 16:36:52 -07001241 if (route.rule == nullptr)
Ed Tanous44e45182022-07-26 16:47:23 -07001242 {
1243 continue;
1244 }
1245 if (!findRoute.allowHeader.empty())
1246 {
1247 findRoute.allowHeader += ", ";
1248 }
Ed Tanous2c9efc32022-07-31 22:08:26 -07001249 HttpVerb thisVerb = static_cast<HttpVerb>(perMethodIndex);
1250 findRoute.allowHeader += httpVerbToString(thisVerb);
Ed Tanous44e45182022-07-26 16:47:23 -07001251 if (perMethodIndex == reqMethodIndex)
1252 {
Ed Tanous759cf102022-07-31 16:36:52 -07001253 findRoute.route = route;
Ed Tanous44e45182022-07-26 16:47:23 -07001254 }
1255 }
1256 return findRoute;
1257 }
1258
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301259 static bool isUserPrivileged(
1260 Request& req, const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1261 BaseRule& rule, const dbus::utility::DBusPropertiesMap& userInfoMap)
Ed Tanouse1f5c162023-03-10 09:02:51 -08001262 {
Ed Tanous3d183202023-03-10 09:21:58 -08001263 std::string userRole{};
1264 const std::string* userRolePtr = nullptr;
1265 const bool* remoteUser = nullptr;
1266 const bool* passwordExpired = nullptr;
1267
1268 const bool success = sdbusplus::unpackPropertiesNoThrow(
1269 redfish::dbus_utils::UnpackErrorPrinter(), userInfoMap,
1270 "UserPrivilege", userRolePtr, "RemoteUser", remoteUser,
1271 "UserPasswordExpired", passwordExpired);
1272
1273 if (!success)
Ed Tanouse1f5c162023-03-10 09:02:51 -08001274 {
Ed Tanous3d183202023-03-10 09:21:58 -08001275 asyncResp->res.result(
1276 boost::beast::http::status::internal_server_error);
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301277 return false;
Ed Tanous3d183202023-03-10 09:21:58 -08001278 }
1279
1280 if (userRolePtr != nullptr)
1281 {
1282 userRole = *userRolePtr;
1283 BMCWEB_LOG_DEBUG << "userName = " << req.session->username
1284 << " userRole = " << *userRolePtr;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001285 }
1286
1287 if (remoteUser == nullptr)
1288 {
1289 BMCWEB_LOG_ERROR << "RemoteUser property missing or wrong type";
1290 asyncResp->res.result(
1291 boost::beast::http::status::internal_server_error);
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301292 return false;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001293 }
Ed Tanous3d183202023-03-10 09:21:58 -08001294 bool expired = false;
1295 if (passwordExpired == nullptr)
Ed Tanouse1f5c162023-03-10 09:02:51 -08001296 {
1297 if (!*remoteUser)
1298 {
1299 BMCWEB_LOG_ERROR
1300 << "UserPasswordExpired property is expected for"
1301 " local user but is missing or wrong type";
1302 asyncResp->res.result(
1303 boost::beast::http::status::internal_server_error);
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301304 return false;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001305 }
Ed Tanous3d183202023-03-10 09:21:58 -08001306 }
1307 else
1308 {
1309 expired = *passwordExpired;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001310 }
1311
1312 // Get the user's privileges from the role
1313 redfish::Privileges userPrivileges =
1314 redfish::getUserPrivileges(userRole);
1315
1316 // Set isConfigureSelfOnly based on D-Bus results. This
1317 // ignores the results from both pamAuthenticateUser and the
1318 // value from any previous use of this session.
Ed Tanous3d183202023-03-10 09:21:58 -08001319 req.session->isConfigureSelfOnly = expired;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001320
1321 // Modify privileges if isConfigureSelfOnly.
1322 if (req.session->isConfigureSelfOnly)
1323 {
1324 // Remove all privileges except ConfigureSelf
1325 userPrivileges = userPrivileges.intersection(
1326 redfish::Privileges{"ConfigureSelf"});
1327 BMCWEB_LOG_DEBUG << "Operation limited to ConfigureSelf";
1328 }
1329
1330 if (!rule.checkPrivileges(userPrivileges))
1331 {
1332 asyncResp->res.result(boost::beast::http::status::forbidden);
1333 if (req.session->isConfigureSelfOnly)
1334 {
1335 redfish::messages::passwordChangeRequired(
1336 asyncResp->res, crow::utility::urlFromPieces(
1337 "redfish", "v1", "AccountService",
1338 "Accounts", req.session->username));
1339 }
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301340 return false;
Ed Tanouse1f5c162023-03-10 09:02:51 -08001341 }
1342
1343 req.userRole = userRole;
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301344
1345 return true;
1346 }
1347
1348 template <typename CallbackFn>
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001349 void afterGetUserInfo(Request& req,
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301350 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1351 BaseRule& rule, CallbackFn&& callback,
1352 const boost::system::error_code& ec,
1353 const dbus::utility::DBusPropertiesMap& userInfoMap)
1354 {
1355 if (ec)
1356 {
1357 BMCWEB_LOG_ERROR << "GetUserInfo failed...";
1358 asyncResp->res.result(
1359 boost::beast::http::status::internal_server_error);
1360 return;
1361 }
1362
1363 if (!Router::isUserPrivileged(req, asyncResp, rule, userInfoMap))
1364 {
1365 // User is not privileged
1366 BMCWEB_LOG_ERROR << "Insufficient Privilege";
1367 asyncResp->res.result(boost::beast::http::status::forbidden);
1368 return;
1369 }
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001370 callback(req);
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301371 }
1372
1373 template <typename CallbackFn>
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001374 void validatePrivilege(Request& req,
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301375 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1376 BaseRule& rule, CallbackFn&& callback)
1377 {
Ed Tanous915d2d42023-03-15 13:09:34 -07001378 if (req.session == nullptr)
1379 {
1380 return;
1381 }
1382 std::string username = req.session->username;
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301383 crow::connections::systemBus->async_method_call(
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001384 [this, &req, asyncResp, &rule,
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301385 callback(std::forward<CallbackFn>(callback))](
1386 const boost::system::error_code& ec,
1387 const dbus::utility::DBusPropertiesMap& userInfoMap) mutable {
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001388 afterGetUserInfo(req, asyncResp, rule,
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301389 std::forward<CallbackFn>(callback), ec,
1390 userInfoMap);
1391 },
1392 "xyz.openbmc_project.User.Manager", "/xyz/openbmc_project/user",
Ed Tanous915d2d42023-03-15 13:09:34 -07001393 "xyz.openbmc_project.User.Manager", "GetUserInfo", username);
Ed Tanouse1f5c162023-03-10 09:02:51 -08001394 }
1395
Ed Tanous1abe55e2018-09-05 08:30:59 -07001396 template <typename Adaptor>
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301397 void handleUpgrade(Request& req,
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +05301398 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp,
1399 Adaptor&& adaptor)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001400 {
Ed Tanous2c9efc32022-07-31 22:08:26 -07001401 std::optional<HttpVerb> verb = httpVerbFromBoost(req.method());
1402 if (!verb || static_cast<size_t>(*verb) >= perMethods.size())
Ed Tanous888880a2020-08-24 13:48:50 -07001403 {
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +05301404 asyncResp->res.result(boost::beast::http::status::not_found);
Tanousf00032d2018-11-05 01:18:10 -03001405 return;
Ed Tanous888880a2020-08-24 13:48:50 -07001406 }
Ed Tanous2c9efc32022-07-31 22:08:26 -07001407 PerMethod& perMethod = perMethods[static_cast<size_t>(*verb)];
Tanousf00032d2018-11-05 01:18:10 -03001408 Trie& trie = perMethod.trie;
1409 std::vector<BaseRule*>& rules = perMethod.rules;
1410
Ed Tanous39662a32023-02-06 15:09:46 -08001411 const std::pair<unsigned, RoutingParams>& found =
1412 trie.find(req.url().encoded_path());
Ed Tanous1abe55e2018-09-05 08:30:59 -07001413 unsigned ruleIndex = found.first;
Ed Tanouse662eae2022-01-25 10:39:19 -08001414 if (ruleIndex == 0U)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001415 {
Ed Tanous39662a32023-02-06 15:09:46 -08001416 BMCWEB_LOG_DEBUG << "Cannot match rules "
1417 << req.url().encoded_path();
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +05301418 asyncResp->res.result(boost::beast::http::status::not_found);
Ed Tanous1abe55e2018-09-05 08:30:59 -07001419 return;
1420 }
1421
1422 if (ruleIndex >= rules.size())
Ed Tanous3174e4d2020-10-07 11:41:22 -07001423 {
Ed Tanous1abe55e2018-09-05 08:30:59 -07001424 throw std::runtime_error("Trie internal structure corrupted!");
Ed Tanous3174e4d2020-10-07 11:41:22 -07001425 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001426
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301427 BaseRule& rule = *rules[ruleIndex];
1428 size_t methods = rule.getMethods();
1429 if ((methods & (1U << static_cast<size_t>(*verb))) == 0)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001430 {
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301431 BMCWEB_LOG_DEBUG
1432 << "Rule found but method mismatch: "
1433 << req.url().encoded_path() << " with " << req.methodString()
1434 << "(" << static_cast<uint32_t>(*verb) << ") / " << methods;
P Dheeraj Srujan Kumara9f076e2021-10-18 22:45:37 +05301435 asyncResp->res.result(boost::beast::http::status::not_found);
Ed Tanous1abe55e2018-09-05 08:30:59 -07001436 return;
1437 }
1438
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301439 BMCWEB_LOG_DEBUG << "Matched rule (upgrade) '" << rule.rule << "' "
1440 << static_cast<uint32_t>(*verb) << " / " << methods;
Ed Tanous1abe55e2018-09-05 08:30:59 -07001441
P Dheeraj Srujan Kumar7e9093e2021-09-18 01:19:04 +05301442 // TODO(ed) This should be able to use std::bind_front, but it doesn't
1443 // appear to work with the std::move on adaptor.
Ed Tanous915d2d42023-03-15 13:09:34 -07001444 validatePrivilege(
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001445 req, asyncResp, rule,
Ed Tanous915d2d42023-03-15 13:09:34 -07001446 [&rule, asyncResp, adaptor(std::forward<Adaptor>(adaptor))](
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001447 Request& thisReq) mutable {
Ed Tanous915d2d42023-03-15 13:09:34 -07001448 rule.handleUpgrade(thisReq, asyncResp, std::move(adaptor));
1449 });
Ed Tanous7045c8d2017-04-03 10:04:37 -07001450 }
1451
zhanghch058d1b46d2021-04-01 11:18:24 +08001452 void handle(Request& req,
1453 const std::shared_ptr<bmcweb::AsyncResp>& asyncResp)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001454 {
Ed Tanous2c9efc32022-07-31 22:08:26 -07001455 std::optional<HttpVerb> verb = httpVerbFromBoost(req.method());
1456 if (!verb || static_cast<size_t>(*verb) >= perMethods.size())
Ed Tanous888880a2020-08-24 13:48:50 -07001457 {
zhanghch058d1b46d2021-04-01 11:18:24 +08001458 asyncResp->res.result(boost::beast::http::status::not_found);
Tanousf00032d2018-11-05 01:18:10 -03001459 return;
Ed Tanous888880a2020-08-24 13:48:50 -07001460 }
Ed Tanous44e45182022-07-26 16:47:23 -07001461
1462 FindRouteResponse foundRoute = findRoute(req);
1463
Ed Tanous759cf102022-07-31 16:36:52 -07001464 if (foundRoute.route.rule == nullptr)
Ed Tanous88a03c52022-03-14 10:16:07 -07001465 {
Ed Tanous759cf102022-07-31 16:36:52 -07001466 // Couldn't find a normal route with any verb, try looking for a 404
1467 // route
1468 if (foundRoute.allowHeader.empty())
Ed Tanous44e45182022-07-26 16:47:23 -07001469 {
Ed Tanous39662a32023-02-06 15:09:46 -08001470 foundRoute.route =
1471 findRouteByIndex(req.url().encoded_path(), notFoundIndex);
Ed Tanous759cf102022-07-31 16:36:52 -07001472 }
1473 else
1474 {
1475 // See if we have a method not allowed (405) handler
Ed Tanous39662a32023-02-06 15:09:46 -08001476 foundRoute.route = findRouteByIndex(req.url().encoded_path(),
1477 methodNotAllowedIndex);
Ed Tanous44e45182022-07-26 16:47:23 -07001478 }
1479 }
Ed Tanous759cf102022-07-31 16:36:52 -07001480
1481 // Fill in the allow header if it's valid
1482 if (!foundRoute.allowHeader.empty())
Ed Tanous44e45182022-07-26 16:47:23 -07001483 {
Ed Tanous759cf102022-07-31 16:36:52 -07001484
Ed Tanous88a03c52022-03-14 10:16:07 -07001485 asyncResp->res.addHeader(boost::beast::http::field::allow,
Ed Tanous44e45182022-07-26 16:47:23 -07001486 foundRoute.allowHeader);
Ed Tanous88a03c52022-03-14 10:16:07 -07001487 }
Tanousf00032d2018-11-05 01:18:10 -03001488
Ed Tanous44e45182022-07-26 16:47:23 -07001489 // If we couldn't find a real route or a 404 route, return a generic
1490 // response
1491 if (foundRoute.route.rule == nullptr)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001492 {
Ed Tanous44e45182022-07-26 16:47:23 -07001493 if (foundRoute.allowHeader.empty())
1494 {
1495 asyncResp->res.result(boost::beast::http::status::not_found);
1496 }
1497 else
Ed Tanous2634dcd2019-03-26 09:28:06 -07001498 {
Ed Tanous88a03c52022-03-14 10:16:07 -07001499 asyncResp->res.result(
1500 boost::beast::http::status::method_not_allowed);
Ed Tanous2634dcd2019-03-26 09:28:06 -07001501 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001502 return;
1503 }
1504
Ed Tanous44e45182022-07-26 16:47:23 -07001505 BaseRule& rule = *foundRoute.route.rule;
1506 RoutingParams params = std::move(foundRoute.route.params);
Ed Tanous1abe55e2018-09-05 08:30:59 -07001507
Ed Tanous44e45182022-07-26 16:47:23 -07001508 BMCWEB_LOG_DEBUG << "Matched rule '" << rule.rule << "' "
Snehalatha Venkatesh1c99da02022-12-27 06:45:35 +00001509 << static_cast<uint32_t>(*verb) << " / "
Ed Tanous44e45182022-07-26 16:47:23 -07001510 << rule.getMethods();
Ed Tanous1abe55e2018-09-05 08:30:59 -07001511
RAJESWARAN THILLAIGOVINDAN61dbeef2019-12-13 04:26:54 -06001512 if (req.session == nullptr)
James Feist7166bf02019-12-10 16:52:14 +00001513 {
Ed Tanous44e45182022-07-26 16:47:23 -07001514 rule.handle(req, asyncResp, params);
James Feist7166bf02019-12-10 16:52:14 +00001515 return;
1516 }
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001517 validatePrivilege(req, asyncResp, rule,
1518 [&rule, asyncResp, params](Request& thisReq) mutable {
Ed Tanous915d2d42023-03-15 13:09:34 -07001519 rule.handle(thisReq, asyncResp, params);
Jonathan Domand3c8ce62023-03-21 18:17:06 -07001520 });
Ed Tanous7045c8d2017-04-03 10:04:37 -07001521 }
Ed Tanous7045c8d2017-04-03 10:04:37 -07001522
Ed Tanous1abe55e2018-09-05 08:30:59 -07001523 void debugPrint()
1524 {
Ed Tanous271584a2019-07-09 16:24:22 -07001525 for (size_t i = 0; i < perMethods.size(); i++)
Tanousf00032d2018-11-05 01:18:10 -03001526 {
Ed Tanous23a21a12020-07-25 04:45:05 +00001527 BMCWEB_LOG_DEBUG << boost::beast::http::to_string(
1528 static_cast<boost::beast::http::verb>(i));
Tanousf00032d2018-11-05 01:18:10 -03001529 perMethods[i].trie.debugPrint();
1530 }
Ed Tanous3dac7492017-08-02 13:46:20 -07001531 }
Ed Tanousb4a7bfa2017-04-04 17:23:00 -07001532
Ed Tanous1abe55e2018-09-05 08:30:59 -07001533 std::vector<const std::string*> getRoutes(const std::string& parent)
1534 {
Ed Tanous1abe55e2018-09-05 08:30:59 -07001535 std::vector<const std::string*> ret;
Tanousf00032d2018-11-05 01:18:10 -03001536
1537 for (const PerMethod& pm : perMethods)
Ed Tanous1abe55e2018-09-05 08:30:59 -07001538 {
Tanousf00032d2018-11-05 01:18:10 -03001539 std::vector<unsigned> x;
1540 pm.trie.findRouteIndexes(parent, x);
1541 for (unsigned index : x)
1542 {
1543 ret.push_back(&pm.rules[index]->rule);
1544 }
Ed Tanous1abe55e2018-09-05 08:30:59 -07001545 }
1546 return ret;
1547 }
1548
1549 private:
Tanousf00032d2018-11-05 01:18:10 -03001550 struct PerMethod
1551 {
1552 std::vector<BaseRule*> rules;
1553 Trie trie;
Ed Tanous313a3c22022-03-14 09:27:38 -07001554 // rule index 0 has special meaning; preallocate it to avoid
Tanousf00032d2018-11-05 01:18:10 -03001555 // duplication.
Ed Tanous313a3c22022-03-14 09:27:38 -07001556 PerMethod() : rules(1)
Gunnar Mills1214b7e2020-06-04 10:11:30 -05001557 {}
Tanousf00032d2018-11-05 01:18:10 -03001558 };
Ed Tanous888880a2020-08-24 13:48:50 -07001559
Ed Tanous759cf102022-07-31 16:36:52 -07001560 std::array<PerMethod, methodNotAllowedIndex + 1> perMethods;
Tanousf00032d2018-11-05 01:18:10 -03001561 std::vector<std::unique_ptr<BaseRule>> allRules;
Ed Tanous7045c8d2017-04-03 10:04:37 -07001562};
Ed Tanous1abe55e2018-09-05 08:30:59 -07001563} // namespace crow