summaryrefslogtreecommitdiffstats
path: root/server/src/srv.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'server/src/srv.cpp')
-rw-r--r--server/src/srv.cpp684
1 files changed, 0 insertions, 684 deletions
diff --git a/server/src/srv.cpp b/server/src/srv.cpp
deleted file mode 100644
index 287f838..0000000
--- a/server/src/srv.cpp
+++ /dev/null
@@ -1,684 +0,0 @@
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:srv$impl;
19
20import std;
21import :gpx;
22import :srv;
23import :rwgps.webhook;
24
25namespace beast = boost::beast;
26namespace chrono = std::chrono;
27namespace json = boost::json;
28namespace net = boost::asio;
29using tcp = boost::asio::ip::tcp;
30
31namespace routemon::srv {
32
33class gpx_parse_error_category_impl : public std::error_category
34{
35public:
36 auto name() const noexcept -> char const* override { return "gpx_parse"; }
37
38 auto message(int condition) const noexcept -> std::string override
39 {
40 std::ignore = condition;
41 return "failed to parse GPX file";
42 }
43};
44
45auto gpx_parse_error_category() noexcept -> gpx_parse_error_category_impl const&
46{
47 static auto const inst = gpx_parse_error_category_impl{};
48 return inst;
49}
50
51auto gpx_parse_error() noexcept -> std::error_code
52{
53 return std::error_code{1, gpx_parse_error_category()};
54}
55
56class gpx_parse_result
57{
58 chrono::steady_clock::duration init_parse_dur_;
59 chrono::steady_clock::duration put_parse_dur_;
60 chrono::steady_clock::duration finish_parse_dur_;
61 std::variant<std::exception_ptr, gpx::file> res_;
62
63public:
64 auto set_exception(std::exception_ptr ex) noexcept { res_ = ex; }
65 auto set_gpx_file(gpx::file&& f) noexcept { res_ = std::move(f); }
66
67 auto init_parse_duration(chrono::steady_clock::duration dur) noexcept
68 {
69 init_parse_dur_ = dur;
70 }
71 [[nodiscard]] auto init_parse_duration() const noexcept
72 -> chrono::steady_clock::duration
73 {
74 return init_parse_dur_;
75 }
76 auto put_parse_duration(chrono::steady_clock::duration dur) noexcept
77 {
78 put_parse_dur_ = dur;
79 }
80 [[nodiscard]] auto put_parse_duration() const noexcept
81 -> chrono::steady_clock::duration
82 {
83 return put_parse_dur_;
84 }
85 auto finish_parse_duration(chrono::steady_clock::duration dur) noexcept
86 {
87 finish_parse_dur_ = dur;
88 }
89 [[nodiscard]] auto finish_parse_duration() const noexcept
90 -> chrono::steady_clock::duration
91 {
92 return finish_parse_dur_;
93 }
94
95 auto unwrap() -> gpx::file&&
96 {
97 return std::visit(
98 util::overloaded{
99 [](std::exception_ptr ex) -> gpx::file&&
100 {
101 if (ex)
102 std::rethrow_exception(ex);
103 else
104 throw std::runtime_error{"no GPX file parse result available"};
105 },
106 [](gpx::file&& f) -> gpx::file&& { return std::move(f); },
107 },
108 std::move(res_));
109 }
110};
111
112struct readable_gpx_body
113{
114 using value_type = gpx_parse_result;
115
116 class reader
117 {
118 gpx::reader r_;
119 util::not_null<value_type*> res_;
120 std::inplace_vector<char, 4096> buf_;
121
122 public:
123 template <bool isRequest, bhttp::concepts::fields Fields>
124 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v) : res_{&v}
125 {
126 res_->init_parse_duration({});
127 res_->put_parse_duration({});
128 res_->finish_parse_duration({});
129 }
130
131 // The following methods (which are called by Beast) are marked
132 // noexcept, since Beast does not ensure that exceptions thrown
133 // here are appropriately directed to the caller of
134 // (async_)read(_some), so throwing here might cause the program
135 // to crash.
136
137 auto
138 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
139 -> void
140 {
141 auto const init_start = chrono::steady_clock::now();
142 try
143 {
144 r_.init();
145 ec = {};
146 }
147 catch (std::exception& ex)
148 {
149 res_->set_exception(std::current_exception());
150 ec = gpx_parse_error();
151 }
152 res_->init_parse_duration(chrono::steady_clock::now() - init_start);
153 }
154
155 auto
156 put(beast::concepts::const_buffer_sequence auto b,
157 beast::error_code& ec) noexcept -> std::size_t
158 {
159 auto const put_start = chrono::steady_clock::now();
160 auto total = 0uz;
161 try
162 {
163 for (auto cur_in_buf : beast::buffers_range(b))
164 {
165 while (cur_in_buf.size() > 0)
166 {
167 auto to_read =
168 std::min(cur_in_buf.size(), buf_.max_size() - buf_.size());
169 buf_.append_range(
170 std::span{
171 static_cast<char const*>(cur_in_buf.data()), to_read
172 });
173 cur_in_buf += to_read;
174 total += to_read;
175
176 if (buf_.size() == buf_.max_size())
177 {
178 r_.put(std::string_view{buf_});
179 buf_.clear();
180 }
181 }
182 }
183 ec = {};
184 }
185 catch (std::exception& ex)
186 {
187 res_->set_exception(std::current_exception());
188 ec = gpx_parse_error();
189 }
190 res_->put_parse_duration(
191 res_->put_parse_duration()
192 + (chrono::steady_clock::now() - put_start));
193 return total;
194 }
195
196 auto finish(beast::error_code& ec) noexcept
197 {
198 auto const finish_start = chrono::steady_clock::now();
199 try
200 {
201 if (buf_.size() > 0)
202 {
203 r_.put(std::string_view{buf_});
204 buf_.clear();
205 }
206
207 res_->set_gpx_file(r_.finish());
208 ec = {};
209 }
210 catch (std::exception& ex)
211 {
212 res_->set_exception(std::current_exception());
213 ec = gpx_parse_error();
214 }
215 res_->finish_parse_duration(chrono::steady_clock::now() - finish_start);
216 }
217 };
218};
219static_assert(bhttp::concepts::body<readable_gpx_body>);
220static_assert(bhttp::concepts::body_reader<readable_gpx_body>);
221
222template <bhttp::concepts::body_reader Inner>
223struct raw_deflate_body
224{
225 using value_type = Inner::value_type;
226
227 class reader
228 {
229 static constexpr auto const chunk_size = 16384;
230
231 Inner::reader r_;
232 bool stream_ended_ = false;
233 beast::zlib::z_params zs_ = {};
234 beast::zlib::inflate_stream inflate_strm_ = {};
235 std::unique_ptr<std::array<char, chunk_size>> in_buf_ = nullptr;
236 std::unique_ptr<std::array<char, chunk_size>> out_buf_ = nullptr;
237
238 auto inflate_chunk(beast::error_code& ec) -> void
239 {
240 assert(zs_.avail_in > 0);
241 zs_.next_in = in_buf_->data();
242
243 do
244 {
245 zs_.avail_out = out_buf_->size();
246 zs_.next_out = out_buf_->data();
247
248 inflate_strm_.write(zs_, beast::zlib::Flush::none, ec);
249 assert(ec != beast::zlib::error::stream_error);
250 if (ec == beast::zlib::error::need_buffers)
251 ec = {};
252 if (ec == beast::zlib::error::end_of_stream)
253 {
254 ec = {};
255 stream_ended_ = true;
256 }
257 if (ec)
258 break;
259
260 auto have = chunk_size - zs_.avail_out;
261 auto cbuf =
262 net::buffer(static_cast<void const*>(out_buf_->data()), have);
263
264 auto inner_ec = beast::error_code{};
265 do
266 cbuf += r_.put(cbuf, inner_ec);
267 while (cbuf.size() > 0 && !inner_ec);
268 if (inner_ec)
269 {
270 ec = inner_ec;
271 break;
272 }
273 }
274 while (zs_.avail_out == 0);
275
276 // In the last case (stream_ended_), the user has sent too much data
277 assert(zs_.avail_in == 0 || ec || stream_ended_);
278 }
279
280 public:
281 template <bool isRequest, bhttp::concepts::fields Fields>
282 explicit reader(bhttp::header<isRequest, Fields>& hdr, value_type& v)
283 : r_{hdr, v}
284 {
285 }
286
287 auto
288 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
289 -> void
290 {
291 in_buf_.reset(new std::array<char, chunk_size>{});
292 out_buf_.reset(new std::array<char, chunk_size>{});
293 ec = {};
294 }
295
296 auto
297 put(beast::concepts::const_buffer_sequence auto b,
298 beast::error_code& ec) noexcept -> std::size_t
299 {
300 auto in_buf = net::buffer(in_buf_->data(), in_buf_->size());
301 in_buf += zs_.avail_in;
302
303 auto consumed_from_b = net::buffer_copy(in_buf, b);
304 zs_.avail_in += consumed_from_b;
305
306 if (zs_.avail_in == in_buf_->size())
307 inflate_chunk(ec);
308 else
309 ec = {};
310
311 return consumed_from_b;
312 }
313
314 auto finish(beast::error_code& ec) noexcept
315 {
316 ec = {};
317 if (zs_.avail_in > 0)
318 inflate_chunk(ec);
319 if (!ec && !stream_ended_)
320 ec = beast::zlib::error::stream_error;
321 if (stream_ended_ && zs_.avail_in > 0)
322 // client sent data past deflate stream end
323 ec = beast::zlib::error::stream_error;
324
325 in_buf_.reset();
326 out_buf_.reset();
327 inflate_strm_.reset();
328 if (!ec)
329 {
330 r_.finish(ec);
331 }
332 }
333 };
334};
335
336auto parse_timestamp_mins(std::string_view in)
337 -> std::optional<time::timestamp<std::chrono::minutes>>
338{
339 auto res = time::timestamp<std::chrono::minutes>{};
340 auto is = std::istringstream{in};
341 is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res);
342 return is.fail() ? std::nullopt : std::make_optional(res);
343}
344
345auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r)
346 -> net::awaitable<http::presponse>
347{
348 auto l =
349 l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string());
350
351 auto cp_begin = time::timestamp<std::chrono::minutes>{};
352 auto cp_end = time::timestamp<std::chrono::minutes>{};
353
354 auto const params = ctx.target.params();
355 if (auto it = params.find("cpbegin"); it != params.end())
356 {
357 auto mts = parse_timestamp_mins((*it).value);
358 if (!mts)
359 {
360 auto tpl = problem::tpl{
361 .status = bhttp::status::bad_request,
362 .title = translate("Query parameter has bad value"),
363 .type_uri =
364 "https://routemon.fautchen.eu/problems/query-param-bad-value",
365 };
366 co_return http::problem_rsp(
367 ctx, tpl.instantiate(), http::keep_alive{false});
368 }
369 cp_begin = *mts;
370
371 ++it;
372 if (it != params.end() && (*it).key == "cpbegin")
373 {
374 auto tpl = problem::tpl{
375 .status = bhttp::status::bad_request,
376 .title = translate("Query parameter provided too many times"),
377 .type_uri = "https://routemon.fautchen.eu/problems/"
378 "query-param-too-many-occurrences",
379 };
380 co_return http::problem_rsp(
381 ctx, tpl.instantiate(), http::keep_alive{false});
382 }
383 }
384 else
385 {
386 auto tpl = problem::tpl{
387 .status = bhttp::status::bad_request,
388 .title = translate("Required query parameter not provided"),
389 .type_uri = "https://routemon.fautchen.eu/problems/"
390 "required-query-param-not-provided",
391 };
392 co_return http::problem_rsp(
393 ctx, tpl.instantiate(), http::keep_alive{false});
394 }
395 if (auto it = params.find("cpend"); it != params.end())
396 {
397 auto mts = parse_timestamp_mins((*it).value);
398 if (!mts)
399 {
400 auto tpl = problem::tpl{
401 .status = bhttp::status::bad_request,
402 .title = translate("Query parameter has bad value"),
403 .type_uri =
404 "https://routemon.fautchen.eu/problems/query-param-bad-value",
405 };
406 co_return http::problem_rsp(
407 ctx, tpl.instantiate(), http::keep_alive{false});
408 }
409 cp_end = *mts;
410
411 ++it;
412 if (it != params.end() && (*it).key == "cpend")
413 {
414 auto tpl = problem::tpl{
415 .status = bhttp::status::bad_request,
416 .title = translate("Query parameter provided too many times"),
417 .type_uri = "https://routemon.fautchen.eu/problems/"
418 "query-param-too-many-occurrences",
419 };
420 co_return http::problem_rsp(
421 ctx, tpl.instantiate(), http::keep_alive{false});
422 }
423 }
424 else
425 {
426 auto tpl = problem::tpl{
427 .status = bhttp::status::bad_request,
428 .title = translate("Required query parameter not provided"),
429 .type_uri = "https://routemon.fautchen.eu/problems/"
430 "required-query-param-not-provided",
431 };
432 co_return http::problem_rsp(
433 ctx, tpl.instantiate(), http::keep_alive{false});
434 }
435
436 if (cp_begin >= cp_end)
437 {
438 auto tpl = problem::tpl{
439 .status = bhttp::status::bad_request,
440 .title = translate("Invalid check period provided"),
441 .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period",
442 };
443 co_return http::problem_rsp(
444 ctx,
445 tpl.instantiate().set_detail(translate(
446 "Begin of check period must be before end of check period")),
447 http::keep_alive{false});
448 }
449 auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end};
450
451 auto gpx_file = gpx::file{};
452 try
453 {
454 l.debug("Reading GPX request body");
455 auto const before_read_gpx = chrono::steady_clock::now();
456 auto parse_res =
457 r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw"
458 ? std::move((co_await http::
459 read_request<raw_deflate_body<readable_gpx_body>>(
460 ctx, std::move(r)))
461 .body())
462 : std::move((co_await http::read_request<readable_gpx_body>(
463 ctx, std::move(r)))
464 .body());
465 l.debug(
466 "Read GPX request body in {}; init took {}, actual parsing {}, "
467 "finishing {}",
468 chrono::duration<double, std::milli>{
469 chrono::steady_clock::now() - before_read_gpx
470 },
471 chrono::duration<double, std::milli>{parse_res.init_parse_duration()},
472 chrono::duration<double, std::milli>{parse_res.put_parse_duration()},
473 chrono::duration<double, std::milli>{
474 parse_res.finish_parse_duration()
475 });
476 gpx_file = std::move(parse_res.unwrap());
477 }
478 catch (std::exception& ex)
479 {
480 l_.warn("Failed to parse GPX file: {}", ex.what());
481 // TODO: more detailed problem reporting
482 auto tpl = problem::tpl{
483 .status = bhttp::status::bad_request,
484 .title = translate("Failed to parse GPX file"),
485 .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed",
486 };
487 co_return http::problem_rsp(
488 ctx, tpl.instantiate(), http::keep_alive{false});
489 }
490
491 // TODO: catch handler exceptions and return 500 when raised?
492 // (keep-alive depends on whether whole request was read)
493 auto mres = inner_.process_gpx(
494 ctx.trace_id, std::move(gpx_file),
495 time::period_seq<std::chrono::minutes>{cp});
496 if (!mres)
497 {
498 auto tpl = problem::tpl{
499 .status = bhttp::status::internal_server_error,
500 .title = translate("Internal server error"),
501 .type_uri = "https://routemon.fautchen.eu/problems/"
502 "internal-server-error",
503 };
504 co_return http::problem_rsp(ctx, tpl.instantiate(), http::keep_alive{true});
505 }
506
507 auto rsp = http::make_rsp<bhttp::string_body>(
508 bhttp::status::ok, http::keep_alive{true});
509 rsp.set(bhttp::field::content_type, "application/json");
510 rsp.body() = json::serialize(json::value_from(*mres));
511 rsp.prepare_payload();
512 co_return rsp;
513}
514
515auto handler::handle_sysinfo(l0_ctx ctx, http::readable_request r)
516 -> net::awaitable<http::presponse>
517{
518 auto req = co_await http::read_empty_request(ctx, std::move(r));
519 auto info = inner_.sysinfo();
520
521 auto rsp = http::make_rsp<bhttp::string_body>(
522 bhttp::status::ok, http::keep_alive{true});
523 rsp.set(bhttp::field::content_type, "application/json");
524 rsp.body() = json::serialize(json::value_from(info));
525 rsp.prepare_payload();
526 co_return rsp;
527}
528
529auto decode_hexnib(char c) -> std::optional<std::uint8_t>
530{
531 if ('a' <= c && c <= 'f')
532 return c - 'a' + 10;
533 if ('A' <= c && c <= 'F')
534 return c - 'A' + 10;
535 if ('0' <= c && c <= '9')
536 return c - '0';
537 return std::nullopt;
538}
539
540auto parse_timestamp_secs(std::string_view in)
541 -> std::optional<time::timestamp<std::chrono::seconds>>
542{
543 auto res = time::timestamp<std::chrono::seconds>{};
544 auto is = std::istringstream{in};
545 is >> std::chrono::parse("%FT%TZ", res);
546 return is.fail() ? std::nullopt : std::make_optional(res);
547}
548
549auto handler::handle_rwgps_webhook(l0_ctx ctx, http::readable_request r)
550 -> net::awaitable<http::presponse>
551{
552 if (r.p->get()[bhttp::field::content_type] != "application/json")
553 {
554 // TODO: 415 Unsupported Media Type
555 // (respond Accept-Post: application/json)
556 throw std::runtime_error{"unhandled: unsupported media type provided"};
557 }
558
559 auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]);
560 if (!mrwgps_ts)
561 {
562 // TODO: 400 Bad Request
563 throw std::runtime_error{
564 "failed to parse ISO 8601 date/time in x-rwgps-datetime header"
565 };
566 }
567
568 // TODO: better to instead copy the expected API key to a buffer of
569 // (at least) the size of the input API key and to compare those two
570 // buffers? Then this operation should be Ω/Θ(API key provided in
571 // request)
572 auto req_api_key = r.p->get()["x-rwgps-api-key"];
573 auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X');
574 std::memcpy(
575 req_api_key_copy.data(), req_api_key.data(),
576 std::min(req_api_key.size(), rwgps_creds_->api_key().size()));
577
578 if (CRYPTO_memcmp(
579 req_api_key_copy.data(), rwgps_creds_->api_key().data(),
580 rwgps_creds_->api_key().size()))
581 {
582 // TODO: Unauthorized
583 // TODO: constant-time comparison
584 throw std::runtime_error{"unhandled: mismatching API key provided"};
585 }
586
587 auto rwgps_sig = r.p->get()["x-rwgps-signature"];
588 auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{};
589
590 if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size())
591 {
592 // TODO: Bad request
593 throw std::runtime_error{"unhandled: bad signature provided"};
594 }
595
596 for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate)
597 {
598 auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]);
599 auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]);
600 if (!mhi || !mlo)
601 {
602 throw std::runtime_error{"TODO: INVALID SIGNATURE"};
603 }
604 static_assert(std::same_as<decltype(b), std::uint8_t&>);
605 b = static_cast<std::uint8_t>((*mhi << 4) | *mlo);
606 }
607
608 auto req = co_await http::
609 read_request<rwgps::webhook::hmac_body<rwgps::webhook::json_body>>(
610 ctx, std::move(r), rwgps_creds_->api_secret());
611
612 if (req.body().mac() != rwgps_sig_decoded)
613 {
614 throw std::runtime_error{"unhandled: incorrect signature provided"};
615 }
616
617 // TODO: handle conversion failure gracefully
618 inner_.rwgps_webhook(
619 *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get()));
620
621 auto rsp = http::make_rsp<bhttp::empty_body>(
622 bhttp::status::ok, http::keep_alive{true});
623 rsp.prepare_payload();
624 co_return rsp;
625}
626
627handler::handler(
628 log::logger const& l, api::handler&& inner,
629 std::shared_ptr<rwgps::credentials> rwgps_creds)
630 : l_{l.sub("handler")}, inner_{std::move(inner)},
631 rwgps_creds_{std::move(rwgps_creds)}
632{
633}
634
635auto handler::make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>>
636{
637 auto handler = [this]<class MemFn>(MemFn member)
638 { return std::bind_front(member, this); };
639
640 return http::dtree<http::routed_ctx<outer_ctx>>{}.named_subtrees({
641 {"gpx", http::dtree<l0_ctx>{{
642 .post = handler(&handler::handle_process_gpx),
643 }}
644 .no_subtrees()},
645 {"sysinfo", http::dtree<l0_ctx>{{
646 .get = handler(&handler::handle_sysinfo),
647 }}
648 .no_subtrees()},
649 {"webhook", http::dtree<l0_ctx>{}.named_subtrees({
650 {"rwgps", http::dtree<l0_ctx>{
651 {.post = handler(&handler::handle_rwgps_webhook)}
652 }.no_subtrees()},
653 })},
654 });
655}
656
657auto server::make_global_middleware(config::http_server const& cfg)
658 -> http::middleware_t<http::base_ctx, handler::outer_ctx>
659{
660 return http::
661 middleware_compose<http::base_ctx, http::base_ctx, http::base_ctx>(
662 http::expose_content_language_middleware<http::base_ctx>,
663 middleware_compose<http::base_ctx, http::base_ctx, http::base_ctx>(
664 http::expose_trace_id_middleware<http::base_ctx>,
665 http::cors_middleware<http::base_ctx>(cfg.allow_origins)));
666}
667
668server::server(
669 log::logger const& l, config::http_server const& cfg,
670 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
671 api::handler&& inner)
672 : handler_{l, std::move(inner), std::move(rwgps_creds)},
673 srv_{
674 l,
675 http::router{
676 l, std::move(lsel), make_global_middleware(cfg), handler_.make_routes()
677 }
678 }
679{
680}
681
682auto server::spawn(net::io_context& ioc) -> void { srv_.spawn(ioc); }
683
684} // namespace routemon::srv