TLA Line data Source code
1 : //
2 : // Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3 : //
4 : // Distributed under the Boost Software License, Version 1.0. (See accompanying
5 : // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6 : //
7 : // Official repository: https://github.com/cppalliance/http
8 : //
9 :
10 : #ifndef BOOST_HTTP_SERVER_ROUTE_HANDLER_HPP
11 : #define BOOST_HTTP_SERVER_ROUTE_HANDLER_HPP
12 :
13 : #include <boost/http/detail/config.hpp>
14 : #include <boost/http/method.hpp>
15 : #include <boost/http/detail/except.hpp>
16 : #include <boost/http/datastore.hpp>
17 : #include <boost/http/request.hpp>
18 : #include <boost/http/response.hpp>
19 : #include <boost/core/detail/string_view.hpp>
20 : #include <boost/capy/buffers.hpp>
21 : #include <boost/capy/buffers/make_buffer.hpp>
22 : #include <boost/capy/results.hpp>
23 : #include <boost/capy/task.hpp>
24 : #include <boost/capy/write.hpp>
25 : #include <boost/http/io/any_buffer_source.hpp>
26 : #include <boost/http/io/any_buffer_sink.hpp>
27 : #include <boost/url/url_view.hpp>
28 : #include <system_error>
29 : #include <concepts>
30 : #include <exception>
31 : #include <memory>
32 : #include <span>
33 : #include <string>
34 : #include <type_traits>
35 : #include <utility>
36 : #include <vector>
37 :
38 : namespace boost {
39 : namespace http {
40 :
41 : /** Directive values for route handler results.
42 :
43 : These values indicate how the router should proceed
44 : after a handler completes. Handlers return one of
45 : the predefined constants (@ref route_done, @ref route_next,
46 : @ref route_next_route, @ref route_close) or an error code.
47 :
48 : @see route_result, route_task
49 : */
50 : enum class route_what
51 : {
52 : /// Handler completed successfully, response was sent
53 : done,
54 :
55 : /// Handler declined, try next handler in the route
56 : next,
57 :
58 : /// Handler declined, skip to next matching route
59 : next_route,
60 :
61 : /// Handler requests connection closure
62 : close,
63 :
64 : /// Handler encountered an error
65 : error
66 : };
67 :
68 : //------------------------------------------------
69 :
70 : /** The result type returned by route handlers.
71 :
72 : This class represents the outcome of a route handler.
73 : Handlers return this type to indicate how the router
74 : should proceed. Construct from a directive constant
75 : or an error code:
76 :
77 : @code
78 : route_task my_handler(route_params& p)
79 : {
80 : if(! authorized(p))
81 : co_return route_next; // try next handler
82 :
83 : if(auto ec = process(p); ec)
84 : co_return ec; // return error
85 :
86 : co_return route_done; // success
87 : }
88 : @endcode
89 :
90 : @par Checking Results
91 :
92 : Use @ref what() to determine the directive, and
93 : @ref error() to retrieve any error code:
94 :
95 : @code
96 : route_result rv = co_await handler(p);
97 : if(rv.what() == route_what::error)
98 : handle_error(rv.error());
99 : @endcode
100 :
101 : @see route_task, route_what, route_done, route_next
102 : */
103 : class BOOST_HTTP_DECL
104 : route_result
105 : {
106 : std::error_code ec_;
107 :
108 : template<route_what T>
109 : struct what_t {};
110 :
111 : route_result(std::error_code ec);
112 : void set(route_what w);
113 :
114 : public:
115 HIT 227 : route_result() = default;
116 :
117 : /** Construct from a directive constant.
118 :
119 : This constructor allows implicit conversion from
120 : the predefined constants (@ref route_done, @ref route_next,
121 : @ref route_next_route, @ref route_close).
122 :
123 : @code
124 : route_task handler(route_params& p)
125 : {
126 : co_return route_done; // implicitly converts
127 : }
128 : @endcode
129 : */
130 : template<route_what W>
131 132 : route_result(what_t<W>)
132 132 : {
133 : static_assert(W != route_what::error);
134 132 : set(W);
135 132 : }
136 :
137 : /** Return the directive for this result.
138 :
139 : Call this to determine how the router should proceed:
140 :
141 : @code
142 : route_result rv = co_await handler(p);
143 : switch(rv.what())
144 : {
145 : case route_what::done:
146 : // response sent, done with request
147 : break;
148 : case route_what::next:
149 : // try next handler
150 : break;
151 : case route_what::error:
152 : log_error(rv.error());
153 : break;
154 : }
155 : @endcode
156 :
157 : @return The directive value.
158 : */
159 : auto
160 : what() const noexcept ->
161 : route_what;
162 :
163 : /** Return the error code, if any.
164 :
165 : If @ref what() returns `route_what::error`, this
166 : returns the underlying error code. Otherwise returns
167 : a default-constructed (non-failing) error code.
168 :
169 : @return The error code, or a non-failing code.
170 : */
171 : auto
172 : error() const noexcept ->
173 : std::error_code;
174 :
175 : /** Return true if the result indicates an error.
176 :
177 : @return `true` if @ref what() equals `route_what::error`.
178 : */
179 1 : bool failed() const noexcept
180 : {
181 1 : return what() == route_what::error;
182 : }
183 :
184 : static constexpr route_result::what_t<route_what::done> route_done{};
185 : static constexpr route_result::what_t<route_what::next> route_next{};
186 : static constexpr route_result::what_t<route_what::next_route> route_next_route{};
187 : static constexpr route_result::what_t<route_what::close> route_close{};
188 : friend route_result route_error(std::error_code ec) noexcept;
189 :
190 : template<class E>
191 : friend auto route_error(E e) noexcept ->
192 : std::enable_if_t<
193 : std::is_error_code_enum<E>::value,
194 : route_result>;
195 : };
196 :
197 : //------------------------------------------------
198 :
199 : /** Handler completed successfully.
200 :
201 : Return this from a handler to indicate the response
202 : was sent and the request is complete:
203 :
204 : @code
205 : route_task handler(route_params& p)
206 : {
207 : p.res.set(field::content_type, "text/plain");
208 : co_await p.send("Hello, World!");
209 : co_return route_done;
210 : }
211 : @endcode
212 : */
213 : inline constexpr decltype(auto) route_done = route_result::route_done;
214 :
215 : /** Handler declined, try next handler.
216 :
217 : Return this from a handler to decline processing
218 : and allow the next handler in the route to try:
219 :
220 : @code
221 : route_task auth_handler(route_params& p)
222 : {
223 : if(! p.req.exists(field::authorization))
224 : co_return route_next; // let another handler try
225 :
226 : // process authenticated request...
227 : co_return route_done;
228 : }
229 : @endcode
230 : */
231 : inline constexpr decltype(auto) route_next = route_result::route_next;
232 :
233 : /** Handler declined, skip to next route.
234 :
235 : Return this from a handler to skip all remaining
236 : handlers in the current route and proceed to the
237 : next matching route:
238 :
239 : @code
240 : route_task version_check(route_params& p)
241 : {
242 : if(p.req.version() < 11)
243 : co_return route_next_route; // skip this route
244 :
245 : co_return route_next; // continue with this route
246 : }
247 : @endcode
248 : */
249 : inline constexpr decltype(auto) route_next_route = route_result::route_next_route;
250 :
251 : /** Handler requests connection closure.
252 :
253 : Return this from a handler to immediately close
254 : the connection without sending a response:
255 :
256 : @code
257 : route_task ban_check(route_params& p)
258 : {
259 : if(is_banned(p.req.remote_address()))
260 : co_return route_close; // drop connection
261 :
262 : co_return route_next;
263 : }
264 : @endcode
265 : */
266 : inline constexpr decltype(auto) route_close = route_result::route_close;
267 :
268 : /** Construct from an error code.
269 :
270 : Use this constructor to return an error from a handler.
271 : The error code must represent a failure condition.
272 :
273 : @param ec The error code to return.
274 :
275 : @throw std::invalid_argument if `!ec` (non-failing code).
276 : */
277 11 : inline route_result route_error(std::error_code ec) noexcept
278 : {
279 11 : return route_result(ec);
280 : }
281 :
282 : /** Construct from an error enum.
283 :
284 : Use this overload to return an error from a handler
285 : using any type satisfying `is_error_code_enum`.
286 :
287 : @param e The error enum value to return.
288 : */
289 : template<class E>
290 2 : auto route_error(E e) noexcept ->
291 : std::enable_if_t<
292 : std::is_error_code_enum<E>::value,
293 : route_result>
294 : {
295 2 : return route_result(make_error_code(e));
296 : }
297 :
298 : //------------------------------------------------
299 :
300 : /** Convenience alias for route handler return type.
301 :
302 : Route handlers are coroutines that return a @ref route_result
303 : indicating how the router should proceed. This alias simplifies
304 : handler declarations:
305 :
306 : @code
307 : route_task my_handler(route_params& p)
308 : {
309 : // process request...
310 : co_return route_done;
311 : }
312 :
313 : route_task auth_middleware(route_params& p)
314 : {
315 : if(! check_token(p))
316 : {
317 : p.res.set_status(status::unauthorized);
318 : co_await p.send();
319 : co_return route_done;
320 : }
321 : co_return route_next; // continue to next handler
322 : }
323 : @endcode
324 :
325 : @see route_result, route_params
326 : */
327 : using route_task = capy::task<route_result>;
328 :
329 : //------------------------------------------------
330 :
331 : template<class, class> class router;
332 :
333 : namespace detail {
334 :
335 : struct route_params_access;
336 : class router_base;
337 :
338 : struct route_params_base_privates
339 : {
340 : std::string verb_str_;
341 : std::string decoded_path_;
342 : std::error_code ec_;
343 : std::exception_ptr ep_;
344 : std::size_t pos_ = 0;
345 : std::size_t resume_ = 0;
346 : http::method verb_ =
347 : http::method::unknown;
348 : bool addedSlash_ = false;
349 : bool case_sensitive = false;
350 : bool strict = false;
351 : char kind_ = 0;
352 : };
353 :
354 : } // detail
355 :
356 : //------------------------------------------------
357 :
358 : /** Parameters object for HTTP route handlers.
359 :
360 : This structure holds all the context needed for a route
361 : handler to process an HTTP request and generate a response.
362 :
363 : @par Example
364 : @code
365 : route_task my_handler(route_params& p)
366 : {
367 : p.res.set(field::content_type, "text/plain");
368 : co_await p.send("Hello, World!");
369 : co_return route_done;
370 : }
371 : @endcode
372 :
373 : @see route_task, route_result
374 : */
375 : class BOOST_HTTP_SYMBOL_VISIBLE
376 : route_params
377 : {
378 : detail::route_params_base_privates priv_;
379 :
380 : public:
381 : struct match_result;
382 :
383 : /** Return true if the request method matches `m`
384 : */
385 MIS 0 : bool is_method(
386 : http::method m) const noexcept
387 : {
388 0 : return priv_.verb_ == m;
389 : }
390 :
391 : /** Return true if the request method matches `s`
392 : */
393 : BOOST_HTTP_DECL
394 : bool is_method(
395 : core::string_view s) const noexcept;
396 :
397 : /** The mount path of the current router
398 :
399 : This is the portion of the request path
400 : which was matched to select the handler.
401 : The remaining portion is available in
402 : @ref path.
403 : */
404 : core::string_view base_path;
405 :
406 : /** The current pathname, relative to the base path
407 : */
408 : core::string_view path;
409 :
410 : /** Captured route parameters
411 :
412 : Contains name-value pairs extracted from the path
413 : by matching :param and *wildcard tokens.
414 : */
415 : std::vector<std::pair<std::string, std::string>> params;
416 :
417 : /// The complete request target
418 : urls::url_view url;
419 :
420 : /// The HTTP request
421 : http::request req;
422 :
423 : /// The HTTP response
424 : http::response res;
425 :
426 : /// Provides access to the request body
427 : http::any_buffer_source req_body;
428 :
429 : /// Provides access to the response body
430 : http::any_buffer_sink res_body;
431 :
432 : /// Arbitrary per-route data
433 : http::datastore route_data;
434 :
435 : /// Arbitrary per-session data
436 : http::datastore session_data;
437 :
438 : BOOST_HTTP_DECL ~route_params();
439 : BOOST_HTTP_DECL void reset();
440 : BOOST_HTTP_DECL route_params& status(http::status code);
441 :
442 : /** Send the response with an optional body.
443 : */
444 : BOOST_HTTP_DECL capy::task<capy::results<>> send(std::string_view body = {});
445 :
446 : private:
447 : template<class, class>
448 : friend class router;
449 : friend class detail::router_base;
450 : friend struct detail::route_params_access;
451 :
452 : route_params& operator=(
453 : route_params const&) = delete;
454 : };
455 :
456 : struct route_params::
457 : match_result
458 : {
459 : std::vector<std::pair<std::string, std::string>> params_;
460 :
461 HIT 136 : void adjust_path(
462 : route_params& p,
463 : std::size_t n)
464 : {
465 136 : n_ = n;
466 136 : if(n_ == 0)
467 50 : return;
468 86 : p.base_path = {
469 : p.base_path.data(),
470 86 : p.base_path.size() + n_ };
471 86 : if(n_ < p.path.size())
472 : {
473 28 : p.path.remove_prefix(n_);
474 : }
475 : else
476 : {
477 : // append a soft slash
478 58 : p.path = { p.priv_.decoded_path_.data() +
479 58 : p.priv_.decoded_path_.size() - 1, 1};
480 58 : BOOST_ASSERT(p.path == "/");
481 : }
482 : }
483 :
484 : void restore_path(
485 : route_params& p)
486 : {
487 : if( n_ > 0 &&
488 : p.priv_.addedSlash_ &&
489 : p.path.data() ==
490 : p.priv_.decoded_path_.data() +
491 : p.priv_.decoded_path_.size() - 1)
492 : {
493 : // remove soft slash
494 : p.path = {
495 : p.base_path.data() +
496 : p.base_path.size(), 0 };
497 : }
498 : p.base_path.remove_suffix(n_);
499 : p.path = {
500 : p.path.data() - n_,
501 : p.path.size() + n_ };
502 : }
503 :
504 : private:
505 : std::size_t n_ = 0; // chars moved from path to base_path
506 : };
507 :
508 : //------------------------------------------------
509 :
510 : namespace detail {
511 :
512 : template<class H, class... Args>
513 : concept returns_route_task = std::same_as<
514 : std::invoke_result_t<H, Args...>, route_task>;
515 :
516 : struct route_params_access
517 : {
518 : route_params& rp;
519 :
520 360 : route_params_base_privates& operator*() const noexcept
521 : {
522 360 : return rp.priv_;
523 : }
524 :
525 62 : route_params_base_privates* operator->() const noexcept
526 : {
527 62 : return &rp.priv_;
528 : }
529 : };
530 :
531 : } // detail
532 :
533 : } // http
534 : } // boost
535 :
536 : #endif
|