summaryrefslogtreecommitdiffstats
path: root/server/src/http
diff options
context:
space:
mode:
authorRutger Broekhoff2026-11-30 21:27:55 +0100
committerRutger Broekhoff2026-11-30 21:27:55 +0100
commit7bba7176194c4d1d9c7066f8eda7a94491d924e6 (patch)
treea9a171e8608786e09d6342729ee13b8471c0c9c2 /server/src/http
parent02475e05ccd1aa15c6a6163834f28bfebbef796f (diff)
downloadroutemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.tar.gz
routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.zip
Cleanups and updates
Diffstat (limited to 'server/src/http')
-rw-r--r--server/src/http/core/client.cpp20
-rw-r--r--server/src/http/core/client.cppm65
-rw-r--r--server/src/http/core/common.cpp108
-rw-r--r--server/src/http/core/common.cppm79
-rw-r--r--server/src/http/core/server.cpp209
-rw-r--r--server/src/http/core/server.cppm799
-rw-r--r--server/src/http/ext/gpx.cpp139
-rw-r--r--server/src/http/ext/gpx.cppm128
-rw-r--r--server/src/http/ext/hmac_openssl.cppm173
-rw-r--r--server/src/http/ext/json.cpp34
-rw-r--r--server/src/http/ext/json.cppm65
-rw-r--r--server/src/http/ext/raw_deflate.cppm134
-rw-r--r--server/src/http/handler.cpp348
-rw-r--r--server/src/http/handler.cppm41
-rw-r--r--server/src/http/server.cpp61
-rw-r--r--server/src/http/server.cppm31
16 files changed, 2432 insertions, 2 deletions
diff --git a/server/src/http/core/client.cpp b/server/src/http/core/client.cpp
new file mode 100644
index 0000000..c0143b0
--- /dev/null
+++ b/server/src/http/core/client.cpp
@@ -0,0 +1,20 @@
1module;
2
3#include <boost/asio/ssl.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6
7module routemon:http.core.client$impl;
8
9import :http.core.client;
10
11namespace routemon::http::core {
12
13client::client(net::io_context& ioc) : ioc_{ioc}, resolver_{ioc}
14{
15 sslc_.set_default_verify_paths();
16 sslc_.set_verify_mode(
17 net::ssl::verify_peer | net::ssl::verify_fail_if_no_peer_cert);
18}
19
20} // namespace routemon::http::core
diff --git a/server/src/http/core/client.cppm b/server/src/http/core/client.cppm
new file mode 100644
index 0000000..ada4f03
--- /dev/null
+++ b/server/src/http/core/client.cppm
@@ -0,0 +1,65 @@
1module;
2
3#include <boost/asio/connect.hpp>
4#include <boost/asio/ip/tcp.hpp>
5#include <boost/asio/ssl.hpp>
6#include <boost/beast/core.hpp>
7#include <boost/beast/http.hpp>
8
9export module routemon:http.core.client;
10
11export import :http.core.common;
12
13namespace net = boost::asio;
14namespace ssl = net::ssl;
15using tcp = net::ip::tcp;
16
17namespace routemon::http::core {
18
19export class client
20{
21 net::io_context& ioc_;
22 ssl::context sslc_{ssl::context::tlsv12_client};
23 tcp::resolver resolver_;
24
25public:
26 explicit client(net::io_context& ioc);
27
28 template <class ReqBody>
29 auto do_request(bhttp::request<ReqBody>& req)
30 -> bhttp::response<bhttp::dynamic_body>
31 {
32 // TODO: call into non-template member ASAP.
33 // Consider using beast::message_generator.
34
35 auto stream = ssl::stream<beast::tcp_stream>{ioc_, sslc_};
36
37 auto host = std::string{req.at(bhttp::field::host)};
38 if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str()))
39 {
40 throw beast::system_error{
41 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
42 };
43 }
44 stream.set_verify_callback(ssl::host_name_verification(host));
45 auto const results = resolver_.resolve(host, "443");
46 beast::get_lowest_layer(stream).connect(results);
47 stream.handshake(ssl::stream_base::client);
48
49 req.set(bhttp::field::user_agent, "routemon/1.0");
50 bhttp::write(stream, req);
51
52 auto buffer = beast::flat_buffer{};
53 auto res = bhttp::response<bhttp::dynamic_body>{};
54 bhttp::read(stream, buffer, res);
55
56 auto ec = beast::error_code{};
57 stream.shutdown(ec);
58 if (ec != net::ssl::error::stream_truncated)
59 throw beast::system_error{ec};
60
61 return res;
62 }
63};
64
65} // namespace routemon::http::core
diff --git a/server/src/http/core/common.cpp b/server/src/http/core/common.cpp
new file mode 100644
index 0000000..bc3ef31
--- /dev/null
+++ b/server/src/http/core/common.cpp
@@ -0,0 +1,108 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5
6module routemon:http.core.common$impl;
7
8import :http.core.common;
9
10namespace routemon::http::core {
11
12supported_verb::supported_verb(supported_verb_t value) : value{value} {}
13
14auto supported_verb::from(bhttp::verb v) -> std::optional<supported_verb>
15{
16 switch (v)
17 {
18 case bhttp::verb::options:
19 return supported_verb::options;
20 case bhttp::verb::delete_:
21 return supported_verb::delete_;
22 case bhttp::verb::get:
23 return supported_verb::get;
24 case bhttp::verb::head:
25 return supported_verb::head;
26 case bhttp::verb::post:
27 return supported_verb::post;
28 case bhttp::verb::put:
29 return supported_verb::put;
30 default:
31 return std::nullopt;
32 }
33}
34
35supported_verb::operator bhttp::verb() const
36{
37 switch (value)
38 {
39 case supported_verb::options:
40 return bhttp::verb::options;
41 case supported_verb::delete_:
42 return bhttp::verb::delete_;
43 case supported_verb::get:
44 return bhttp::verb::get;
45 case supported_verb::head:
46 return bhttp::verb::head;
47 case supported_verb::post:
48 return bhttp::verb::post;
49 case supported_verb::put:
50 return bhttp::verb::put;
51 }
52}
53
54auto verb_set::with(supported_verb v) const noexcept -> verb_set
55{
56 auto set = verb_set{*this};
57 switch (v.value)
58 {
59 case supported_verb::delete_:
60 set.delete_ = true;
61 return set;
62 case supported_verb::get:
63 set.get = true;
64 return set;
65 case supported_verb::head:
66 set.head = true;
67 return set;
68 case supported_verb::post:
69 set.post = true;
70 return set;
71 case supported_verb::put:
72 set.put = true;
73 return set;
74 case supported_verb::options:
75 set.options = true;
76 return set;
77 }
78}
79
80auto verb_set::empty() const noexcept -> bool { return *this == verb_set{}; }
81
82auto verb_set::to_string() const -> std::string
83{
84 std::ostringstream ss;
85 bool wrote = false;
86 auto write = [&](bhttp::verb v)
87 {
88 if (wrote)
89 ss << ", ";
90 ss << v;
91 wrote = true;
92 };
93 if (delete_)
94 write(bhttp::verb::delete_);
95 if (get)
96 write(bhttp::verb::get);
97 if (head)
98 write(bhttp::verb::head);
99 if (post)
100 write(bhttp::verb::post);
101 if (put)
102 write(bhttp::verb::put);
103 if (options)
104 write(bhttp::verb::options);
105 return ss.str();
106}
107
108} // namespace routemon::http::core
diff --git a/server/src/http/core/common.cppm b/server/src/http/core/common.cppm
new file mode 100644
index 0000000..e8fbe42
--- /dev/null
+++ b/server/src/http/core/common.cppm
@@ -0,0 +1,79 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5
6export module routemon:http.core.common;
7
8namespace beast = boost::beast;
9export namespace bhttp = beast::http;
10
11namespace boost::beast {
12
13namespace concepts {
14
15template <class T>
16concept buffers_generator = beast::is_buffers_generator<T>::value;
17
18template <class T>
19concept const_buffer_sequence = beast::is_const_buffer_sequence<T>::value;
20
21} // namespace concepts
22
23namespace http::concepts {
24
25template <class T>
26concept fields = is_fields<T>::value;
27
28template <class T>
29concept body = is_body<T>::value;
30
31template <class T>
32concept body_reader = is_body_reader<T>::value;
33
34} // namespace http::concepts
35
36} // namespace boost::beast
37
38namespace routemon::http::core {
39
40struct supported_verb
41{
42 enum supported_verb_t : std::uint8_t
43 {
44 options,
45 delete_,
46 get,
47 head,
48 post,
49 put,
50 };
51
52 supported_verb_t value;
53
54 supported_verb(supported_verb_t value);
55
56 static auto from(bhttp::verb v) -> std::optional<supported_verb>;
57
58 operator bhttp::verb() const;
59};
60
61export struct verb_set
62{
63 bool options : 1 = false;
64 bool delete_ : 1 = false;
65 bool get : 1 = false;
66 bool head : 1 = false;
67 bool post : 1 = false;
68 bool put : 1 = false;
69
70 [[nodiscard]] auto with(supported_verb v) const noexcept -> verb_set;
71 [[nodiscard]] auto empty() const noexcept -> bool;
72 [[nodiscard]] auto to_string() const -> std::string;
73
74 auto operator==(verb_set const& rhs) const noexcept -> bool = default;
75};
76static_assert(sizeof(verb_set) == 1);
77static_assert(alignof(verb_set) == 1);
78
79} // namespace routemon::http::core
diff --git a/server/src/http/core/server.cpp b/server/src/http/core/server.cpp
new file mode 100644
index 0000000..f204dfb
--- /dev/null
+++ b/server/src/http/core/server.cpp
@@ -0,0 +1,209 @@
1module;
2
3#include <boost/asio/as_tuple.hpp>
4#include <boost/asio/awaitable.hpp>
5#include <boost/asio/co_spawn.hpp>
6#include <boost/asio/ip/tcp.hpp>
7#include <boost/beast/core.hpp>
8#include <boost/beast/http.hpp>
9#include <boost/config.hpp>
10#include <boost/json/serialize.hpp>
11#include <boost/url.hpp>
12
13module routemon:http.core.server$impl;
14
15import :http.core.server;
16import :trace;
17
18namespace chrono = std::chrono;
19
20namespace routemon::http::core {
21
22auto presponse::header() -> bhttp::response_header<bhttp::fields>&
23{
24 return impl_->header();
25}
26
27auto presponse::header() const -> bhttp::response_header<bhttp::fields> const&
28{
29 return impl_->header();
30}
31
32auto presponse::is_done() const -> bool { return impl_->is_done(); }
33
34auto presponse::prepare(beast::error_code& ec) -> const_buffers_type
35{
36 return impl_->prepare(ec);
37}
38
39auto presponse::consume(std::size_t n) -> void { return impl_->consume(n); }
40
41auto presponse::keep_alive() const noexcept -> bool
42{
43 return impl_->keep_alive();
44}
45
46keep_alive::keep_alive(bool value) : value{value} {}
47
48auto problem_rsp(
49 base_ctx const& ctx, problem::details const& problem, keep_alive ka)
50 -> presponse
51{
52 auto rsp = make_rsp<bhttp::string_body>(problem.status, ka);
53 rsp.set(bhttp::field::content_type, "application/problem+json");
54 rsp.body() = json::serialize(json::value_from(problem, ctx.locale));
55 rsp.prepare_payload();
56 return presponse{std::move(rsp)};
57}
58
59auto make_preflight_rsp(preflight_response res, keep_alive ka)
60 -> bhttp::response<bhttp::empty_body>
61{
62 auto rsp = make_rsp<bhttp::empty_body>(bhttp::status::no_content, ka);
63 auto allow_headers_str = res.allow_headers
64 | std::views::transform(
65 [](auto const& field) -> std::string_view
66 { return bhttp::to_string(field); })
67 | std::views::join_with(std::string_view{", "})
68 | std::ranges::to<std::string>();
69 rsp.set(
70 bhttp::field::access_control_allow_methods,
71 res.allow_methods.to_string());
72 rsp.set(bhttp::field::access_control_allow_headers, allow_headers_str);
73 rsp.prepare_payload();
74 return rsp;
75}
76
77auto global_options_handler(base_ctx const& ctx, readable_request r)
78 -> net::awaitable<presponse>
79{
80 // TODO: switch to "small (4KB) discarded" body type, similar to what Go
81 // does? Same goes for default_options_handler? Not sure.
82 if (auto res = co_await read_empty_request(ctx, std::move(r)); !res)
83 co_return std::move(res.error());
84 auto req = r.p->release();
85 auto rsp = make_rsp<bhttp::empty_body>(
86 bhttp::status::no_content, keep_alive{req.keep_alive()});
87 rsp.prepare_payload();
88 co_return std::move(rsp);
89}
90
91auto router::handle_request(trace::id trace_id, readable_request r) const
92 -> net::awaitable<presponse>
93{
94 return impl_->handle_request(trace_id, r);
95}
96
97server::server(log::logger const& l, router&& r)
98 : l_{l.sub("http_server")}, r_{std::move(r)}
99{
100}
101
102auto server::do_session(beast::tcp_stream strm) -> net::awaitable<void>
103{
104 auto buf = beast::flat_buffer{};
105
106 while (true)
107 {
108 auto p0 = bhttp::request_parser<bhttp::empty_body>{};
109 p0.body_limit(boost::none);
110 auto [ec, _] =
111 co_await bhttp::async_read_header(strm, buf, p0, net::as_tuple);
112 if (ec == bhttp::error::end_of_stream)
113 break;
114 else if (ec)
115 throw boost::system::system_error{ec};
116
117 auto trace_id = trace::id{};
118 auto l = l_.sub("do_session").with("trace_id", trace_id.as_string());
119 l.debug("Read header, invoking request handler");
120 auto const before_hdl = chrono::steady_clock::now();
121
122 auto http_version = p0.get().version();
123 auto&& rsp = co_await r_.handle_request(
124 trace_id, readable_request{
125 .p = util::not_null{&p0},
126 .strm = util::not_null{&strm},
127 .buf = util::not_null{&buf},
128 });
129
130 l.debug(
131 "Request handler returned after {}, writing response",
132 chrono::duration<double, std::milli>{
133 chrono::steady_clock::now() - before_hdl
134 });
135 auto before_write_rsp = chrono::steady_clock::now();
136
137 rsp.header().version(http_version);
138 bool keep_alive = rsp.keep_alive();
139 co_await beast::async_write(strm, std::move(rsp));
140
141 l.debug(
142 "Wrote response in {}", chrono::duration<double, std::milli>{
143 chrono::steady_clock::now() - before_write_rsp
144 });
145
146 if (!keep_alive)
147 {
148 break;
149 }
150 }
151
152 strm.socket().shutdown(tcp::socket::shutdown_send);
153}
154
155auto server::do_listen(tcp::endpoint endpoint) -> net::awaitable<void>
156{
157 auto executor = co_await net::this_coro::executor;
158 auto acceptor = tcp::acceptor{executor, endpoint};
159
160 l_.with("endpoint", endpoint.address().to_string())
161 .with("port", std::to_string(endpoint.port()))
162 .info("Serving");
163 while (true)
164 {
165 net::co_spawn(
166 executor,
167 do_session(beast::tcp_stream{co_await acceptor.async_accept()}),
168 [this](std::exception_ptr e)
169 {
170 if (e)
171 {
172 try
173 {
174 std::rethrow_exception(e);
175 }
176 catch (std::exception const& e)
177 {
178 l_.error("Error in session: {}", e.what());
179 }
180 }
181 });
182 }
183}
184
185auto server::spawn(net::io_context& ioc) -> void
186{
187 auto const addr = net::ip::make_address("0.0.0.0");
188 auto const endpoint = tcp::endpoint{addr, 8284};
189
190 // TODO: make exception handling as nice as in srv.cpp
191 net::co_spawn(
192 ioc, do_listen(endpoint),
193 [this](std::exception_ptr e)
194 {
195 if (e)
196 {
197 try
198 {
199 std::rethrow_exception(e);
200 }
201 catch (std::exception const& e)
202 {
203 l_.error("Error: {}", e.what());
204 }
205 }
206 });
207}
208
209} // namespace routemon::http::core
diff --git a/server/src/http/core/server.cppm b/server/src/http/core/server.cppm
new file mode 100644
index 0000000..dbef975
--- /dev/null
+++ b/server/src/http/core/server.cppm
@@ -0,0 +1,799 @@
1module;
2
3#include <boost/asio/as_tuple.hpp>
4#include <boost/asio/awaitable.hpp>
5#include <boost/asio/co_spawn.hpp>
6#include <boost/asio/ip/tcp.hpp>
7#include <boost/beast/core.hpp>
8#include <boost/beast/http.hpp>
9#include <boost/config.hpp>
10#include <boost/json/serialize.hpp>
11#include <boost/url.hpp>
12
13export module routemon:http.core.server;
14
15import std;
16import :config;
17import :trace;
18import :http.core.common;
19import :problem;
20
21namespace net = boost::asio;
22using tcp = net::ip::tcp;
23
24namespace routemon::http::core {
25
26struct readable_request
27{
28 util::not_null<bhttp::request_parser<bhttp::empty_body>*> p;
29 util::not_null<beast::tcp_stream*> strm;
30 util::not_null<beast::flat_buffer*> buf;
31};
32
33class presponse
34{
35public:
36 using const_buffers_type = beast::span<net::const_buffer>;
37
38private:
39 struct impl_base
40 {
41 virtual ~impl_base() = default;
42 virtual auto header() -> bhttp::response_header<bhttp::fields>& = 0;
43 virtual auto header() const
44 -> bhttp::response_header<bhttp::fields> const& = 0;
45 virtual auto is_done() const -> bool = 0;
46 virtual auto prepare(beast::error_code&) -> const_buffers_type = 0;
47 virtual auto consume(std::size_t n) -> void = 0;
48 virtual auto keep_alive() const -> bool = 0;
49 };
50 std::unique_ptr<impl_base> impl_;
51
52 template <bhttp::concepts::body Body>
53 class impl : public impl_base
54 {
55 // Initializes in the response state.
56 // At the first call to prepare, we switch to the message generator
57 // state. After that point, header may not be called anymore (it will
58 // throw).
59 std::variant<bhttp::response<Body>, bhttp::message_generator> state_;
60
61 auto ensure_message_generator() -> bhttp::message_generator&
62 {
63 if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
64 {
65 auto rsp = bhttp::response<Body>{std::move(*prsp)};
66 state_.template emplace<bhttp::message_generator>(std::move(rsp));
67 }
68 return std::get<bhttp::message_generator>(state_);
69 }
70
71 public:
72 explicit impl(bhttp::response<Body>&& rsp) : state_{std::move(rsp)} {}
73
74 auto header() -> bhttp::response_header<bhttp::fields>& override
75 {
76 if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
77 {
78 return prsp->base();
79 }
80 else
81 {
82 // TODO: define custom exception type
83 // presponse::bad_header_access
84 throw std::logic_error{"header() may not be called after prepare()"};
85 }
86 }
87 auto header() const -> bhttp::response_header<bhttp::fields> const& override
88 {
89 if (auto prsp = std::get_if<bhttp::response<Body>>(&state_))
90 {
91 return prsp->base();
92 }
93 else
94 {
95 throw std::logic_error{"header() may not be called after prepare()"};
96 }
97 }
98
99 auto is_done() const -> bool override
100 {
101 if (auto pgen = std::get_if<bhttp::message_generator>(&state_))
102 {
103 return pgen->is_done();
104 }
105 else /* still in the response state */
106 {
107 return false;
108 }
109 }
110
111 auto prepare(beast::error_code& ec) -> const_buffers_type override
112 {
113 return ensure_message_generator().prepare(ec);
114 }
115
116 auto consume(std::size_t n) -> void override
117 {
118 ensure_message_generator().consume(n);
119 }
120
121 auto keep_alive() const noexcept -> bool override
122 {
123 return state_.visit(
124 util::overloaded{
125 [](bhttp::response<Body> const& rsp) -> bool
126 { return rsp.keep_alive(); },
127 [](bhttp::message_generator const& gen) -> bool
128 { return gen.keep_alive(); },
129 });
130 }
131 };
132
133public:
134 template <bhttp::concepts::body Body>
135 explicit presponse(bhttp::response<Body>&& rsp)
136 : impl_{new impl{std::move(rsp)}}
137 {
138 }
139
140 auto header() -> bhttp::response_header<bhttp::fields>&;
141 auto header() const -> bhttp::response_header<bhttp::fields> const&;
142 auto is_done() const -> bool;
143 auto prepare(beast::error_code& ec) -> const_buffers_type;
144 auto consume(std::size_t n) -> void;
145 auto keep_alive() const noexcept -> bool;
146};
147static_assert(beast::concepts::buffers_generator<presponse>);
148
149template <class Ctx>
150using next_handler_t = std::function<auto(Ctx)->net::awaitable<presponse>>;
151
152template <class OuterCtx, class InnerCtx>
153using middleware_t =
154 std::function<auto(
155 OuterCtx, bhttp::request_header<bhttp::fields>&,
156 next_handler_t<InnerCtx>)
157 ->net::awaitable<presponse>>;
158
159template <class Ctx>
160auto id_middleware(
161 Ctx ctx, bhttp::request_header<bhttp::fields>&, next_handler_t<Ctx> next)
162 -> net::awaitable<presponse>
163{
164 co_return co_await next(std::move(ctx));
165}
166
167struct base_ctx
168{
169 std::locale locale;
170 trace::id trace_id;
171};
172
173template <class Ctx>
174using basic_route_handler_fn_t =
175 std::function<auto(
176 Ctx, readable_request,
177 std::vector<std::string> const& matches)
178 ->net::awaitable<presponse>>;
179
180template <class Ctx>
181auto cors_middleware(std::vector<std::string> const& allow_origins)
182 -> middleware_t<Ctx, Ctx>
183{
184 if (allow_origins.empty())
185 return id_middleware<Ctx>;
186
187 auto header_str = allow_origins
188 | std::views::join_with(std::string_view{", "})
189 | std::ranges::to<std::string>();
190
191 return [header_str = std::move(header_str)](
192 Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr,
193 next_handler_t<Ctx> next) -> net::awaitable<presponse>
194 {
195 std::ignore = req_hdr;
196 auto prersp = co_await next(ctx);
197 prersp.header().set(bhttp::field::access_control_allow_origin, header_str);
198 co_return std::move(prersp);
199 };
200}
201
202template <class Ctx>
203auto expose_trace_id_middleware(
204 Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr,
205 next_handler_t<Ctx> next) -> net::awaitable<presponse>
206{
207 std::ignore = req_hdr;
208 auto prersp = co_await next(std::move(ctx));
209 prersp.header().set(
210 "X-Routemon-Trace-Id",
211 std::string_view{static_cast<base_ctx const&>(ctx).trace_id.as_string()});
212 prersp.header().insert(
213 bhttp::field::access_control_expose_headers, "X-Routemon-Trace-Id");
214 co_return std::move(prersp);
215}
216
217template <class Ctx>
218auto expose_content_language_middleware(
219 Ctx ctx, bhttp::request_header<bhttp::fields>& req_hdr,
220 next_handler_t<Ctx> next) -> net::awaitable<presponse>
221{
222 std::ignore = req_hdr;
223 auto prersp = co_await next(std::move(ctx));
224 if (prersp.header().find(bhttp::field::content_language)
225 == prersp.header().end()
226 && std::has_facet<locale::bcp47_tag>(ctx.locale))
227 {
228 prersp.header().set(
229 bhttp::field::content_language,
230 std::use_facet<locale::bcp47_tag>(ctx.locale).tag());
231 }
232 co_return std::move(prersp);
233}
234
235struct keep_alive
236{
237 bool value;
238
239 explicit keep_alive(bool value);
240};
241
242template <bhttp::concepts::body Body>
243auto make_rsp(bhttp::status status, keep_alive ka) -> bhttp::response<Body>
244{
245 auto rsp = bhttp::response<Body>{}; // HTTP version gets set later
246 rsp.result(status);
247 rsp.keep_alive(ka.value);
248 return rsp;
249}
250
251auto problem_rsp(
252 base_ctx const& ctx, problem::details const& problem, keep_alive ka)
253 -> presponse;
254
255struct preflight_response
256{
257 verb_set allow_methods;
258 std::vector<bhttp::field> allow_headers;
259};
260
261auto make_preflight_rsp(preflight_response res, keep_alive ka)
262 -> bhttp::response<bhttp::empty_body>;
263
264// Using base_ctx instead of a template here since that saves you
265// typing on invocation (and we do not care about the context type
266// anyway, but all context types should derive from base_ctx).
267template <bhttp::concepts::body_reader Body, typename... Args>
268auto read_request(base_ctx const& ctx, readable_request&& r, Args&&... args)
269 -> net::awaitable<bhttp::request<Body>>
270{
271 std::ignore = ctx;
272 auto p =
273 bhttp::request_parser<Body>{std::move(*r.p), std::forward<Args>(args)...};
274 co_await bhttp::async_read(*r.strm, *r.buf, p);
275 co_return std::move(p.release());
276}
277
278auto read_empty_request(base_ctx const& ctx, readable_request&& r) -> net::
279 awaitable<std::expected<bhttp::request<bhttp::empty_body>, presponse>>
280{
281 auto [ec, _] =
282 co_await bhttp::async_read(*r.strm, *r.buf, *r.p, net::as_tuple);
283 if (ec == bhttp::error::unexpected_body)
284 {
285 auto tpl = problem::tpl{
286 .status = bhttp::status::bad_request,
287 .title = translate("No body expected for this request"),
288 .type_uri = "https://routemon.fautchen.eu/problems/unexpected-body",
289 };
290 co_return std::unexpected{problem_rsp(
291 ctx, tpl.instantiate(), keep_alive{false})};
292 }
293 else if (ec)
294 {
295 throw boost::system::system_error{ec};
296 }
297 co_return r.p->release();
298}
299
300template <class InnerCtx>
301struct routed_ctx : InnerCtx
302{
303 verb_set route_methods;
304 boost::urls::url target;
305};
306
307template <class Ctx>
308 requires requires(Ctx ctx) {
309 // Ctx must be derived from an instantiation of routed_ctx
310 []<class InnerCtx>(routed_ctx<InnerCtx> const&) {}(ctx);
311 }
312auto default_options_handler(
313 Ctx const& ctx, readable_request r, std::vector<std::string> const&)
314 -> net::awaitable<presponse>
315{
316 auto mreq = co_await read_empty_request(ctx, std::move(r));
317 if (!mreq)
318 co_return std::move(mreq.error());
319
320 if (mreq->find(bhttp::field::access_control_request_method) != mreq->end())
321 {
322 // CORS preflight request
323 co_return make_preflight_rsp(
324 preflight_response{
325 // TODO: should access-control-allow-methods contain OPTIONS?
326 .allow_methods = ctx.route_methods,
327 .allow_headers =
328 {bhttp::field::content_type, bhttp::field::content_encoding},
329 },
330 keep_alive{mreq->keep_alive()});
331 }
332 else
333 {
334 // Normal OPTIONS request
335 auto rsp = make_rsp<bhttp::empty_body>(
336 bhttp::status::no_content, keep_alive{mreq->keep_alive()});
337 rsp.set(bhttp::field::allow, ctx.route_methods.to_string());
338 rsp.prepare_payload();
339 co_return std::move(rsp);
340 }
341}
342
343auto global_options_handler(base_ctx const& ctx, readable_request r)
344 -> net::awaitable<presponse>;
345
346template <class A, class B, class C>
347auto middleware_compose(middleware_t<A, B> ab, middleware_t<B, C> bc)
348 -> middleware_t<A, C>
349{
350 return [ab = std::move(ab), bc = std::move(bc)](
351 A a, bhttp::request_header<bhttp::fields>& header,
352 next_handler_t<C> next) -> net::awaitable<presponse>
353 {
354 co_return co_await ab(
355 std::move(a), header, [&](B b) -> net::awaitable<presponse>
356 { co_return co_await bc(std::move(b), header, next); });
357 };
358}
359
360template <class A, class B>
361auto middleware_wrap_fn(middleware_t<A, B> ab, basic_route_handler_fn_t<B> fn)
362 -> basic_route_handler_fn_t<A>
363{
364 return
365 [ab = std::move(ab), fn = std::move(fn)](
366 A a_ctx, readable_request r,
367 std::vector<std::string> const& matches) -> net::awaitable<presponse>
368 {
369 co_return co_await ab(
370 std::move(a_ctx), r.p->get().base(),
371 [&](B b_ctx) -> net::awaitable<presponse>
372 { co_return co_await fn(std::move(b_ctx), r, matches); });
373 };
374}
375
376template <std::default_initializable V>
377 requires requires(V v) {
378 { static_cast<bool>(v) };
379 }
380struct handler_map
381{
382 V options = {};
383 V delete_ = {};
384 V get = {};
385 V head = {};
386 V post = {};
387 V put = {};
388
389 template <class Self>
390 auto lookup(this Self&& self, supported_verb v) -> auto&&
391 {
392 switch (v.value)
393 {
394 case supported_verb::options:
395 return std::forward<Self>(self).options;
396 case supported_verb::delete_:
397 return std::forward<Self>(self).delete_;
398 case supported_verb::get:
399 return std::forward<Self>(self).get;
400 case supported_verb::head:
401 return std::forward<Self>(self).head;
402 case supported_verb::post:
403 return std::forward<Self>(self).post;
404 case supported_verb::put:
405 return std::forward<Self>(self).put;
406 }
407 }
408
409 auto verbs() const -> verb_set
410 {
411 return verb_set{
412 .options = static_cast<bool>(options),
413 .delete_ = static_cast<bool>(delete_),
414 .get = static_cast<bool>(get),
415 .head = static_cast<bool>(head),
416 .post = static_cast<bool>(post),
417 .put = static_cast<bool>(put),
418 };
419 }
420
421 auto empty() const -> bool { return verbs().empty(); }
422
423 template <std::default_initializable U>
424 auto map(std::invocable<V const&> auto f) const -> handler_map<U>
425 requires std::
426 assignable_from<U&, std::invoke_result_t<decltype(f), V const&>>
427 {
428 return {
429 .options = static_cast<bool>(options) ? f(options) : U{},
430 .delete_ = static_cast<bool>(delete_) ? f(delete_) : U{},
431 .get = static_cast<bool>(get) ? f(get) : U{},
432 .head = static_cast<bool>(head) ? f(head) : U{},
433 .post = static_cast<bool>(post) ? f(post) : U{},
434 .put = static_cast<bool>(put) ? f(put) : U{},
435 };
436 }
437};
438
439template <class Ctx>
440struct route_tree
441{
442 using leaves = handler_map<basic_route_handler_fn_t<Ctx>>;
443 using named_subtrees = std::unordered_map<std::string, route_tree>;
444 using wildcard_subtree = std::indirect<route_tree>;
445
446 leaves here;
447 // TODO: consider making the first alternative a radix tree
448 // Note: the map is the first variant here; the variant will be
449 // default-constructed with the default-constructed first
450 // alternative. The empty map denotes a lack of subtrees.
451 std::variant<named_subtrees, wildcard_subtree> sub;
452};
453
454template <class OuterCtx, class InnerCtx>
455auto middleware_wrap_tree(
456 middleware_t<OuterCtx, InnerCtx> mw, route_tree<InnerCtx> const& tree)
457 -> route_tree<OuterCtx>
458{
459 auto new_leaves = tree.here.template map<basic_route_handler_fn_t<OuterCtx>>(
460 std::bind_front(middleware_wrap_fn<OuterCtx, InnerCtx>, mw));
461 auto new_sub = tree.sub.visit(
462 util::overloaded{
463 [&mw](route_tree<InnerCtx>::named_subtrees const& subtrees)
464 -> decltype(route_tree<OuterCtx>::sub)
465 {
466 auto new_subtrees = typename route_tree<OuterCtx>::named_subtrees{};
467 for (auto [seg, subtree] : subtrees)
468 new_subtrees[seg] = middleware_wrap_tree(mw, subtree);
469 return new_subtrees;
470 },
471 [&mw](route_tree<InnerCtx>::wildcard_subtree const& subtree)
472 -> decltype(route_tree<OuterCtx>::sub)
473 {
474 return typename route_tree<OuterCtx>::wildcard_subtree{
475 middleware_wrap_tree(mw, *subtree)
476 };
477 },
478 });
479 return {.here = new_leaves, .sub = new_sub};
480}
481
482template <class T>
483concept match_arg = std::constructible_from<T, std::string const&>;
484
485template <class Ctx, match_arg... MatchArgs>
486using route_handler_fn_t =
487 std::function<auto(Ctx, readable_request, MatchArgs...)
488 ->net::awaitable<presponse>>;
489
490template <class Ctx, match_arg... MatchArgs>
491auto degen_route_handler(route_handler_fn_t<Ctx, MatchArgs...> fn)
492 -> basic_route_handler_fn_t<Ctx>
493{
494 return
495 [fn = std::move(fn)](
496 Ctx ctx, readable_request r,
497 std::vector<std::string> const& matches) -> net::awaitable<presponse>
498 {
499 if (sizeof...(MatchArgs) != matches.size())
500 throw std::runtime_error{"got unexpected amount of matches"};
501 auto it = matches.begin();
502 co_return co_await fn(
503 std::move(ctx), r,
504 MatchArgs{static_cast<std::string const&>(*it++)}...);
505 };
506}
507
508template <class Ctx, match_arg... MatchArgs>
509struct ctree : route_tree<Ctx>
510{
511 template <class OuterCtx>
512 auto wrap(middleware_t<OuterCtx, Ctx> mw) const
513 -> ctree<OuterCtx, MatchArgs...>
514 {
515 return {middleware_wrap_tree(std::move(mw), *this)};
516 }
517};
518
519template <class Ctx, match_arg... MatchArgs>
520struct dtree : handler_map<route_handler_fn_t<Ctx, MatchArgs...>>
521{
522 [[nodiscard]] auto to_leaves() const -> typename route_tree<Ctx>::leaves
523 {
524 auto here = this->template map<basic_route_handler_fn_t<Ctx>>(
525 degen_route_handler<Ctx, MatchArgs...>);
526 if (!here.verbs().empty() && !static_cast<bool>(this->options))
527 here.options = default_options_handler<Ctx>;
528 return here;
529 }
530
531 [[nodiscard]] auto named_subtrees(
532 std::initializer_list<std::pair<std::string, ctree<Ctx, MatchArgs...>>>
533 subtrees) const -> ctree<Ctx, MatchArgs...>
534 {
535 auto sub = typename route_tree<Ctx>::named_subtrees{
536 std::from_range, subtrees
537 | std::views::transform(
538 [](auto const& p)
539 {
540 return std::make_pair(
541 p.first,
542 static_cast<route_tree<Ctx>>(p.second));
543 })
544 };
545 return {route_tree<Ctx>{.here = to_leaves(), .sub = sub}};
546 }
547
548 template <match_arg MatchArg>
549 [[nodiscard]] auto
550 wildcard_subtree(ctree<Ctx, MatchArgs..., MatchArg> subtree)
551 -> ctree<Ctx, MatchArgs...>
552 {
553 return {route_tree<Ctx>{
554 .here = to_leaves(),
555 .sub = typename route_tree<Ctx>::wildcard_subtree{
556 static_cast<route_tree<Ctx>>(subtree)
557 }
558 }};
559 }
560
561 [[nodiscard]] auto no_subtrees() const -> ctree<Ctx, MatchArgs...>
562 {
563 return {route_tree<Ctx>{.here = to_leaves(), .sub = {}}};
564 }
565};
566
567class router
568{
569 struct impl_base
570 {
571 virtual ~impl_base() = default;
572 virtual auto handle_request(trace::id trace_id, readable_request r) const
573 -> net::awaitable<presponse> = 0;
574 };
575
576 std::unique_ptr<impl_base> impl_;
577
578 template <std::derived_from<base_ctx> PreRouteCtx>
579 class impl : public impl_base
580 {
581 log::logger l_;
582 locale::selector lsel_;
583 middleware_t<base_ctx, PreRouteCtx> global_middleware_;
584 route_tree<routed_ctx<PreRouteCtx>> routes_;
585
586 public:
587 explicit impl(
588 log::logger const& l, locale::selector&& lsel,
589 middleware_t<base_ctx, PreRouteCtx> global_middleware,
590 route_tree<routed_ctx<PreRouteCtx>> routes)
591 : l_{l.sub("router")}, lsel_{std::move(lsel)},
592 global_middleware_{std::move(global_middleware)},
593 routes_{std::move(routes)}
594 {
595 }
596
597 struct match_result
598 {
599 util::not_null<
600 handler_map<basic_route_handler_fn_t<routed_ctx<PreRouteCtx>>> const*
601 >
602 route_handlers;
603 std::vector<std::string> wildcard_matches;
604
605 auto allowed_methods() const -> verb_set
606 {
607 return route_handlers->verbs();
608 }
609 };
610
611 auto match(boost::urls::segments_view segments) const
612 -> std::optional<match_result>
613 {
614 auto const* tree = &routes_;
615 auto wildcard_matches = std::vector<std::string>{};
616 for (auto const& seg : segments)
617 {
618 tree->sub.visit(
619 util::overloaded{
620 [&](route_tree<routed_ctx<PreRouteCtx>>::named_subtrees const&
621 subtrees)
622 {
623 auto it = subtrees.find(seg);
624 tree = it == subtrees.end() ? nullptr : &it->second;
625 },
626 [&](route_tree<routed_ctx<PreRouteCtx>>::wildcard_subtree const&
627 wildcard_subtree)
628 {
629 wildcard_matches.push_back(seg);
630 tree = &*wildcard_subtree;
631 },
632 });
633 if (!tree)
634 return std::nullopt;
635 }
636 if (tree->here.empty())
637 return std::nullopt;
638 return match_result{
639 .route_handlers = util::not_null{&tree->here},
640 .wildcard_matches = wildcard_matches,
641 };
642 }
643
644 auto route_request(PreRouteCtx ctx, readable_request r) const
645 -> net::awaitable<presponse>
646 {
647 auto req_base = r.p->get().base();
648
649 auto const bad_request_tpl = problem::tpl{
650 .status = bhttp::status::bad_request,
651 .title = translate("Bad request"),
652 .type_uri = "https://routemon.fautchen.eu/problems/bad-request",
653 };
654
655 if (req_base.target() == "*")
656 {
657 // request-target is in asterisk-form (RFC 9112, § 3.2.4),
658 // so the request must be a server-wide OPTIONS request.
659
660 if (req_base.method() != bhttp::verb::options)
661 {
662 auto tpl = problem::tpl{
663 .status = bhttp::status::method_not_allowed,
664 .title = translate("Method not allowed"),
665 .type_uri = "https://routemon.fautchen.eu/problems/"
666 "method-not-allowed",
667 };
668 co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
669 }
670
671 co_return co_await global_options_handler(ctx, r);
672 }
673 else if (auto mreq_url0 =
674 boost::urls::parse_origin_form(req_base.target()))
675 {
676 // request-target is in origin-form (RFC 9112, § 3.2.1),
677 // so it must be a normal request (not a CONNECT or
678 // server-wide OPTIONS request).
679
680 auto req_url = boost::urls::url{*mreq_url0};
681 req_url.normalize();
682 if (!req_url.is_path_absolute())
683 {
684 auto problem = bad_request_tpl.instantiate().set_detail(translate(
685 "Path of normalized (RFC 3986, § 6) "
686 "origin-form request-target (RFC "
687 "9112, § 3.2.1) should be "
688 "absolute"));
689 co_return problem_rsp(ctx, problem, keep_alive{false});
690 }
691
692 // l_.with(
693 // "trace_id",
694 // static_cast<base_ctx const&>(ctx).trace_id.as_string())
695 // .debug(
696 // "Request targets {} {}", req_base.method_string(),
697 // req_url.path());
698
699 auto mres = match(req_url.segments());
700 if (!mres)
701 {
702 auto tpl = problem::tpl{
703 .status = bhttp::status::not_found,
704 .title = translate("Not found"),
705 .type_uri = "https://routemon.fautchen.eu/problems/not-found",
706 };
707 co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
708 }
709
710 auto mverb = supported_verb::from(req_base.method());
711 if (!mverb)
712 {
713 // Method not implemented.
714 auto tpl = problem::tpl{
715 .status = bhttp::status::not_implemented,
716 .title = translate("Method not implemented"),
717 .type_uri = "https://routemon.fautchen.eu/problems/"
718 "method-not-implemented",
719 };
720 co_return problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
721 }
722
723 if (auto mhdl = mres->route_handlers->lookup(*mverb))
724 {
725 auto new_ctx = routed_ctx<PreRouteCtx>{
726 std::move(ctx), mres->allowed_methods(), std::move(req_url)
727 };
728 co_return co_await mhdl(
729 std::move(new_ctx), r, mres->wildcard_matches);
730 }
731 else
732 {
733 // Path recognized, but method not allowed.
734 auto tpl = problem::tpl{
735 .status = bhttp::status::method_not_allowed,
736 .title = translate("Method not allowed"),
737 .type_uri = "https://routemon.fautchen.eu/problems/"
738 "method-not-allowed",
739 };
740 auto rsp = problem_rsp(ctx, tpl.instantiate(), keep_alive{false});
741 rsp.header().set(
742 bhttp::field::allow, mres->allowed_methods().to_string());
743 co_return std::move(rsp);
744 }
745 }
746 else
747 {
748 // We do not accept any other request-target forms.
749
750 auto problem = bad_request_tpl.instantiate().set_detail(translate(
751 "Invalid request-target, expected "
752 "asterisk-form or origin-form "
753 "(see RFC 9112, § 3.2)"));
754 co_return problem_rsp(ctx, problem, keep_alive{false});
755 }
756 }
757
758 auto handle_request(trace::id trace_id, readable_request r) const
759 -> net::awaitable<presponse> override
760 {
761 auto header = r.p->get().base();
762 auto locale = lsel_.select(header[bhttp::field::accept_language]);
763 co_return co_await global_middleware_(
764 base_ctx{.locale = locale, .trace_id = trace_id}, header,
765 [&](PreRouteCtx ctx) -> net::awaitable<presponse>
766 { co_return co_await route_request(std::move(ctx), std::move(r)); });
767 }
768 };
769
770public:
771 template <std::derived_from<base_ctx> PreRouteCtx>
772 explicit router(
773 log::logger const& l, locale::selector&& lsel,
774 middleware_t<base_ctx, PreRouteCtx> global_middleware,
775 route_tree<routed_ctx<PreRouteCtx>> routes)
776 : impl_{std::make_unique<impl<PreRouteCtx>>(
777 l, std::move(lsel), std::move(global_middleware), std::move(routes))}
778 {
779 }
780
781 auto handle_request(trace::id trace_id, readable_request r) const
782 -> net::awaitable<presponse>;
783};
784
785class server
786{
787 log::logger l_;
788 router r_;
789
790 auto do_session(beast::tcp_stream strm) -> net::awaitable<void>;
791 auto do_listen(tcp::endpoint endpoint) -> net::awaitable<void>;
792
793public:
794 explicit server(log::logger const& l, router&& r);
795
796 auto spawn(net::io_context& ioc) -> void;
797};
798
799} // namespace routemon::http::core
diff --git a/server/src/http/ext/gpx.cpp b/server/src/http/ext/gpx.cpp
new file mode 100644
index 0000000..c1f565f
--- /dev/null
+++ b/server/src/http/ext/gpx.cpp
@@ -0,0 +1,139 @@
1module;
2
3#include <boost/beast/core.hpp>
4
5module routemon:http.ext.gpx$impl;
6
7import :http.ext.gpx;
8
9namespace chrono = std::chrono;
10
11namespace routemon::http::ext::gpx {
12
13auto parse_error_category_impl::name() const noexcept -> char const*
14{
15 return "gpx_parse";
16}
17
18auto parse_error_category_impl::message(int condition) const noexcept
19 -> std::string
20{
21 std::ignore = condition;
22 return "failed to parse GPX file";
23}
24
25auto parse_error_category() noexcept -> parse_error_category_impl const&
26{
27 static auto const inst = parse_error_category_impl{};
28 return inst;
29}
30
31auto parse_error() noexcept -> std::error_code
32{
33 return std::error_code{1, parse_error_category()};
34}
35
36auto parse_result::set_exception(std::exception_ptr ex) noexcept -> void
37{
38 res_ = ex;
39}
40
41auto parse_result::set_gpx_file(routemon::gpx::file&& f) noexcept -> void
42{
43 res_ = std::move(f);
44}
45
46auto parse_result::init_parse_duration(
47 chrono::steady_clock::duration dur) noexcept -> void
48{
49 init_parse_dur_ = dur;
50}
51
52[[nodiscard]] auto parse_result::init_parse_duration() const noexcept
53 -> chrono::steady_clock::duration
54{
55 return init_parse_dur_;
56}
57
58auto parse_result::put_parse_duration(
59 chrono::steady_clock::duration dur) noexcept -> void
60{
61 put_parse_dur_ = dur;
62}
63
64[[nodiscard]] auto parse_result::put_parse_duration() const noexcept
65 -> chrono::steady_clock::duration
66{
67 return put_parse_dur_;
68}
69
70auto parse_result::finish_parse_duration(
71 chrono::steady_clock::duration dur) noexcept -> void
72{
73 finish_parse_dur_ = dur;
74}
75
76[[nodiscard]] auto parse_result::finish_parse_duration() const noexcept
77 -> chrono::steady_clock::duration
78{
79 return finish_parse_dur_;
80}
81
82auto parse_result::unwrap() -> routemon::gpx::file&&
83{
84 return std::visit(
85 util::overloaded{
86 [](std::exception_ptr ex) -> routemon::gpx::file&&
87 {
88 if (ex)
89 std::rethrow_exception(ex);
90 else
91 throw std::runtime_error{"no GPX file parse result available"};
92 },
93 [](routemon::gpx::file&& f) -> routemon::gpx::file&&
94 { return std::move(f); },
95 },
96 std::move(res_));
97}
98
99auto body::reader::init(
100 boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
101 -> void
102{
103 auto const init_start = chrono::steady_clock::now();
104 try
105 {
106 r_.init();
107 ec = {};
108 }
109 catch (std::exception& ex)
110 {
111 res_->set_exception(std::current_exception());
112 ec = parse_error();
113 }
114 res_->init_parse_duration(chrono::steady_clock::now() - init_start);
115}
116
117auto body::reader::finish(beast::error_code& ec) noexcept -> void
118{
119 auto const finish_start = chrono::steady_clock::now();
120 try
121 {
122 if (buf_.size() > 0)
123 {
124 r_.put(std::string_view{buf_});
125 buf_.clear();
126 }
127
128 res_->set_gpx_file(r_.finish());
129 ec = {};
130 }
131 catch (std::exception& ex)
132 {
133 res_->set_exception(std::current_exception());
134 ec = parse_error();
135 }
136 res_->finish_parse_duration(chrono::steady_clock::now() - finish_start);
137}
138
139} // namespace routemon::http::ext::gpx
diff --git a/server/src/http/ext/gpx.cppm b/server/src/http/ext/gpx.cppm
new file mode 100644
index 0000000..69763d8
--- /dev/null
+++ b/server/src/http/ext/gpx.cppm
@@ -0,0 +1,128 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5
6export module routemon:http.ext.gpx;
7
8import std;
9import :gpx;
10import :http.core.common;
11
12namespace chrono = std::chrono;
13
14namespace routemon::http::ext::gpx {
15
16class parse_error_category_impl : public std::error_category
17{
18public:
19 auto name() const noexcept -> char const* override;
20 auto message(int condition) const noexcept -> std::string override;
21};
22
23auto parse_error_category() noexcept -> parse_error_category_impl const&;
24
25auto parse_error() noexcept -> std::error_code;
26
27class parse_result
28{
29 chrono::steady_clock::duration init_parse_dur_;
30 chrono::steady_clock::duration put_parse_dur_;
31 chrono::steady_clock::duration finish_parse_dur_;
32 std::variant<std::exception_ptr, routemon::gpx::file> res_;
33
34public:
35 auto set_exception(std::exception_ptr ex) noexcept -> void;
36 auto set_gpx_file(routemon::gpx::file&& f) noexcept -> void;
37
38 auto init_parse_duration(chrono::steady_clock::duration dur) noexcept -> void;
39 [[nodiscard]] auto init_parse_duration() const noexcept
40 -> chrono::steady_clock::duration;
41 auto put_parse_duration(chrono::steady_clock::duration dur) noexcept -> void;
42 [[nodiscard]] auto put_parse_duration() const noexcept
43 -> chrono::steady_clock::duration;
44 auto finish_parse_duration(chrono::steady_clock::duration dur) noexcept
45 -> void;
46 [[nodiscard]] auto finish_parse_duration() const noexcept
47 -> chrono::steady_clock::duration;
48
49 auto unwrap() -> routemon::gpx::file&&;
50};
51
52struct body
53{
54 using value_type = parse_result;
55
56 class reader
57 {
58 routemon::gpx::reader r_;
59 util::not_null<value_type*> res_;
60 std::inplace_vector<char, 4096> buf_;
61
62 public:
63 template <bool isRequest, bhttp::concepts::fields Fields>
64 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v) : res_{&v}
65 {
66 res_->init_parse_duration({});
67 res_->put_parse_duration({});
68 res_->finish_parse_duration({});
69 }
70
71 // The following methods (which are called by Beast) are marked
72 // noexcept, since Beast does not ensure that exceptions thrown
73 // here are appropriately directed to the caller of
74 // (async_)read(_some), so throwing here might cause the program
75 // to crash.
76
77 auto
78 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
79 -> void;
80
81 auto
82 put(beast::concepts::const_buffer_sequence auto b,
83 beast::error_code& ec) noexcept -> std::size_t
84 {
85 auto const put_start = chrono::steady_clock::now();
86 auto total = 0uz;
87 try
88 {
89 for (auto cur_in_buf : beast::buffers_range(b))
90 {
91 while (cur_in_buf.size() > 0)
92 {
93 auto to_read =
94 std::min(cur_in_buf.size(), buf_.max_size() - buf_.size());
95 buf_.append_range(
96 std::span{
97 static_cast<char const*>(cur_in_buf.data()), to_read
98 });
99 cur_in_buf += to_read;
100 total += to_read;
101
102 if (buf_.size() == buf_.max_size())
103 {
104 r_.put(std::string_view{buf_});
105 buf_.clear();
106 }
107 }
108 }
109 ec = {};
110 }
111 catch (std::exception& ex)
112 {
113 res_->set_exception(std::current_exception());
114 ec = parse_error();
115 }
116 res_->put_parse_duration(
117 res_->put_parse_duration()
118 + (chrono::steady_clock::now() - put_start));
119 return total;
120 }
121
122 auto finish(beast::error_code& ec) noexcept -> void;
123 };
124};
125static_assert(bhttp::concepts::body<body>);
126static_assert(bhttp::concepts::body_reader<body>);
127
128} // namespace routemon::http::ext::gpx
diff --git a/server/src/http/ext/hmac_openssl.cppm b/server/src/http/ext/hmac_openssl.cppm
index 52ccb86..b196094 100644
--- a/server/src/http/ext/hmac_openssl.cppm
+++ b/server/src/http/ext/hmac_openssl.cppm
@@ -1,10 +1,179 @@
1module; 1module;
2 2
3#include <boost/asio/ssl/error.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6
3#include <openssl/evp.h> 7#include <openssl/evp.h>
4#include <openssl/params.h> 8#include <openssl/params.h>
5 9
6export module routemon:hmac_openssl; 10export module routemon:http.ext.hmac_openssl;
11
12import std;
13import :http.core.common;
14import :util;
15
16namespace {
7 17
8namespace routemon::hmac_openssl { 18namespace net = boost::asio;
9 19
10} 20}
21
22namespace routemon::http::ext::hmac_openssl {
23
24// TODO: constrain T? What are appropriate constraints?
25template <typename T>
26class readable
27{
28 std::string_view key_;
29 std::optional<std::array<std::uint8_t, 32>> mac_;
30 T res_;
31
32 template <bhttp::concepts::body_reader Sub>
33 friend struct body_reader;
34
35public:
36 template <typename... Args>
37 explicit readable(std::string_view key, Args&&... args)
38 : key_{key}, res_{std::forward<Args>(args)...}
39 {
40 }
41
42 template <typename Self>
43 constexpr auto get(this Self&& self) -> auto&&
44 {
45 return std::forward<Self>(self).res_;
46 }
47
48 auto mac() const -> std::optional<std::array<std::uint8_t, 32>>
49 {
50 return mac_;
51 }
52};
53
54template <bhttp::concepts::body_reader Sub>
55class body_reader
56{
57 EVP_MAC* mac_ = nullptr;
58 EVP_MAC_CTX* ctx_ = nullptr;
59
60 util::not_null<readable<typename Sub::value_type>*> v_;
61 Sub::reader subr_;
62 beast::error_code ec_;
63
64public:
65 template <bool isRequest, bhttp::concepts::fields Fields>
66 explicit body_reader(
67 bhttp::header<isRequest, Fields>& h,
68 readable<typename Sub::value_type>& v)
69 : v_{util::not_null{&v}},
70 subr_{h, v.get()} // we are not supposed to use v yet, but this just
71 // computes an address, so it should be fine
72 {
73 }
74
75 ~body_reader()
76 {
77 ::EVP_MAC_CTX_free(ctx_);
78 ::EVP_MAC_free(mac_);
79 }
80
81 // TODO: move to impl. unit.
82 auto init(boost::optional<std::uint64_t> n, beast::error_code& ec) noexcept
83 -> void
84 {
85 // https://docs.openssl.org/master/man3/EVP_MAC/#examples
86 mac_ = ::EVP_MAC_fetch(nullptr, "HMAC", nullptr);
87 if (!mac_)
88 {
89 ec_ = ec = make_error_code(std::errc::not_enough_memory);
90 return;
91 }
92
93 ctx_ = ::EVP_MAC_CTX_new(mac_);
94 if (!ctx_)
95 {
96 ec_ = ec = make_error_code(std::errc::not_enough_memory);
97 return;
98 }
99
100 char sha256[] = "SHA256";
101 ::OSSL_PARAM const params[] = {
102 OSSL_PARAM_utf8_string("digest", sha256, sizeof(sha256) - 1),
103 OSSL_PARAM_END
104 };
105 if (!::EVP_MAC_init(
106 ctx_, reinterpret_cast<unsigned char const*>(v_->key_.data()),
107 v_->key_.size(), params))
108 {
109 ec_ = ec = beast::error_code{
110 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
111 };
112 return;
113 }
114
115 subr_.init(n, ec);
116 }
117
118 auto
119 put(beast::concepts::const_buffer_sequence auto b,
120 beast::error_code& ec) noexcept -> std::size_t
121 {
122 if ((ec = ec_))
123 return 0uz;
124
125 auto const total_read = subr_.put(b, ec);
126 if (total_read > 0)
127 {
128 auto remaining = total_read;
129 for (auto const buf : beast::buffers_range(b))
130 {
131 auto const to_hash_from_this_buf = std::min(remaining, buf.size());
132 if (!::EVP_MAC_update(
133 ctx_, static_cast<unsigned char const*>(buf.data()),
134 to_hash_from_this_buf))
135 {
136 ec_ = ec = beast::error_code{
137 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
138 };
139 return total_read;
140 }
141 remaining -= to_hash_from_this_buf;
142 }
143 }
144 return total_read;
145 }
146
147 auto finish(beast::error_code& ec) noexcept -> void
148 {
149 auto got_mac_len = 0uz;
150 auto got_mac = std::array<std::uint8_t, 32>{};
151 if (!::EVP_MAC_final(ctx_, got_mac.data(), &got_mac_len, got_mac.size()))
152 {
153 ec = beast::error_code{
154 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
155 };
156 return;
157 }
158 assert(got_mac_len == got_mac.size());
159 v_->mac_ = got_mac;
160 subr_.finish(ec);
161 }
162};
163
164template <bhttp::concepts::body Sub>
165struct body
166{
167 using value_type = readable<typename Sub::value_type>;
168};
169
170template <bhttp::concepts::body Sub>
171 requires bhttp::concepts::body_reader<Sub>
172struct body<Sub>
173{
174 using value_type = readable<typename Sub::value_type>;
175
176 using reader = body_reader<Sub>;
177};
178
179} // namespace routemon::http::ext::hmac_openssl
diff --git a/server/src/http/ext/json.cpp b/server/src/http/ext/json.cpp
new file mode 100644
index 0000000..f03d336
--- /dev/null
+++ b/server/src/http/ext/json.cpp
@@ -0,0 +1,34 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/json/stream_parser.hpp>
5
6module routemon:http.ext.json$impl;
7
8import :http.ext.json;
9
10namespace routemon::http::ext::json {
11
12namespace {
13
14namespace json = boost::json;
15
16} // namespace
17
18auto body::reader::init(
19 boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
20 -> void
21{
22 p_.reset();
23 ec = {};
24}
25
26auto body::reader::finish(beast::error_code& ec) noexcept -> void
27{
28 p_.finish(ec);
29 if (ec)
30 return;
31 *v_ = p_.release();
32}
33
34} // namespace routemon::http::ext::json
diff --git a/server/src/http/ext/json.cppm b/server/src/http/ext/json.cppm
index e69de29..4097253 100644
--- a/server/src/http/ext/json.cppm
+++ b/server/src/http/ext/json.cppm
@@ -0,0 +1,65 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5#include <boost/json/stream_parser.hpp>
6
7export module routemon:http.ext.json;
8
9import std;
10import :http.core.common;
11import :util;
12
13namespace routemon::http::ext::json {
14
15namespace {
16
17namespace json = boost::json;
18
19} // namespace
20
21struct body
22{
23 using value_type = json::value;
24
25 class reader
26 {
27 json::stream_parser p_;
28 util::not_null<value_type*> v_;
29
30 public:
31 template <bool isRequest, bhttp::concepts::fields Fields>
32 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v)
33 : v_{util::not_null{&v}}
34 {
35 }
36
37 auto
38 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
39 -> void;
40
41 auto
42 put(beast::concepts::const_buffer_sequence auto b,
43 beast::error_code& ec) noexcept -> std::size_t
44 {
45 ec = {};
46
47 auto wrote = 0uz;
48 for (auto const buf : beast::buffers_range(b))
49 {
50 p_.write(static_cast<char const*>(buf.data()), buf.size(), ec);
51 wrote += buf.size();
52 if (ec)
53 break;
54 }
55 return wrote;
56 }
57
58 auto finish(beast::error_code& ec) noexcept -> void;
59 };
60};
61
62static_assert(bhttp::concepts::body<body>);
63static_assert(bhttp::concepts::body_reader<body>);
64
65} // namespace routemon::http::ext::json
diff --git a/server/src/http/ext/raw_deflate.cppm b/server/src/http/ext/raw_deflate.cppm
new file mode 100644
index 0000000..ee7da2f
--- /dev/null
+++ b/server/src/http/ext/raw_deflate.cppm
@@ -0,0 +1,134 @@
1module;
2
3#include <boost/asio/buffer.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <boost/beast/zlib.hpp>
7
8export module routemon:http.ext.raw_deflate;
9
10import :http.core.common;
11
12namespace routemon::http::ext::raw_deflate {
13
14namespace {
15
16namespace net = boost::asio;
17
18}
19
20template <bhttp::concepts::body_reader Inner>
21struct body
22{
23 using value_type = Inner::value_type;
24
25 class reader
26 {
27 static constexpr auto const chunk_size = 16384;
28
29 Inner::reader r_;
30 bool stream_ended_ = false;
31 beast::zlib::z_params zs_ = {};
32 beast::zlib::inflate_stream inflate_strm_ = {};
33 std::unique_ptr<std::array<char, chunk_size>> in_buf_ = nullptr;
34 std::unique_ptr<std::array<char, chunk_size>> out_buf_ = nullptr;
35
36 auto inflate_chunk(beast::error_code& ec) -> void
37 {
38 assert(zs_.avail_in > 0);
39 zs_.next_in = in_buf_->data();
40
41 do
42 {
43 zs_.avail_out = out_buf_->size();
44 zs_.next_out = out_buf_->data();
45
46 inflate_strm_.write(zs_, beast::zlib::Flush::none, ec);
47 assert(ec != beast::zlib::error::stream_error);
48 if (ec == beast::zlib::error::need_buffers)
49 ec = {};
50 if (ec == beast::zlib::error::end_of_stream)
51 {
52 ec = {};
53 stream_ended_ = true;
54 }
55 if (ec)
56 break;
57
58 auto have = chunk_size - zs_.avail_out;
59 auto cbuf =
60 net::buffer(static_cast<void const*>(out_buf_->data()), have);
61
62 auto inner_ec = beast::error_code{};
63 do
64 cbuf += r_.put(cbuf, inner_ec);
65 while (cbuf.size() > 0 && !inner_ec);
66 if (inner_ec)
67 {
68 ec = inner_ec;
69 break;
70 }
71 }
72 while (zs_.avail_out == 0);
73
74 // In the last case (stream_ended_), the user has sent too much data
75 assert(zs_.avail_in == 0 || ec || stream_ended_);
76 }
77
78 public:
79 template <bool isRequest, bhttp::concepts::fields Fields>
80 explicit reader(bhttp::header<isRequest, Fields>& hdr, value_type& v)
81 : r_{hdr, v}
82 {
83 }
84
85 auto
86 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
87 -> void
88 {
89 in_buf_.reset(new std::array<char, chunk_size>{});
90 out_buf_.reset(new std::array<char, chunk_size>{});
91 ec = {};
92 }
93
94 auto
95 put(beast::concepts::const_buffer_sequence auto b,
96 beast::error_code& ec) noexcept -> std::size_t
97 {
98 auto in_buf = net::buffer(in_buf_->data(), in_buf_->size());
99 in_buf += zs_.avail_in;
100
101 auto consumed_from_b = net::buffer_copy(in_buf, b);
102 zs_.avail_in += consumed_from_b;
103
104 if (zs_.avail_in == in_buf_->size())
105 inflate_chunk(ec);
106 else
107 ec = {};
108
109 return consumed_from_b;
110 }
111
112 auto finish(beast::error_code& ec) noexcept -> void
113 {
114 ec = {};
115 if (zs_.avail_in > 0)
116 inflate_chunk(ec);
117 if (!ec && !stream_ended_)
118 ec = beast::zlib::error::stream_error;
119 if (stream_ended_ && zs_.avail_in > 0)
120 // client sent data past deflate stream end
121 ec = beast::zlib::error::stream_error;
122
123 in_buf_.reset();
124 out_buf_.reset();
125 inflate_strm_.reset();
126 if (!ec)
127 {
128 r_.finish(ec);
129 }
130 }
131 };
132};
133
134} // namespace routemon::http::ext::raw_deflate
diff --git a/server/src/http/handler.cpp b/server/src/http/handler.cpp
new file mode 100644
index 0000000..d755c16
--- /dev/null
+++ b/server/src/http/handler.cpp
@@ -0,0 +1,348 @@
1module;
2
3#include <boost/asio/awaitable.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <boost/config.hpp>
7#include <boost/json.hpp>
8
9#include <openssl/crypto.h>
10
11module routemon:http.handler$impl;
12
13import std;
14import :gpx;
15import :http.server;
16import :http.ext.gpx;
17import :http.ext.hmac_openssl;
18import :http.ext.json;
19import :http.ext.raw_deflate;
20
21namespace beast = boost::beast;
22namespace json = boost::json;
23namespace net = boost::asio;
24
25namespace routemon::http {
26
27auto parse_timestamp_mins(std::string_view in)
28 -> std::optional<time::timestamp<std::chrono::minutes>>
29{
30 auto res = time::timestamp<std::chrono::minutes>{};
31 auto is = std::istringstream{in};
32 is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res);
33 return is.fail() ? std::nullopt : std::make_optional(res);
34}
35
36auto parse_timestamp_secs(std::string_view in)
37 -> std::optional<time::timestamp<std::chrono::seconds>>
38{
39 auto res = time::timestamp<std::chrono::seconds>{};
40 auto is = std::istringstream{in};
41 is >> std::chrono::parse("%FT%TZ", res);
42 return is.fail() ? std::nullopt : std::make_optional(res);
43}
44
45auto handler::handle_process_gpx(l0_ctx ctx, core::readable_request r)
46 -> net::awaitable<core::presponse>
47{
48 auto l =
49 l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string());
50
51 auto cp_begin = time::timestamp<std::chrono::minutes>{};
52 auto cp_end = time::timestamp<std::chrono::minutes>{};
53
54 auto const params = ctx.target.params();
55 if (auto it = params.find("cpbegin"); it != params.end())
56 {
57 auto mts = parse_timestamp_mins((*it).value);
58 if (!mts)
59 {
60 auto tpl = problem::tpl{
61 .status = bhttp::status::bad_request,
62 .title = translate("Query parameter has bad value"),
63 .type_uri =
64 "https://routemon.fautchen.eu/problems/query-param-bad-value",
65 };
66 co_return core::problem_rsp(
67 ctx, tpl.instantiate(), core::keep_alive{false});
68 }
69 cp_begin = *mts;
70
71 ++it;
72 if (it != params.end() && (*it).key == "cpbegin")
73 {
74 auto tpl = problem::tpl{
75 .status = bhttp::status::bad_request,
76 .title = translate("Query parameter provided too many times"),
77 .type_uri = "https://routemon.fautchen.eu/problems/"
78 "query-param-too-many-occurrences",
79 };
80 co_return core::problem_rsp(
81 ctx, tpl.instantiate(), core::keep_alive{false});
82 }
83 }
84 else
85 {
86 auto tpl = problem::tpl{
87 .status = bhttp::status::bad_request,
88 .title = translate("Required query parameter not provided"),
89 .type_uri = "https://routemon.fautchen.eu/problems/"
90 "required-query-param-not-provided",
91 };
92 co_return core::problem_rsp(
93 ctx, tpl.instantiate(), core::keep_alive{false});
94 }
95 if (auto it = params.find("cpend"); it != params.end())
96 {
97 auto mts = parse_timestamp_mins((*it).value);
98 if (!mts)
99 {
100 auto tpl = problem::tpl{
101 .status = bhttp::status::bad_request,
102 .title = translate("Query parameter has bad value"),
103 .type_uri =
104 "https://routemon.fautchen.eu/problems/query-param-bad-value",
105 };
106 co_return core::problem_rsp(
107 ctx, tpl.instantiate(), core::keep_alive{false});
108 }
109 cp_end = *mts;
110
111 ++it;
112 if (it != params.end() && (*it).key == "cpend")
113 {
114 auto tpl = problem::tpl{
115 .status = bhttp::status::bad_request,
116 .title = translate("Query parameter provided too many times"),
117 .type_uri = "https://routemon.fautchen.eu/problems/"
118 "query-param-too-many-occurrences",
119 };
120 co_return core::problem_rsp(
121 ctx, tpl.instantiate(), core::keep_alive{false});
122 }
123 }
124 else
125 {
126 auto tpl = problem::tpl{
127 .status = bhttp::status::bad_request,
128 .title = translate("Required query parameter not provided"),
129 .type_uri = "https://routemon.fautchen.eu/problems/"
130 "required-query-param-not-provided",
131 };
132 co_return core::problem_rsp(
133 ctx, tpl.instantiate(), core::keep_alive{false});
134 }
135
136 if (cp_begin >= cp_end)
137 {
138 auto tpl = problem::tpl{
139 .status = bhttp::status::bad_request,
140 .title = translate("Invalid check period provided"),
141 .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period",
142 };
143 co_return core::problem_rsp(
144 ctx,
145 tpl.instantiate().set_detail(translate(
146 "Begin of check period must be before end of check period")),
147 core::keep_alive{false});
148 }
149 auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end};
150
151 auto gpx_file = gpx::file{};
152 try
153 {
154 l.debug("Reading GPX request body");
155 auto const before_read_gpx = chrono::steady_clock::now();
156 auto parse_res =
157 r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw"
158 ? std::move((co_await core::read_request<
159 ext::raw_deflate::body<ext::gpx::body>
160 >(ctx, std::move(r)))
161 .body())
162 : std::move((co_await core::read_request<ext::gpx::body>(
163 ctx, std::move(r)))
164 .body());
165 l.debug(
166 "Read GPX request body in {}; init took {}, actual parsing {}, "
167 "finishing {}",
168 chrono::duration<double, std::milli>{
169 chrono::steady_clock::now() - before_read_gpx
170 },
171 chrono::duration<double, std::milli>{parse_res.init_parse_duration()},
172 chrono::duration<double, std::milli>{parse_res.put_parse_duration()},
173 chrono::duration<double, std::milli>{
174 parse_res.finish_parse_duration()
175 });
176 gpx_file = std::move(parse_res.unwrap());
177 }
178 catch (std::exception& ex)
179 {
180 l_.warn("Failed to parse GPX file: {}", ex.what());
181 // TODO: more detailed problem reporting
182 auto tpl = problem::tpl{
183 .status = bhttp::status::bad_request,
184 .title = translate("Failed to parse GPX file"),
185 .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed",
186 };
187 co_return core::problem_rsp(
188 ctx, tpl.instantiate(), core::keep_alive{false});
189 }
190
191 // TODO: catch handler exceptions and return 500 when raised?
192 // (keep-alive depends on whether whole request was read)
193 auto mres = inner_.process_gpx(
194 ctx.trace_id, std::move(gpx_file),
195 time::period_seq<std::chrono::minutes>{cp});
196 if (!mres)
197 {
198 auto tpl = problem::tpl{
199 .status = bhttp::status::internal_server_error,
200 .title = translate("Internal server error"),
201 .type_uri = "https://routemon.fautchen.eu/problems/"
202 "internal-server-error",
203 };
204 co_return core::problem_rsp(ctx, tpl.instantiate(), core::keep_alive{true});
205 }
206
207 auto rsp = core::make_rsp<bhttp::string_body>(
208 bhttp::status::ok, core::keep_alive{true});
209 rsp.set(bhttp::field::content_type, "application/json");
210 rsp.body() = json::serialize(json::value_from(*mres));
211 rsp.prepare_payload();
212 co_return rsp;
213}
214
215auto handler::handle_sysinfo(l0_ctx ctx, core::readable_request r)
216 -> net::awaitable<core::presponse>
217{
218 auto req = co_await core::read_empty_request(ctx, std::move(r));
219 auto info = inner_.sysinfo();
220
221 auto rsp = core::make_rsp<bhttp::string_body>(
222 bhttp::status::ok, core::keep_alive{true});
223 rsp.set(bhttp::field::content_type, "application/json");
224 rsp.body() = json::serialize(json::value_from(info));
225 rsp.prepare_payload();
226 co_return rsp;
227}
228
229auto decode_hexnib(char c) -> std::optional<std::uint8_t>
230{
231 if ('a' <= c && c <= 'f')
232 return c - 'a' + 10;
233 if ('A' <= c && c <= 'F')
234 return c - 'A' + 10;
235 if ('0' <= c && c <= '9')
236 return c - '0';
237 return std::nullopt;
238}
239
240auto handler::handle_rwgps_webhook(l0_ctx ctx, core::readable_request r)
241 -> net::awaitable<core::presponse>
242{
243 if (r.p->get()[bhttp::field::content_type] != "application/json")
244 {
245 // TODO: 415 Unsupported Media Type
246 // (respond Accept-Post: application/json)
247 throw std::runtime_error{"unhandled: unsupported media type provided"};
248 }
249
250 auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]);
251 if (!mrwgps_ts)
252 {
253 // TODO: 400 Bad Request
254 throw std::runtime_error{
255 "failed to parse ISO 8601 date/time in x-rwgps-datetime header"
256 };
257 }
258
259 // TODO: better to instead copy the expected API key to a buffer of
260 // (at least) the size of the input API key and to compare those two
261 // buffers? Then this operation should be Ω/Θ(API key provided in
262 // request)
263 auto req_api_key = r.p->get()["x-rwgps-api-key"];
264 auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X');
265 std::memcpy(
266 req_api_key_copy.data(), req_api_key.data(),
267 std::min(req_api_key.size(), rwgps_creds_->api_key().size()));
268
269 if (CRYPTO_memcmp(
270 req_api_key_copy.data(), rwgps_creds_->api_key().data(),
271 rwgps_creds_->api_key().size()))
272 {
273 // TODO: Unauthorized
274 // TODO: constant-time comparison
275 throw std::runtime_error{"unhandled: mismatching API key provided"};
276 }
277
278 auto rwgps_sig = r.p->get()["x-rwgps-signature"];
279 auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{};
280
281 if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size())
282 {
283 // TODO: Bad request
284 throw std::runtime_error{"unhandled: bad signature provided"};
285 }
286
287 for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate)
288 {
289 auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]);
290 auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]);
291 if (!mhi || !mlo)
292 {
293 throw std::runtime_error{"TODO: INVALID SIGNATURE"};
294 }
295 static_assert(std::same_as<decltype(b), std::uint8_t&>);
296 b = static_cast<std::uint8_t>((*mhi << 4) | *mlo);
297 }
298
299 auto req = co_await core::
300 read_request<http::ext::hmac_openssl::body<http::ext::json::body>>(
301 ctx, std::move(r), rwgps_creds_->api_secret());
302
303 if (req.body().mac() != rwgps_sig_decoded)
304 {
305 throw std::runtime_error{"unhandled: incorrect signature provided"};
306 }
307
308 // TODO: handle conversion failure gracefully
309 inner_.rwgps_webhook(
310 *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get()));
311
312 auto rsp = core::make_rsp<bhttp::empty_body>(
313 bhttp::status::ok, core::keep_alive{true});
314 rsp.prepare_payload();
315 co_return rsp;
316}
317
318handler::handler(
319 log::logger const& l, api::handler&& inner,
320 std::shared_ptr<rwgps::credentials> rwgps_creds)
321 : l_{l.sub("handler")}, inner_{std::move(inner)},
322 rwgps_creds_{std::move(rwgps_creds)}
323{
324}
325
326auto handler::make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>>
327{
328 auto handler = [this]<class MemFn>(MemFn member)
329 { return std::bind_front(member, this); };
330
331 return core::dtree<core::routed_ctx<outer_ctx>>{}.named_subtrees({
332 {"gpx", core::dtree<l0_ctx>{{
333 .post = handler(&handler::handle_process_gpx),
334 }}
335 .no_subtrees()},
336 {"sysinfo", core::dtree<l0_ctx>{{
337 .get = handler(&handler::handle_sysinfo),
338 }}
339 .no_subtrees()},
340 {"webhook", core::dtree<l0_ctx>{}.named_subtrees({
341 {"rwgps", core::dtree<l0_ctx>{
342 {.post = handler(&handler::handle_rwgps_webhook)}
343 }.no_subtrees()},
344 })},
345 });
346}
347
348} // namespace routemon::http
diff --git a/server/src/http/handler.cppm b/server/src/http/handler.cppm
new file mode 100644
index 0000000..d28e765
--- /dev/null
+++ b/server/src/http/handler.cppm
@@ -0,0 +1,41 @@
1module;
2
3#include <boost/asio/awaitable.hpp>
4
5export module routemon:http.handler;
6
7import :api;
8import :http.core.server;
9import :rwgps;
10
11namespace routemon::http {
12
13class handler
14{
15 log::logger l_;
16 api::handler inner_;
17 std::shared_ptr<rwgps::credentials> rwgps_creds_;
18
19public:
20 using outer_ctx = core::base_ctx;
21 using l0_ctx = core::routed_ctx<outer_ctx>;
22
23private:
24 auto handle_process_gpx(l0_ctx ctx, core::readable_request r)
25 -> net::awaitable<core::presponse>;
26
27 auto handle_sysinfo(l0_ctx ctx, core::readable_request r)
28 -> net::awaitable<core::presponse>;
29
30 auto handle_rwgps_webhook(l0_ctx ctx, core::readable_request r)
31 -> net::awaitable<core::presponse>;
32
33public:
34 handler(
35 log::logger const& l, api::handler&& inner,
36 std::shared_ptr<rwgps::credentials> rwgps_creds);
37
38 auto make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>>;
39};
40
41} // namespace routemon::http
diff --git a/server/src/http/server.cpp b/server/src/http/server.cpp
new file mode 100644
index 0000000..ddb8243
--- /dev/null
+++ b/server/src/http/server.cpp
@@ -0,0 +1,61 @@
1module;
2
3#include <boost/asio/as_tuple.hpp>
4#include <boost/asio/awaitable.hpp>
5#include <boost/asio/co_spawn.hpp>
6#include <boost/asio/ip/tcp.hpp>
7#include <boost/beast/core.hpp>
8#include <boost/beast/http.hpp>
9#include <boost/beast/zlib.hpp>
10#include <boost/config.hpp>
11#include <boost/json.hpp>
12#include <boost/locale/generator.hpp>
13
14#include <expat.h>
15
16#include <openssl/crypto.h>
17
18module routemon:http.server$impl;
19
20import std;
21import :gpx;
22import :http.server;
23import :http.ext.hmac_openssl;
24import :http.ext.json;
25
26namespace beast = boost::beast;
27namespace chrono = std::chrono;
28namespace json = boost::json;
29namespace net = boost::asio;
30using tcp = boost::asio::ip::tcp;
31
32namespace routemon::http {
33
34auto server::make_global_middleware(config::http_server const& cfg)
35 -> core::middleware_t<core::base_ctx, handler::outer_ctx>
36{
37 return core::
38 middleware_compose<core::base_ctx, core::base_ctx, core::base_ctx>(
39 core::expose_content_language_middleware<core::base_ctx>,
40 middleware_compose<core::base_ctx, core::base_ctx, core::base_ctx>(
41 core::expose_trace_id_middleware<core::base_ctx>,
42 core::cors_middleware<core::base_ctx>(cfg.allow_origins)));
43}
44
45server::server(
46 log::logger const& l, config::http_server const& cfg,
47 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
48 api::handler&& inner)
49 : handler_{l, std::move(inner), std::move(rwgps_creds)},
50 srv_{
51 l,
52 core::router{
53 l, std::move(lsel), make_global_middleware(cfg), handler_.make_routes()
54 }
55 }
56{
57}
58
59auto server::spawn(net::io_context& ioc) -> void { srv_.spawn(ioc); }
60
61} // namespace routemon::http
diff --git a/server/src/http/server.cppm b/server/src/http/server.cppm
new file mode 100644
index 0000000..7b30deb
--- /dev/null
+++ b/server/src/http/server.cppm
@@ -0,0 +1,31 @@
1module;
2
3#include <boost/asio/io_context.hpp>
4
5export module routemon:http.server;
6
7import :api;
8import :http.core.server;
9import :http.handler;
10import :rwgps;
11
12namespace routemon::http {
13
14export class server
15{
16 handler handler_;
17 core::server srv_;
18
19 static auto make_global_middleware(config::http_server const& cfg)
20 -> core::middleware_t<core::base_ctx, handler::outer_ctx>;
21
22public:
23 server(
24 log::logger const& l, config::http_server const& cfg,
25 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
26 api::handler&& inner);
27
28 auto spawn(net::io_context& ioc) -> void;
29};
30
31} // namespace routemon::http