From 02475e05ccd1aa15c6a6163834f28bfebbef796f Mon Sep 17 00:00:00 2001 From: Rutger Broekhoff Date: Mon, 30 Nov 2026 11:47:36 +0100 Subject: RWGPS webhook and such --- server/CMakeLists.txt | 3 + server/migrations/1_init_up.sql | 13 +- server/migrations/2_kaas_up.sql | 23 --- server/migrations/2_rwgps_up.sql | 22 +++ server/src/api.cpp | 104 ++++++++++- server/src/api.cppm | 68 ++++---- server/src/config.cpp | 4 +- server/src/config.cppm | 23 +-- server/src/database.cpp | 116 ++++++++++++- server/src/database.cppm | 64 ++++++- server/src/datex2.cpp | 63 ++++--- server/src/datex2.cppm | 10 +- server/src/geo/utm_multizonal.cppm | 11 +- server/src/gpx.cpp | 12 +- server/src/gpx.cppm | 18 +- server/src/http/ext/hmac_openssl.cppm | 10 ++ server/src/http/ext/json.cppm | 0 server/src/http_client.cppm | 5 +- server/src/http_server.cppm | 7 +- server/src/locale.cpp | 2 +- server/src/log.cppm | 3 +- server/src/main.cpp | 219 ++++++++++++++++++++--- server/src/migrate.cppm | 126 ++++++++++++++ server/src/routemon.cppm | 1 + server/src/rwgps.cpp | 168 ++++++++++++++---- server/src/rwgps.cppm | 82 ++++++++- server/src/rwgps_webhook.cppm | 237 +++++++++++++++++++++++++ server/src/sqlite3.cpp | 318 ++++++++++++++++++++++++---------- server/src/sqlite3.cppm | 149 +++++++++++----- server/src/srv.cpp | 145 ++++++++++++++-- server/src/srv.cppm | 12 +- server/src/time.cpp | 167 +----------------- server/src/time.cppm | 237 +++++++++++++++++++++++-- server/src/trace.cpp | 6 - server/src/util.cppm | 56 ++++-- server/src/xml.cppm | 8 +- 36 files changed, 1945 insertions(+), 567 deletions(-) delete mode 100644 server/migrations/2_kaas_up.sql create mode 100644 server/migrations/2_rwgps_up.sql create mode 100644 server/src/http/ext/hmac_openssl.cppm create mode 100644 server/src/http/ext/json.cppm create mode 100644 server/src/migrate.cppm create mode 100644 server/src/rwgps_webhook.cppm diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index fad973f..b8fd37a 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -7,6 +7,7 @@ add_compile_options( -O2 -fno-omit-frame-pointer -Wall -Wextra -Wformat -Wformat=2 -Wconversion -Wimplicit-fallthrough + -Wconsumed -Werror=format-security -U_FORTIFY_SOURCE # -D_FORTIFY_SOURCE=3 (unfortunately breaks the std module, see https://github.com/llvm/llvm-project/issues/121709) -D_GLIBCXX_ASSERTIONS @@ -46,11 +47,13 @@ target_sources(routemon_lib src/locale.cpp src/log.cppm src/log.cpp + src/migrate.cppm src/problem.cppm src/problem.cpp src/routemon.cppm src/rwgps.cppm src/rwgps.cpp + src/rwgps_webhook.cppm src/sqlite3.cppm src/sqlite3.cpp src/srv.cppm diff --git a/server/migrations/1_init_up.sql b/server/migrations/1_init_up.sql index 7edb398..8400f8d 100644 --- a/server/migrations/1_init_up.sql +++ b/server/migrations/1_init_up.sql @@ -1,7 +1,8 @@ -BEGIN; +CREATE TABLE migration ( + at_most_one_row INTEGER UNIQUE DEFAULT 1, + version INTEGER NOT NULL, + -- This table should have at most one row. + CHECK (at_most_one_row = 1) +) STRICT; -CREATE TABLE migration (version); - -INSERT INTO migration VALUES (1); - -COMMIT; +INSERT INTO migration (version) VALUES (0); diff --git a/server/migrations/2_kaas_up.sql b/server/migrations/2_kaas_up.sql deleted file mode 100644 index 0c7837a..0000000 --- a/server/migrations/2_kaas_up.sql +++ /dev/null @@ -1,23 +0,0 @@ -BEGIN; - --- TODO enable strict mode so that primary key is automatically enforced to not be NULL -CREATE TABLE received_route ( - id INTEGER PRIMARY KEY, - - received_route_source route_source NOT NULL, - recieved_route_strava_id TEXT, - - -- ON DELETE what? - FOREIGN KEY (received_route_source_id) REFERENCES received_route_source (id), - CHECK (received_route_source IN ('gpx_upload', 'strava', 'rwgps')), - CHECK ((received_route_source = 'strava') = (received_route_strava_id IS NULL)) -); - -CREATE TABLE received_route_linestring ( - received_route_id INT NOT NULL, - linestring BLOB NOT NULL, - - FOREIGN KEY (received_route_id) REFERENCES received_route (id) -); - -COMMIT; diff --git a/server/migrations/2_rwgps_up.sql b/server/migrations/2_rwgps_up.sql new file mode 100644 index 0000000..569479b --- /dev/null +++ b/server/migrations/2_rwgps_up.sql @@ -0,0 +1,22 @@ +CREATE TABLE rwgps_notification ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + rwgps_timestamp TEXT NOT NULL, + user_id INTEGER NOT NULL, + item_type TEXT, -- NULL if unknown + item_id INTEGER, + item_user_id INTEGER, + item_url TEXT, + action_ TEXT, -- NULL if unknown + CHECK (rwgps_timestamp IS strftime('%FT%TZ', rwgps_timestamp)), + CHECK (item_type IN ('trip', 'route', 'event', 'event_participant', 'club_member', 'authorization')), + CHECK (action_ IN ('created', 'updated', 'deleted', 'added', 'removed')) +) STRICT; + +CREATE TABLE rwgps_notification_target_collection ( + notification_id INTEGER PRIMARY KEY, + id INTEGER NOT NULL, + type_ TEXT, -- NULL if unknown + url TEXT, + CHECK (type_ IN ('pinned')), + FOREIGN KEY (notification_id) REFERENCES rwgps_notification (id) +) STRICT; diff --git a/server/src/api.cpp b/server/src/api.cpp index 9a51690..8a986d4 100644 --- a/server/src/api.cpp +++ b/server/src/api.cpp @@ -99,8 +99,10 @@ auto tag_invoke(json::value_from_tag, json::value& jv, sysinfo const& info) }; } -handler::handler(log::logger const& l, datex2::situation_publication pub) - : l_{l.sub("handler")}, pub_{std::move(pub)} +handler::handler( + log::logger const& l, std::shared_ptr dbc, + datex2::situation_publication pub) + : l_{l.sub("handler")}, dbc_{std::move(dbc)}, pub_{std::move(pub)} { auto const nsit = pub_.situations.size(); auto progress_percent = @@ -145,7 +147,8 @@ handler::handler(log::logger const& l, datex2::situation_publication pub) } auto handler::process_gpx( - trace::id trace_id, gpx::file&& gpx_file, time::period_seq check_periods) + trace::id trace_id, gpx::file&& gpx_file, + time::period_seq const& check_periods) -> std::optional { auto l = l_.with("trace_id", trace_id.as_string()); @@ -282,4 +285,99 @@ auto handler::sysinfo() -> struct sysinfo }; } + auto rwgps_notification_cause_to_db(rwgps::notification_cause c) -> database::schema::rwgps_notification_cause +{ + switch (c) + { + case rwgps::notification_cause::unknown: + return database::schema::rwgps_notification_cause::unknown; + case rwgps::notification_cause::created: + return database::schema::rwgps_notification_cause::created; + case rwgps::notification_cause::updated: + return database::schema::rwgps_notification_cause::updated; + case rwgps::notification_cause::deleted: + return database::schema::rwgps_notification_cause::deleted; + case rwgps::notification_cause::added: + return database::schema::rwgps_notification_cause::added; + case rwgps::notification_cause::removed: + return database::schema::rwgps_notification_cause::removed; + } +} + +auto rwgps_notification_item_type_to_db(rwgps::notification_item_type t) + -> database::schema::rwgps_notification_item_type +{ + switch (t) + { + case rwgps::notification_item_type::unknown: + return database::schema::rwgps_notification_item_type::unknown; + case rwgps::notification_item_type::trip: + return database::schema::rwgps_notification_item_type::trip; + case rwgps::notification_item_type::route: + return database::schema::rwgps_notification_item_type::route; + case rwgps::notification_item_type::event: + return database::schema::rwgps_notification_item_type::event; + case rwgps::notification_item_type::event_participant: + return database::schema::rwgps_notification_item_type::event_participant; + case rwgps::notification_item_type::club_member: + return database::schema::rwgps_notification_item_type::club_member; + case rwgps::notification_item_type::authorization: + return database::schema::rwgps_notification_item_type::authorization; + } +} + +auto rwgps_notification_target_collection_type_to_db( + rwgps::notification_target_collection_type t) + -> database::schema::rwgps_notification_target_collection_type +{ + switch (t) + { + case rwgps::notification_target_collection_type::unknown: + return database::schema::rwgps_notification_target_collection_type::unknown; + case rwgps::notification_target_collection_type::pinned: + return database::schema::rwgps_notification_target_collection_type::pinned; + } +} + +auto handler::rwgps_webhook( + time::timestamp rwgps_ts, rwgps::webhook_request req) + -> void +{ + l_.info("Handling (valid) RWGPS webhook request"); + + auto notifs = std::vector + >>{}; + + for (auto const& notif : req.notifications) + { + auto db_notif = database::schema::rwgps_notification{ + .rwgps_timestamp = rwgps_ts, + .user_id = notif.user_id, + .item_type = rwgps_notification_item_type_to_db(notif.item_type), + .item_id = notif.item_id, + .item_user_id = notif.item_user_id, + .item_url = notif.item_url, + .action = rwgps_notification_cause_to_db(notif.action), + }; + + auto mdb_collection = notif.collection.transform( + [](auto const& collection) + -> database::schema::rwgps_notification_target_collection + { + return { + .id = collection.id, + .type = rwgps_notification_target_collection_type_to_db( + collection.type), + .url = collection.url, + }; + }); + + notifs.emplace_back(db_notif, mdb_collection); + } + + dbc_->insert_rwgps_notifications(notifs); +} + } // namespace routemon::api diff --git a/server/src/api.cppm b/server/src/api.cppm index b14bbcf..7e71413 100644 --- a/server/src/api.cppm +++ b/server/src/api.cppm @@ -6,74 +6,71 @@ module; export module routemon:api; import std; +import :database; import :datex2; import :geo.wgs84; import :geo.utm.multizonal; import :gpx; import :log; import :time; +import :rwgps; import :trace; -namespace { - -namespace chrono = std::chrono; -namespace json = boost::json; -namespace views = std::views; - -} // namespace - export namespace routemon::api { struct relevant_road_closure { - std::vector relevant_lss; + std::vector relevant_lss = {}; }; struct relevant_situation { - std::string id; - std::optional location; - std::vector comments; - std::vector relevant_road_closures; + std::string id = {}; + std::optional location = {}; + std::vector comments = {}; + std::vector relevant_road_closures = {}; }; struct track_segment { - geo::utm::zonable_wgs84_linestring points; + geo::utm::zonable_wgs84_linestring points = {}; }; struct track { - std::vector segments; + std::vector segments = {}; }; struct process_gpx_result { - std::vector tracks; - std::vector relevant_situations; + std::vector tracks = {}; + std::vector relevant_situations = {}; }; struct sysinfo { - time::timestamp using_publication_of; - std::size_t blse_index_size; - std::size_t bpe_index_size; + time::timestamp<> using_publication_of = {}; + std::size_t blse_index_size = 0uz; + std::size_t bpe_index_size = 0uz; }; auto tag_invoke( - json::value_from_tag, json::value& jv, relevant_road_closure const& clo) - -> void; + boost::json::value_from_tag, boost::json::value& jv, + relevant_road_closure const& clo) -> void; auto tag_invoke( - json::value_from_tag, json::value& jv, relevant_situation const& sit) - -> void; -auto tag_invoke(json::value_from_tag, json::value& jv, track_segment const& seg) - -> void; -auto tag_invoke(json::value_from_tag, json::value& jv, track const& track) - -> void; + boost::json::value_from_tag, boost::json::value& jv, + relevant_situation const& sit) -> void; +auto tag_invoke( + boost::json::value_from_tag, boost::json::value& jv, + track_segment const& seg) -> void; auto tag_invoke( - json::value_from_tag, json::value& jv, process_gpx_result const& res) + boost::json::value_from_tag, boost::json::value& jv, track const& track) -> void; -auto tag_invoke(json::value_from_tag, json::value& jv, sysinfo const& info) +auto tag_invoke( + boost::json::value_from_tag, boost::json::value& jv, + process_gpx_result const& res) -> void; +auto tag_invoke( + boost::json::value_from_tag, boost::json::value& jv, sysinfo const& info) -> void; class handler @@ -86,17 +83,24 @@ class handler using bpe_index = geo::utm::multizonal::point_rtree; log::logger l_; + std::shared_ptr dbc_; datex2::situation_publication pub_; blse_index blse_index_; bpe_index bpe_index_; public: - explicit handler(log::logger const& l, datex2::situation_publication pub); + explicit handler( + log::logger const& l, std::shared_ptr dbc, + datex2::situation_publication pub); auto process_gpx( - trace::id trace_id, gpx::file&& gpx_file, time::period_seq check_periods) + trace::id trace_id, gpx::file&& gpx_file, + time::period_seq const& check_periods) -> std::optional; auto sysinfo() -> sysinfo; + auto rwgps_webhook( + time::timestamp rwgps_ts, + rwgps::webhook_request req) -> void; }; } // namespace routemon::api diff --git a/server/src/config.cpp b/server/src/config.cpp index 200b873..9231232 100644 --- a/server/src/config.cpp +++ b/server/src/config.cpp @@ -139,6 +139,8 @@ auto tag_invoke( { return { .api_key_filename = r.expect_at("api_key_filename"), + .api_secret_filename = + r.expect_at("api_secret_filename"), .auth_token_filename = r.expect_at("auth_token_filename"), }; @@ -222,7 +224,7 @@ auto json_value_to_app(json::value const& jv) -> app [](object_reader& r) -> app { return { - .rwgps = r.allow_at("rwgps"), + .rwgps = r.expect_at("rwgps"), .situations = r.expect_at("situations"), .database = r.expect_at("database"), .http_server = r.expect_at("http_server"), diff --git a/server/src/config.cppm b/server/src/config.cppm index ab9b137..01e1055 100644 --- a/server/src/config.cppm +++ b/server/src/config.cppm @@ -7,37 +7,38 @@ namespace routemon::config { export struct rwgps { - std::string api_key_filename; - std::string auth_token_filename; + std::string api_key_filename = {}; + std::string api_secret_filename = {}; + std::string auth_token_filename = {}; }; export struct situations { - std::string datex2_filename; + std::string datex2_filename = {}; }; export struct database { - std::string sqlite3_filename; + std::string sqlite3_filename = {}; }; export struct http_server { - std::vector allow_origins; + std::vector allow_origins = {}; }; export struct logger { - log::level level; + log::level level = log::level::debug; }; export struct app { - std::optional rwgps; - situations situations; - database database; - http_server http_server; - logger logger; + rwgps rwgps = {}; + situations situations = {}; + database database = {}; + http_server http_server = {}; + logger logger = {}; }; export auto load_file(std::string const& filename) -> app; diff --git a/server/src/database.cpp b/server/src/database.cpp index 54e5f34..c1f9ab2 100644 --- a/server/src/database.cpp +++ b/server/src/database.cpp @@ -4,23 +4,125 @@ import :database; namespace routemon::database { -constexpr std::int64_t expected_database_version = 1; +namespace schema { -auto open(std::string const& filename) -> std::shared_ptr +constexpr std::int64_t expected_version = 2; + +auto try_to_string(rwgps_notification_cause c) -> std::optional +{ + switch (c) + { + case rwgps_notification_cause::unknown: + return std::nullopt; + case rwgps_notification_cause::created: + return "created"; + case rwgps_notification_cause::updated: + return "updated"; + case rwgps_notification_cause::deleted: + return "deleted"; + case rwgps_notification_cause::added: + return "added"; + case rwgps_notification_cause::removed: + return "removed"; + } +} + +auto try_to_string(rwgps_notification_item_type t) -> std::optional +{ + switch (t) + { + case rwgps_notification_item_type::unknown: + return std::nullopt; + case rwgps_notification_item_type::trip: + return "trip"; + case rwgps_notification_item_type::route: + return "route"; + case rwgps_notification_item_type::event: + return "event"; + case rwgps_notification_item_type::event_participant: + return "event_participant"; + case rwgps_notification_item_type::club_member: + return "club_member"; + case rwgps_notification_item_type::authorization: + return "authorization"; + } +} + +auto try_to_string(rwgps_notification_target_collection_type t) + -> std::optional +{ + switch (t) + { + case rwgps_notification_target_collection_type::unknown: + return std::nullopt; + case rwgps_notification_target_collection_type::pinned: + return "pinned"; + } +}; + +} // namespace schema + +auto connection::insert_rwgps_notifications( + std::vector + >>& notifs) -> void +{ + auto tx = sqlite3::tx{dbc_}; + for (auto& [notif, mtarget_collection] : notifs) + { + tx.query( + "INSERT INTO rwgps_notification " + " (rwgps_timestamp, user_id, item_type, item_id, " + " item_user_id, item_url, action_) " + "VALUES (:rwgps_timestamp, :user_id, :item_type, :item_id, " + " :item_user_id, :item_url, :action) " + "RETURNING id", + [¬if](auto& s) + { + auto const ts = time::iso8601_secs(notif.rwgps_timestamp); + s.bind(":rwgps_timestamp", std::string_view{ts}); + s.bind(":user_id", notif.user_id); + s.bind(":item_type", try_to_string(notif.item_type)); + s.bind(":item_id", notif.item_id); + s.bind(":item_user_id", notif.item_user_id); + s.bind(":item_url", notif.item_url); + s.bind(":action", try_to_string(notif.action)); + }) + .scan_row_max1(notif.id); + + if (mtarget_collection) + { + tx.exec( + "INSERT INTO rwgps_notification_target_collection " + " (notification_id, id, type_, url) " + "VALUES (:notification_id, :id, :type, :url)", + [¬if, &mtarget_collection](auto& s) + { + s.bind(":notification_id", notif.id); + s.bind(":id", mtarget_collection->id); + s.bind(":type", try_to_string(mtarget_collection->type)); + s.bind(":url", mtarget_collection->url); + }); + } + } +} + +auto open(util::zstring_view filename) -> std::shared_ptr { auto dbc = sqlite3::open(filename); try { - auto version = std::optional{}; - dbc.query("SELECT version FROM migration;").scan_single(version); - if (!version) + auto mversion = std::optional{}; + dbc.query("SELECT version FROM migration;").scan_row_max1(mversion); + if (!mversion) throw std::runtime_error{"failed to fetch database migration version"}; - if (version != expected_database_version) + if (mversion != schema::expected_version) { throw std::runtime_error{std::format( "database migration version ({}) does not match expected " "version ({}), consider running migrations", - *version, expected_database_version)}; + *mversion, schema::expected_version)}; } } catch (std::exception const& e) diff --git a/server/src/database.cppm b/server/src/database.cppm index ff5cae4..83616d2 100644 --- a/server/src/database.cppm +++ b/server/src/database.cppm @@ -2,21 +2,79 @@ export module routemon:database; import std; import :sqlite3; +import :time; namespace routemon::database { +namespace schema { + +enum class rwgps_notification_cause +{ + unknown, + created, + updated, + deleted, + added, + removed, +}; + +enum class rwgps_notification_item_type +{ + unknown, + trip, + route, + event, + event_participant, + club_member, + authorization, +}; + +enum rwgps_notification_target_collection_type +{ + unknown, + pinned, +}; + +struct rwgps_notification_target_collection +{ + std::int64_t notification_id = 0; + std::int64_t id; + rwgps_notification_target_collection_type type; + std::optional url; +}; + +struct rwgps_notification +{ + std::int64_t id = 0; + time::timestamp rwgps_timestamp; + // User that took the action + std::int64_t user_id; + rwgps_notification_item_type item_type; + std::optional item_id; + // User that owns the item + std::optional item_user_id; + std::optional item_url; + rwgps_notification_cause action; +}; + +} // namespace schema + export class connection { sqlite3::connection dbc_; explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {} - friend auto open(std::string const& filename) -> std::shared_ptr; + friend auto open(util::zstring_view filename) -> std::shared_ptr; public: - // Nothing here yet + auto insert_rwgps_notifications( + std::vector + >>& notifs) -> void; }; -export auto open(std::string const& filename) -> std::shared_ptr; +export auto open(util::zstring_view filename) -> std::shared_ptr; } // namespace routemon::database diff --git a/server/src/datex2.cpp b/server/src/datex2.cpp index 70c5f94..ab49fd9 100644 --- a/server/src/datex2.cpp +++ b/server/src/datex2.cpp @@ -14,11 +14,11 @@ using namespace std::literals::string_view_literals; namespace routemon::datex2 { -auto parse_timestamp(char const* in) -> std::optional +auto parse_timestamp_secs(char const* in) -> std::optional> { - auto res = time::timestamp{}; + auto res = time::timestamp<>{}; auto is = std::istringstream{in}; - is >> std::chrono::parse("%Y-%m-%dT%H:%M:%SZ", res); + is >> std::chrono::parse("%FT%TZ", res); return is.fail() ? std::nullopt : std::make_optional(res); } @@ -178,7 +178,7 @@ auto loader::handle_road_or_carriageway_or_lane_management( //---- Check if within the defined validity period - auto validity = std::optional{}; + auto validity = std::optional>{}; auto const& validity_xml = record_xml.child("sit:validity"); if (validity_xml && validity_xml.child_value("com:validityStatus") @@ -187,52 +187,67 @@ auto loader::handle_road_or_carriageway_or_lane_management( auto const& validity_spec_xml = validity_xml.child("com:validityTimeSpecification"); - auto valid_periods = std::vector{}; - auto exception_periods = std::vector{}; + auto valid_periods = std::vector>{}; + auto exception_periods = std::vector>{}; // TODO: com:overallEndTime may be missing (according to the DATEX // II v3 data model) - auto const overall_start_time = - parse_timestamp(validity_spec_xml.child_value("com:overallStartTime")); - auto const overall_end_time = - parse_timestamp(validity_spec_xml.child_value("com:overallEndTime")); + auto const overall_start_time = parse_timestamp_secs( + validity_spec_xml.child_value("com:overallStartTime")); + auto const overall_end_time = parse_timestamp_secs( + validity_spec_xml.child_value("com:overallEndTime")); if (overall_start_time && overall_end_time && *overall_start_time < *overall_end_time) { - valid_periods.emplace_back(*overall_start_time, *overall_end_time); + valid_periods.emplace_back( + std::chrono::time_point_cast( + *overall_start_time), + std::chrono::time_point_cast( + *overall_end_time)); for (auto const valid_period_xml : validity_xml.children("com:validPeriod")) { - auto const start_of_period = - parse_timestamp(valid_period_xml.child_value("com:startOfPeriod")); - auto const end_of_period = - parse_timestamp(valid_period_xml.child_value("com:endOfPeriod")); + auto const start_of_period = parse_timestamp_secs( + valid_period_xml.child_value("com:startOfPeriod")); + auto const end_of_period = parse_timestamp_secs( + valid_period_xml.child_value("com:endOfPeriod")); if (start_of_period && end_of_period && *start_of_period < *end_of_period) { - valid_periods.emplace_back(*start_of_period, *end_of_period); + valid_periods.emplace_back( + std::chrono::time_point_cast( + *start_of_period), + std::chrono::time_point_cast( + *end_of_period)); } } for (auto const exception_period_xml : validity_xml.children("com:exceptionPeriod")) { - auto const start_of_period = parse_timestamp( + auto const start_of_period = parse_timestamp_secs( exception_period_xml.child_value("com:startOfPeriod")); - auto const end_of_period = parse_timestamp( + auto const end_of_period = parse_timestamp_secs( exception_period_xml.child_value("com:endOfPeriod")); if (start_of_period && end_of_period && *start_of_period < *end_of_period) { - exception_periods.emplace_back(*start_of_period, *end_of_period); + exception_periods.emplace_back( + std::chrono::time_point_cast( + *start_of_period), + std::chrono::time_point_cast( + *end_of_period)); } } validity = - time::period_seq{valid_periods.begin(), valid_periods.end()}.except( - time::period_seq{ - exception_periods.begin(), exception_periods.end() - }); + time::period_seq{ + valid_periods.begin(), valid_periods.end() + } + .except( + time::period_seq{ + exception_periods.begin(), exception_periods.end() + }); } else { @@ -263,7 +278,7 @@ auto loader::load_situation_publication(std::string const& filename) } auto payload_xml = doc.child("mc:messageContainer").child("mc:payload"); auto mpublication_time = - parse_timestamp(payload_xml.child_value("com:publicationTime")); + parse_timestamp_secs(payload_xml.child_value("com:publicationTime")); if (!mpublication_time) throw std::runtime_error{ "provided publication does not name publication time" diff --git a/server/src/datex2.cppm b/server/src/datex2.cppm index ae66631..421d29c 100644 --- a/server/src/datex2.cppm +++ b/server/src/datex2.cppm @@ -20,8 +20,8 @@ export struct situation; export struct road_closure { - std::weak_ptr parent; - std::optional validity; + std::weak_ptr parent = {}; + std::optional> validity = std::nullopt; std::vector relevant_points = {}; std::vector> relevant_line_strings = {}; @@ -29,7 +29,7 @@ export struct road_closure export struct situation { - std::string id; + std::string id = {}; std::optional location = std::nullopt; // as shown on the map, not used for querying std::vector comments = {}; @@ -38,8 +38,8 @@ export struct situation export struct situation_publication { - time::timestamp publication_time; - std::vector> situations; + time::timestamp<> publication_time = {}; + std::vector> situations = {}; }; export class loader diff --git a/server/src/geo/utm_multizonal.cppm b/server/src/geo/utm_multizonal.cppm index 540e309..56c6481 100644 --- a/server/src/geo/utm_multizonal.cppm +++ b/server/src/geo/utm_multizonal.cppm @@ -61,7 +61,7 @@ class from_wgs84_transforms : public multi_zone } public: - static from_wgs84_transforms const& instance() + static auto instance() -> from_wgs84_transforms const& { static from_wgs84_transforms inst; return inst; @@ -214,8 +214,7 @@ private: local_rtrees_; public: - template U> - auto insert(utm::zonable_wgs84_linestring const& ls, U&& arg) -> void + auto insert(utm::zonable_wgs84_linestring const& ls, T arg) -> void { auto zone_segments = distribute_linestring_over_zones(ls); for (auto z = utm::zone::min(); z != utm::zone::max(); z = z.next()) @@ -225,8 +224,7 @@ public: auto blse = bgeo::return_buffer( bgeo::return_envelope(ls), 30.0 /* m */); - local_rtrees_[z].insert( - index_value{blse, std::move(ls), std::forward(arg)}); + local_rtrees_[z].insert(index_value{blse, std::move(ls), arg}); } } } @@ -279,8 +277,7 @@ private: local_rtrees_; public: - template U> - auto insert(utm::zonable_wgs84_point const& p, U&& arg) -> void + auto insert(utm::zonable_wgs84_point const& p, T arg) -> void { auto to_utm = from_wgs84_transforms::instance(); diff --git a/server/src/gpx.cpp b/server/src/gpx.cpp index 2193e6a..c43b380 100644 --- a/server/src/gpx.cpp +++ b/server/src/gpx.cpp @@ -51,7 +51,7 @@ auto parse_wpt(xml::executor_ref e, xml::attribute_view attrs) co_return *mp; } -auto parse_trkseg(xml::executor_ref e, xml::attribute_view) +auto parse_trkseg(xml::executor_ref e, xml::attribute_view /* attrs */) -> xml::parser { auto s = track_segment{}; @@ -61,7 +61,8 @@ auto parse_trkseg(xml::executor_ref e, xml::attribute_view) co_return std::move(s); } -auto parse_trk(xml::executor_ref e, xml::attribute_view) -> xml::parser +auto parse_trk(xml::executor_ref e, xml::attribute_view /* attrs */) + -> xml::parser { auto t = track{}; t.name = co_await allow_element( @@ -112,7 +113,7 @@ auto qname(std::string_view local) -> xml::qname_view return {.ns_uri = xmlns, .local = local}; } -auto parse_metadata(xml::executor_ref e, xml::attribute_view) +auto parse_metadata(xml::executor_ref e, xml::attribute_view /* attrs */) -> xml::parser { auto meta = metadata{}; @@ -154,7 +155,7 @@ auto parse_wpt(xml::executor_ref e, xml::attribute_view attrs) co_return *mp; } -auto parse_trkseg(xml::executor_ref e, xml::attribute_view) +auto parse_trkseg(xml::executor_ref e, xml::attribute_view /* attrs */) -> xml::parser { auto s = track_segment{}; @@ -166,7 +167,8 @@ auto parse_trkseg(xml::executor_ref e, xml::attribute_view) co_return std::move(s); } -auto parse_trk(xml::executor_ref e, xml::attribute_view) -> xml::parser +auto parse_trk(xml::executor_ref e, xml::attribute_view /* attrs */) + -> xml::parser { auto t = track{}; t.name = co_await allow_element( diff --git a/server/src/gpx.cppm b/server/src/gpx.cppm index 6267443..ab1b0a1 100644 --- a/server/src/gpx.cppm +++ b/server/src/gpx.cppm @@ -9,27 +9,27 @@ namespace routemon::gpx { struct metadata { - std::optional name; - std::optional desc; + std::optional name = std::nullopt; + std::optional desc = std::nullopt; }; struct track_segment { - geo::utm::zonable_wgs84_linestring waypoints; + geo::utm::zonable_wgs84_linestring waypoints = {}; }; struct track { - std::optional name; - std::optional desc; - std::vector segments; + std::optional name = std::nullopt; + std::optional desc = std::nullopt; + std::vector segments = {}; }; struct file { - std::string creator; - metadata meta; - std::vector tracks; + std::string creator = {}; + metadata meta = {}; + std::vector tracks = {}; }; class reader diff --git a/server/src/http/ext/hmac_openssl.cppm b/server/src/http/ext/hmac_openssl.cppm new file mode 100644 index 0000000..52ccb86 --- /dev/null +++ b/server/src/http/ext/hmac_openssl.cppm @@ -0,0 +1,10 @@ +module; + +#include +#include + +export module routemon:hmac_openssl; + +namespace routemon::hmac_openssl { + +} diff --git a/server/src/http/ext/json.cppm b/server/src/http/ext/json.cppm new file mode 100644 index 0000000..e69de29 diff --git a/server/src/http_client.cppm b/server/src/http_client.cppm index 2047b01..accd5c0 100644 --- a/server/src/http_client.cppm +++ b/server/src/http_client.cppm @@ -37,8 +37,9 @@ public: auto host = std::string{req.at(bhttp::field::host)}; if (!SSL_set_tlsext_host_name(stream.native_handle(), host.c_str())) { - throw beast::system_error( - static_cast(::ERR_get_error()), net::error::get_ssl_category()); + throw beast::system_error{ + static_cast(::ERR_get_error()), net::error::get_ssl_category() + }; } stream.set_verify_callback(ssl::host_name_verification(host)); auto const results = resolver_.resolve(host, "443"); diff --git a/server/src/http_server.cppm b/server/src/http_server.cppm index c111118..b75ada3 100644 --- a/server/src/http_server.cppm +++ b/server/src/http_server.cppm @@ -264,12 +264,13 @@ auto make_preflight_rsp(preflight_response res, keep_alive ka) // Using base_ctx instead of a template here since that saves you // typing on invocation (and we do not care about the context type // anyway, but all context types should derive from base_ctx). -template -auto read_request(base_ctx const& ctx, readable_request&& r) +template +auto read_request(base_ctx const& ctx, readable_request&& r, Args&&... args) -> net::awaitable> { std::ignore = ctx; - auto p = bhttp::request_parser{std::move(*r.p)}; + auto p = + bhttp::request_parser{std::move(*r.p), std::forward(args)...}; co_await bhttp::async_read(*r.strm, *r.buf, p); co_return std::move(p.release()); } diff --git a/server/src/locale.cpp b/server/src/locale.cpp index 92bc33b..a964d5e 100644 --- a/server/src/locale.cpp +++ b/server/src/locale.cpp @@ -206,7 +206,7 @@ constexpr auto messages_path = std::string_view{LOCALEDIR_AUX_XSTR(LOCALEDIR)}; constexpr auto messages_path = std::string_view{"locale/dev"}; #endif // ifdef LOCALEDIR -export auto make_generator() -> std::shared_ptr +auto make_generator() -> std::shared_ptr { auto lgen = std::make_shared(); lgen->add_messages_path(std::string{messages_path}); diff --git a/server/src/log.cppm b/server/src/log.cppm index 87382f6..10c2d7a 100644 --- a/server/src/log.cppm +++ b/server/src/log.cppm @@ -4,7 +4,8 @@ import std; namespace routemon::log { -export enum class level : std::uint8_t { +export enum class level : std::uint8_t +{ debug, info, warn, diff --git a/server/src/main.cpp b/server/src/main.cpp index 3ef45c6..df750d9 100644 --- a/server/src/main.cpp +++ b/server/src/main.cpp @@ -1,5 +1,6 @@ #include #include // for malloc_trim(3) +#include import std; import routemon; @@ -7,27 +8,79 @@ import routemon; namespace chrono = std::chrono; namespace net = boost::asio; +using namespace std::literals::string_view_literals; + enum class exit_status { + success, failure, bad_usage, }; -auto real_main(std::span args) -> exit_status +struct secure_buf { - auto sink = routemon::log::make_sink(routemon::log::level::info); - auto l = routemon::log::logger{sink}; + void* p; + std::size_t size = 0; - if (args.size() != 2) + secure_buf(secure_buf const&) = delete; + secure_buf(secure_buf&&) = delete; + + auto operator=(secure_buf const&) -> secure_buf& = delete; + auto operator=(secure_buf&&) -> secure_buf& = delete; + + secure_buf(std::size_t size) : p{OPENSSL_malloc(size)} { - l.error( - "Fatal: expected exactly one argument (the configuration file " - "location), got {}", - args.size() - 1); - return exit_status::bad_usage; + if (!this->p) + throw std::bad_alloc{}; } - auto const* config_filename = args[1]; + ~secure_buf() { OPENSSL_clear_free(this->p, this->size); } +}; + +auto ltrim_ws(std::string_view s) -> std::string_view +{ + if (auto i = s.find_first_not_of(" \t\r\n"); i != std::string_view::npos) + s.remove_prefix(i); + return s; +} +auto rtrim_ws(std::string_view s) -> std::string_view +{ + if (auto i = s.find_last_not_of(" \t\r\n"); i != std::string_view::npos) + return s.substr(0, i + 1); + return s; +} +auto trim_ws(std::string_view s) -> std::string_view +{ + return rtrim_ws(ltrim_ws(s)); +} + +// TODO: make own secure string type using the OpenSSL primitives +template +auto read_secret_to_string(std::string const& filename) -> std::string +{ + static_assert(max_size <= 65536); // sounds reasonable enough? + + auto f = std::ifstream{filename, std::ios::binary}; + if (!f) + throw std::system_error{ + errno, std::generic_category(), + std::format("opening secret located at {}", filename) + }; + auto buf_cap = max_size; + auto buf = secure_buf{max_size}; + f.read(static_cast(buf.p), static_cast(buf_cap)); + buf.size = static_cast(f.gcount()); + f.seekg(0, std::ios::end); + if (f.peek() != std::ifstream::traits_type::eof()) + throw std::runtime_error{"secret is bigger than allowed"}; + + return std::string{trim_ws( + std::string_view{static_cast(buf.p), buf.size})}; +} + +auto server_main(routemon::log::logger& l, routemon::config::app config) + -> exit_status +{ auto lgen = routemon::locale::make_generator(); auto default_locale = lgen->generate("en_US.UTF-8"); auto locales = { @@ -39,28 +92,32 @@ auto real_main(std::span args) -> exit_status auto ioc = net::io_context{1 /* concurrency hint */}; - auto config = routemon::config::app{}; + auto dbc = std::shared_ptr{}; try { - config = routemon::config::load_file(config_filename); + dbc = routemon::database::open(config.database.sqlite3_filename); } catch (std::exception const& e) { - l.with("filename", std::string_view{config_filename}) - .error("Failed to load configuration: {}", e.what()); + l.with("filename", config.database.sqlite3_filename) + .error("Failed to open database: {}", e.what()); return exit_status::failure; } - sink->set_level(config.logger.level); - auto dbc = std::shared_ptr{}; + auto rwgps_creds = std::shared_ptr{}; try { - dbc = routemon::database::open(config.database.sqlite3_filename); + rwgps_creds.reset(new routemon::rwgps::credentials{ + // TODO: bad secrets handling. Too little information for proper error + // reporting. + read_secret_to_string<4096>(config.rwgps.api_key_filename), + read_secret_to_string<4096>(config.rwgps.api_secret_filename), + read_secret_to_string<4096>(config.rwgps.auth_token_filename), + }); } catch (std::exception const& e) { - l.with("filename", config.database.sqlite3_filename) - .error("Failed to open database: {}", e.what()); + l.error("Failed to read RWGPS credentials: {}", e.what()); return exit_status::failure; } @@ -94,7 +151,7 @@ auto real_main(std::span args) -> exit_status } } // Processing the feed is by far the most memory-intensive operation - // during the run time of this application (at the moment), the + // during the run time of this application (at the moment); the // resident set will likely never be this big again. So we ask libc // to return as much memory as possible to the OS. malloc_trim(0); @@ -103,9 +160,9 @@ auto real_main(std::span args) -> exit_status chrono::duration_cast(after_load - before_load); l.info("Loading situations finished in {}", dur_load); - auto handler = routemon::api::handler{l, std::move(pub)}; + auto handler = routemon::api::handler{l, dbc, std::move(pub)}; auto http_server = routemon::srv::server{ - l, config.http_server, std::move(lsel), std::move(handler) + l, config.http_server, rwgps_creds, std::move(lsel), std::move(handler), }; http_server.spawn(ioc); ioc.run(); @@ -114,19 +171,131 @@ auto real_main(std::span args) -> exit_status return exit_status::failure; } +auto migrate_main( + routemon::log::logger& l, routemon::config::app config, + std::int64_t target_db_version) -> exit_status +{ + auto m = std::unique_ptr{}; + try + { + m.reset( + new routemon::migrate::migrator{l, config.database.sqlite3_filename}); + } + catch (std::exception const& e) + { + l.with("filename", config.database.sqlite3_filename) + .error("Failed to open database: {}", e.what()); + return exit_status::failure; + } + + try + { + m->migrate_to(target_db_version); + } + catch (std::exception const& e) + { + l.error("Failed to migrate database: {}", e.what()); + return exit_status::failure; + } + + return exit_status::success; +} + +// Arguments not including own name (so argv[1..]). +auto real_main(std::span args) -> exit_status +{ + auto const sink = routemon::log::make_sink(routemon::log::level::info); + auto l = routemon::log::logger{sink}; + + auto load_config = [&](char const* config_filename) + -> std::expected + { + try + { + auto const config = routemon::config::load_file(config_filename); + sink->set_level(config.logger.level); + return config; + } + catch (std::exception const& e) + { + l.with("filename", std::string_view{config_filename}) + .error("Failed to load configuration: {}", e.what()); + return std::unexpected{exit_status::failure}; + } + }; + + if (args.size() <= 0) + { + l.error( + "Fatal: expected at least a subcommand argument (∈ {{migrate, " + "server}}), got {} arguments", + args.size()); + return exit_status::bad_usage; + } + + if (args[0] == "server"sv) + { + args = args.subspan<1>(); + if (args.size() != 1) + { + l.error( + "Fatal: expected exactly one argument (the configuration file " + "location), got {}", + args.size()); + return exit_status::bad_usage; + } + auto mconfig = load_config(args[0]); + if (!mconfig) + return mconfig.error(); + return server_main(l, std::move(*mconfig)); + } + else if (args[0] == "migrate"sv) + { + args = args.subspan<1>(); + if (args.size() != 2) + { + l.error( + "Fatal: expected exactly two arguments (the configuration file " + "location and database version to migrate to), got {}", + args.size()); + return exit_status::bad_usage; + } + auto mconfig = load_config(args[0]); + if (!mconfig) + return mconfig.error(); + auto mtarget_db_version = routemon::util::parse_int(args[1]); + if (!mtarget_db_version || *mtarget_db_version < 0) + { + l.error( + "Fatal: could not parse target database version ({}) as a " + "non-negative integer", + args[1]); + return exit_status::bad_usage; + } + return migrate_main(l, std::move(*mconfig), *mtarget_db_version); + } + else + { + l.error("Fatal: unrecognized subcommand {}", args[0]); + return exit_status::bad_usage; + } +} + auto main(int argc, char* argv[]) -> int { - if (argc < 0) + if (argc < 1) { - std::cout << "Fatal: argument count below zero" << std::endl; + std::cout << "Fatal: argument count below one" << std::endl; return EXIT_FAILURE; } auto res = real_main( std::span{ - const_cast(argv), static_cast(argc) + const_cast(argv + 1), static_cast(argc - 1) }); switch (res) { + case exit_status::success: + return EXIT_SUCCESS; case exit_status::failure: return EXIT_FAILURE; case exit_status::bad_usage: diff --git a/server/src/migrate.cppm b/server/src/migrate.cppm new file mode 100644 index 0000000..e5cd52a --- /dev/null +++ b/server/src/migrate.cppm @@ -0,0 +1,126 @@ +module; + +#include + +export module routemon:migrate; + +import :log; +import :sqlite3; + +namespace routemon::migrate { + +auto load_migrations(std::int64_t current_version, std::int64_t target_version) + -> std::vector +{ + if (current_version < 0 || target_version < 0) + throw std::invalid_argument{"database versions must be nonnegative"}; + if (target_version < current_version) + throw std::runtime_error{"migrating down is not supported yet"}; + if (current_version == target_version) + return {}; + assert(current_version < target_version); + + // TODO: narrow_cast or something like that + auto migration_sqls = + std::vector>>{ + static_cast(target_version - current_version) + }; + for (auto const& entry : std::filesystem::directory_iterator{"migrations"}) + { + if (!std::filesystem::is_regular_file(entry.status())) + continue; + auto const filename = std::string{entry.path().filename()}; + if (!filename.ends_with("_up.sql")) + continue; + auto const [no_str, mrest] = util::split_on(filename, '_'); + if (!mrest) + continue; + auto const mno = util::parse_int(no_str); + if (!mno || *mno < 1) + continue; + if (*mno <= current_version || target_version < *mno) + continue; + auto const i = static_cast(*mno - current_version - 1); + + if (migration_sqls[i]) + throw std::runtime_error{std::format( + "found more than one (up) migration file for version {}", *mno)}; + + auto f = std::ifstream{entry.path(), std::ios::binary}; + auto contents = std::string{ + std::istreambuf_iterator{f}, + std::istreambuf_iterator{}, + }; + + migration_sqls[i] = {entry.path(), contents}; + } + + return migration_sqls | std::views::enumerate + | std::views::transform( + [current_version](auto&& pair) -> std::string + { + auto&& [i, mentry] = pair; + if (!mentry) + throw std::runtime_error{std::format( + "no migration found to version {}", + current_version + i + 1)}; + return std::move(mentry->second); + }) + | std::ranges::to>(); +} + +export class migrator +{ + log::logger l_; + sqlite3::connection dbc_; + + auto current_version() -> std::int64_t + { + if (auto const [has_migrations_table] = + dbc_.query( + "SELECT COUNT(*) FROM sqlite_schema WHERE " + "type IS 'table' AND " + "name IS 'migration'") + .scan_row_max1(); + has_migrations_table) + return std::get<0>(dbc_.query("SELECT version FROM migration") + .scan_row_max1()); + return 0; + } + +public: + explicit migrator(log::logger const& l, std::string const& filename) + : l_{l.sub("migrator")}, dbc_{sqlite3::open(filename)} + { + } + + auto migrate_to(std::int64_t target_version) -> void + { + // Part of function contract. Consider throwing instead? + if (target_version < 0) + throw std::invalid_argument{ + "target database version must be nonnegative" + }; + + auto current = current_version(); + auto const migration_sqls = load_migrations(current, target_version); + + for (auto const& sql : migration_sqls) + { + l_.info("Migrating from schema version {} to {}", current, current + 1); + migrate_step(++current, sql); + } + } + + auto migrate_step(std::int64_t target_version, util::zstring_view sql) -> void + { + auto tx = sqlite3::tx{dbc_}; + while (!sql.empty()) + tx.exec_first(sql); + tx.exec( + "UPDATE migration SET version = :version", + [target_version](auto& s) { s.bind(":version", target_version); }); + } +}; + +} // namespace routemon::migrate diff --git a/server/src/routemon.cppm b/server/src/routemon.cppm index 62db02a..8946cf5 100644 --- a/server/src/routemon.cppm +++ b/server/src/routemon.cppm @@ -6,6 +6,7 @@ export import :datex2; export import :gpx; export import :locale; export import :log; +export import :migrate; export import :srv; export import :rwgps; export import :util; diff --git a/server/src/rwgps.cpp b/server/src/rwgps.cpp index b8ebf11..21584a8 100644 --- a/server/src/rwgps.cpp +++ b/server/src/rwgps.cpp @@ -4,6 +4,8 @@ module; #include #include +#include + module routemon:rwgps$impl; import :rwgps; @@ -14,34 +16,6 @@ namespace json = boost::json; namespace routemon::rwgps { -export struct route_summary -{ - std::int64_t id; - std::int64_t user_id; - std::string url; - std::string name; - std::string description; -}; - -struct pagination -{ - std::size_t record_count; - std::size_t page_count; - std::size_t page_size; - std::optional next_page_url; -}; - -struct get_routes_meta -{ - pagination pagination; -}; - -struct get_routes_response -{ - std::vector routes; - get_routes_meta meta; -}; - auto tag_invoke(json::value_to_tag const&, json::value const& jv) -> route_summary { @@ -91,6 +65,133 @@ auto json_value_to_get_routes_response(json::value const& jv) return json::value_to(jv); } +static json::value const json_null = json::value{}; + +auto at_or_null(json::value const& v, std::string_view key) + -> json::value const& +{ + if (v.is_null()) + return json_null; + auto const* obj = v.if_object(); + if (!obj) + throw std::system_error{make_error_code(json::error::not_object)}; + if (auto it = obj->find(key); it != obj->end()) + return it->value(); + return json_null; +} + +auto tag_invoke( + json::value_to_tag const&, json::value const& jv) + -> notification_cause +{ + if (jv == "created") + return notification_cause::created; + if (jv == "updated") + return notification_cause::updated; + if (jv == "deleted") + return notification_cause::deleted; + if (jv == "added") + return notification_cause::added; + if (jv == "removed") + return notification_cause::removed; + return notification_cause::unknown; +} + +auto tag_invoke( + json::value_to_tag const&, json::value const& jv) + -> notification_item_type +{ + if (jv == "trip") + return notification_item_type::trip; + if (jv == "route") + return notification_item_type::route; + if (jv == "event") + return notification_item_type::event; + if (jv == "event_participant") + return notification_item_type::event_participant; + if (jv == "club_member") + return notification_item_type::club_member; + if (jv == "authorization") + return notification_item_type::authorization; + return notification_item_type::unknown; +} + +auto tag_invoke( + json::value_to_tag const&, + json::value const& jv) -> notification_target_collection_type +{ + if (jv == "pinned") + return notification_target_collection_type::pinned; + return notification_target_collection_type::unknown; +} + +auto tag_invoke( + json::value_to_tag const&, + json::value const& jv) -> notification_target_collection +{ + return { + .id = json::value_to(at_or_null(jv, "id")), + .type = json::value_to( + at_or_null(jv, "type")), + .url = json::value_to>(at_or_null(jv, "url")), + }; +} + +auto tag_invoke(json::value_to_tag const&, json::value const& jv) + -> notification +{ + return { + .user_id = json::value_to(at_or_null(jv, "user_id")), + .item_type = + json::value_to(at_or_null(jv, "item_type")), + .item_id = + json::value_to>(at_or_null(jv, "item_id")), + .item_user_id = json::value_to>( + at_or_null(jv, "item_user_id")), + .item_url = + json::value_to>(at_or_null(jv, "item_url")), + .action = json::value_to(at_or_null(jv, "action")), + .collection = json::value_to>( + at_or_null(jv, "collection")), + }; +} + +auto tag_invoke( + json::value_to_tag const&, json::value const& jv) + -> webhook_request +{ + return { + .notifications = json::value_to>( + at_or_null(jv, "notifications")), + }; +} + +credentials::credentials( + std::string&& api_key, std::string&& api_secret, std::string&& auth_token) + : api_key_{std::move(api_key)}, api_secret_{std::move(api_secret)}, + auth_token_{std::move(auth_token)} +{ +} + +credentials::~credentials() +{ + OPENSSL_cleanse(api_key_.data(), api_key_.capacity()); + OPENSSL_cleanse(api_secret_.data(), api_secret_.capacity()); + OPENSSL_cleanse(auth_token_.data(), auth_token_.capacity()); +} + +auto credentials::api_key() const -> std::string const& { return api_key_; } + +auto credentials::api_secret() const -> std::string const& +{ + return api_secret_; +} + +auto credentials::auth_token() const -> std::string const& +{ + return auth_token_; +} + constexpr std::string host = "ridewithgps.com"; // TODO: handle failure appropriately @@ -102,8 +203,8 @@ auto client::get_routes_page(std::size_t page) -> get_routes_response 11, // HTTP 1.1 }; req.set(bhttp::field::host, host); - req.set("x-rwgps-api-key", api_key_); - req.set("x-rwgps-auth-token", auth_token_); + req.set("x-rwgps-api-key", creds_->api_key()); + req.set("x-rwgps-auth-token", creds_->auth_token()); auto rsp = hc_.do_request(req); auto p = json::stream_parser{}; @@ -114,10 +215,9 @@ auto client::get_routes_page(std::size_t page) -> get_routes_response } client::client( - net::io_context& ioc, log::logger const& l, std::string api_key, - std::string auth_token) - : l_{l.sub("rwgps-client")}, hc_{ioc}, api_key_{std::move(api_key)}, - auth_token_{std::move(auth_token)} + net::io_context& ioc, log::logger const& l, + std::shared_ptr creds) + : l_{l.sub("rwgps-client")}, hc_{ioc}, creds_{std::move(creds)} { } diff --git a/server/src/rwgps.cppm b/server/src/rwgps.cppm index 2ed124e..880ea3a 100644 --- a/server/src/rwgps.cppm +++ b/server/src/rwgps.cppm @@ -1,6 +1,7 @@ module; #include +#include export module routemon:rwgps; @@ -9,6 +10,7 @@ import :http.client; import :log; namespace net = boost::asio; +namespace json = boost::json; namespace routemon::rwgps { @@ -21,6 +23,62 @@ export struct route_summary std::string description; }; +enum class notification_cause +{ + unknown, + created, + updated, + deleted, + added, + removed, +}; + +enum class notification_item_type +{ + unknown, + trip, + route, + event, + event_participant, + club_member, + authorization, +}; + +enum notification_target_collection_type +{ + unknown, + pinned, +}; + +struct notification_target_collection +{ + std::int64_t id; + notification_target_collection_type type; + std::optional url; +}; + +struct notification +{ + // User that took the action + std::int64_t user_id; + notification_item_type item_type; + std::optional item_id; + // User that owns the item + std::optional item_user_id; + std::optional item_url; + notification_cause action; + std::optional collection; +}; + +struct webhook_request +{ + std::vector notifications = {}; +}; + +auto tag_invoke( + json::value_to_tag const&, json::value const& jv) + -> webhook_request; + struct pagination { std::size_t record_count; @@ -40,19 +98,35 @@ struct get_routes_response get_routes_meta meta; }; +export class credentials +{ + std::string api_key_; + std::string api_secret_; + std::string auth_token_; + +public: + credentials( + std::string&& api_key, std::string&& api_secret, + std::string&& auth_token); + ~credentials(); + + auto api_key() const -> std::string const&; + auto api_secret() const -> std::string const&; + auto auth_token() const -> std::string const&; +}; + export class client { log::logger l_; http::client hc_; - std::string api_key_; - std::string auth_token_; + std::shared_ptr creds_; auto get_routes_page(std::size_t page) -> get_routes_response; public: explicit client( - net::io_context& ioc, log::logger const& l, std::string api_key, - std::string auth_token); + net::io_context& ioc, log::logger const& l, + std::shared_ptr creds); auto get_all_routes() -> std::vector; }; diff --git a/server/src/rwgps_webhook.cppm b/server/src/rwgps_webhook.cppm new file mode 100644 index 0000000..5a1df37 --- /dev/null +++ b/server/src/rwgps_webhook.cppm @@ -0,0 +1,237 @@ +module; + +#include +#include +#include +#include + +#include +#include +#include + +export module routemon:rwgps.webhook; + +import :http.common; +import :util; +import std; + +namespace { + +namespace net = boost::asio; +namespace json = boost::json; + +} // namespace + +namespace routemon::rwgps::webhook { + +// TODO: constrain T? What are appropriate constraints? +template +class hmac_readable +{ + std::string_view key_; + std::optional> mac_; + T res_; + + template + friend struct hmac_body_reader; + +public: + template + explicit hmac_readable(std::string_view key, Args&&... args) + : key_{key}, res_{std::forward(args)...} + { + } + + template + constexpr auto get(this Self&& self) -> auto&& + { + return std::forward(self).res_; + } + + auto mac() const -> std::optional> + { + return mac_; + } +}; + +template +class hmac_body_reader +{ + EVP_MAC* mac_ = nullptr; + EVP_MAC_CTX* ctx_ = nullptr; + + util::not_null*> v_; + Sub::reader subr_; + beast::error_code ec_; + +public: + template + explicit hmac_body_reader( + bhttp::header& h, + hmac_readable& v) + : v_{util::not_null{&v}}, + subr_{h, v.get()} // we are not supposed to use v yet, but this just + // computes an address, so it should be fine + { + } + + ~hmac_body_reader() + { + ::EVP_MAC_CTX_free(ctx_); + ::EVP_MAC_free(mac_); + } + + // TODO: move to impl. unit. + auto init(boost::optional n, beast::error_code& ec) noexcept + -> void + { + // https://docs.openssl.org/master/man3/EVP_MAC/#examples + mac_ = ::EVP_MAC_fetch(nullptr, "HMAC", nullptr); + if (!mac_) + { + ec_ = ec = make_error_code(std::errc::not_enough_memory); + return; + } + + ctx_ = ::EVP_MAC_CTX_new(mac_); + if (!ctx_) + { + ec_ = ec = make_error_code(std::errc::not_enough_memory); + return; + } + + char sha256[] = "SHA256"; + ::OSSL_PARAM const params[] = { + OSSL_PARAM_utf8_string("digest", sha256, sizeof(sha256) - 1), + OSSL_PARAM_END + }; + if (!::EVP_MAC_init( + ctx_, reinterpret_cast(v_->key_.data()), + v_->key_.size(), params)) + { + ec_ = ec = beast::error_code{ + static_cast(::ERR_get_error()), net::error::get_ssl_category() + }; + return; + } + + subr_.init(n, ec); + } + + auto + put(beast::concepts::const_buffer_sequence auto b, + beast::error_code& ec) noexcept -> std::size_t + { + if ((ec = ec_)) + return 0uz; + + auto const total_read = subr_.put(b, ec); + if (total_read > 0) + { + auto remaining = total_read; + for (auto const buf : beast::buffers_range(b)) + { + auto const to_hash_from_this_buf = std::min(remaining, buf.size()); + if (!::EVP_MAC_update( + ctx_, static_cast(buf.data()), + to_hash_from_this_buf)) + { + ec_ = ec = beast::error_code{ + static_cast(::ERR_get_error()), net::error::get_ssl_category() + }; + return total_read; + } + remaining -= to_hash_from_this_buf; + } + } + return total_read; + } + + auto finish(beast::error_code& ec) noexcept + { + auto got_mac_len = 0uz; + auto got_mac = std::array{}; + if (!::EVP_MAC_final(ctx_, got_mac.data(), &got_mac_len, got_mac.size())) + { + ec = beast::error_code{ + static_cast(::ERR_get_error()), net::error::get_ssl_category() + }; + return; + } + assert(got_mac_len == got_mac.size()); + v_->mac_ = got_mac; + subr_.finish(ec); + } +}; + +template +struct hmac_body +{ + using value_type = hmac_readable; +}; + +template + requires bhttp::concepts::body_reader +struct hmac_body +{ + using value_type = hmac_readable; + + using reader = hmac_body_reader; +}; + +struct json_body +{ + using value_type = json::value; + + class reader + { + json::stream_parser p_; + util::not_null v_; + + public: + template + explicit reader(bhttp::header&, value_type& v) + : v_{util::not_null{&v}} + { + } + + // TODO: move to impl. unit. + auto + init(boost::optional /* n */, beast::error_code& ec) noexcept + -> void + { + p_.reset(); + ec = {}; + } + + auto + put(beast::concepts::const_buffer_sequence auto b, + beast::error_code& ec) noexcept -> std::size_t + { + ec = {}; + + auto wrote = 0uz; + for (auto const buf : beast::buffers_range(b)) + { + p_.write(static_cast(buf.data()), buf.size(), ec); + wrote += buf.size(); + if (ec) + break; + } + return wrote; + } + + auto finish(beast::error_code& ec) noexcept + { + p_.finish(ec); + if (ec) + return; + *v_ = p_.release(); + } + }; +}; + +static_assert(bhttp::concepts::body>); +static_assert(bhttp::concepts::body_reader>); + +} // namespace routemon::rwgps::webhook diff --git a/server/src/sqlite3.cpp b/server/src/sqlite3.cpp index 3e0d64a..243cf41 100644 --- a/server/src/sqlite3.cpp +++ b/server/src/sqlite3.cpp @@ -8,23 +8,28 @@ import :sqlite3; namespace routemon::sqlite3 { -mutex_guard::mutex_guard(::sqlite3_mutex* mut) noexcept : mut_{mut} {} - -mutex_guard::~mutex_guard() { ::sqlite3_mutex_leave(mut_); } - -auto do_guarded(::sqlite3_mutex* mut, std::invocable auto f) - -> decltype(f(std::declval())) +mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc} { - return f(mutex_guard{mut}); + ::sqlite3_mutex_enter(::sqlite3_db_mutex(dbc_)); } -auto do_guarded(::sqlite3* dbc, std::invocable auto f) - -> decltype(f(std::declval())) +mutex_guard::~mutex_guard() { - return do_guarded(::sqlite3_db_mutex(dbc), f); + if (dbc_) + ::sqlite3_mutex_leave(::sqlite3_db_mutex(dbc_)); } -error::error(mutex_guard const&, int code, ::sqlite3* dbc) +// auto do_guarded(::sqlite3* dbc, std::invocable auto f, +// std::optional malready_locked = std::nullopt) +// -> decltype(f(std::declval())) +// { +// if (auto const mguard = malready_locked) +// return f(*mguard); +// else +// return f(mutex_guard{dbc}); +// } + +error::error(int code, ::sqlite3* dbc) : code_{code}, message_{::sqlite3_errmsg(dbc)} { } @@ -38,161 +43,234 @@ error::error(int code) : code_{code}, message_{::sqlite3_errstr(code)} {} [[nodiscard]] auto error::code() const noexcept -> int { return code_; } -statement::statement(::sqlite3_stmt* stmt) : stmt_{stmt} {} -statement::statement(statement&& s) noexcept +locked_statement::locked_statement( + ::sqlite3_stmt* stmt, std::shared_ptr dbc_locked) + : stmt_{stmt}, guard_{std::move(dbc_locked)} +{ + if (!guard_) + throw std::invalid_argument{"mutex guard may not be null"}; + if (!guard_->for_db(::sqlite3_db_handle(stmt_))) + throw std::invalid_argument{ + "provided mutex guard does not apply to statement's database" + }; +} +locked_statement::locked_statement(locked_statement&& rhs) noexcept + : stmt_{std::exchange(rhs.stmt_, nullptr)}, guard_{std::move(rhs.guard_)} { - stmt_ = s.stmt_; - s.stmt_ = nullptr; } -statement::~statement() { ::sqlite3_finalize(stmt_); } -auto statement::get() -> ::sqlite3_stmt* { return stmt_; } +locked_statement::~locked_statement() +{ + if (stmt_) + ::sqlite3_finalize(stmt_); +} -row_reader::row_reader(statement stmt) : stmt_{std::move(stmt)} {} +row_reader::row_reader(locked_statement&& stmt) : stmt_{std::move(stmt)} {} auto row_reader::is_null(int col) -> bool { - return ::sqlite3_column_type(stmt_.get(), col) == SQLITE_NULL; + return ::sqlite3_column_type(stmt_.stmt_, col) == SQLITE_NULL; } auto row_reader::ncols() -> std::size_t { - auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.get())); + auto const mncols = util::size_from_int(::sqlite3_data_count(stmt_.stmt_)); if (!mncols.has_value()) throw std::logic_error{"got unexpected negative amount of columns"}; return *mncols; } -auto row_reader::scan(int col, std::string& s) -> void +auto row_reader::scan_col(int col, std::string& s) -> void { - if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_TEXT) + if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_TEXT) throw std::invalid_argument{"invalid type for scan"}; - unsigned char const* chs = ::sqlite3_column_text(stmt_.get(), col); - auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.get(), col)); + unsigned char const* chs = ::sqlite3_column_text(stmt_.stmt_, col); + auto size = util::size_from_int(::sqlite3_column_bytes(stmt_.stmt_, col)); if (!size.has_value()) throw std::logic_error{"unexpected negative amount of bytes in column"}; s = std::string{reinterpret_cast(chs), *size}; } -auto row_reader::scan(int col, double& v) -> void +auto row_reader::scan_col(int col, double& v) -> void { - if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_FLOAT) + if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_FLOAT) throw std::invalid_argument{"invalid type for scan"}; - v = ::sqlite3_column_double(stmt_.get(), col); + v = ::sqlite3_column_double(stmt_.stmt_, col); } -auto row_reader::scan(int col, std::int64_t& v) -> void +auto row_reader::scan_col(int col, std::int64_t& v) -> void { - if (::sqlite3_column_type(stmt_.get(), col) != SQLITE_INTEGER) + if (::sqlite3_column_type(stmt_.stmt_, col) != SQLITE_INTEGER) throw std::invalid_argument{"invalid type for scan"}; - v = ::sqlite3_column_int64(stmt_.get(), col); + v = ::sqlite3_column_int64(stmt_.stmt_, col); } auto row_reader::next() -> bool { - ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.get()); - return do_guarded( - dbc, - [&](auto const& guard) -> bool - { - auto const s = ::sqlite3_step(stmt_.get()); - if (s == SQLITE_ROW) - return true; - if (s == SQLITE_DONE) - return false; - throw error{guard, s, dbc}; - }); + ::sqlite3* dbc = ::sqlite3_db_handle(stmt_.stmt_); + auto const s = ::sqlite3_step(stmt_.stmt_); + if (s == SQLITE_ROW) + return true; + if (s == SQLITE_DONE) + return false; + throw error{s, dbc}; } -binder::binder(statement& stmt) : stmt_{stmt} {} +statement::statement(locked_statement&& stmt) : stmt_{std::move(stmt)} {} -auto binder::text(std::string const& param_name, std::string_view str) -> void +auto statement::param_idx(util::zstring_view name) -> int { - int const i = ::sqlite3_bind_parameter_index(stmt_.get(), param_name.c_str()); + int const i = ::sqlite3_bind_parameter_index(stmt_.stmt_, name.c_str()); if (i == 0) throw std::invalid_argument{std::format( - "bind: no parameter with name {} found", param_name)}; + "bind: no parameter with name {} found", name)}; + return i; +} + +auto statement::bind_null(util::zstring_view param_name) -> statement& +{ + if (auto s = ::sqlite3_bind_null(stmt_.stmt_, param_idx(param_name)); + s != SQLITE_OK) + throw error{s}; + return *this; +} + +auto statement::bind(util::zstring_view param_name, std::string_view str) + -> statement& +{ auto str_size = util::int_from_size(str.size()); if (!str_size.has_value()) throw std::invalid_argument{"bind: provided text is too long"}; if (auto s = ::sqlite3_bind_text( - stmt_.get(), i, str.data(), *str_size, SQLITE_TRANSIENT); + stmt_.stmt_, param_idx(param_name), str.data(), *str_size, + SQLITE_TRANSIENT); s != SQLITE_OK) - { throw error{s}; - } + return *this; } -auto binder::noop(binder&) -> void {} +auto statement::bind(util::zstring_view param_name, std::int64_t x) + -> statement& +{ + if (auto s = ::sqlite3_bind_int64(stmt_.stmt_, param_idx(param_name), x); + s != SQLITE_OK) + throw error{s}; + return *this; +} + +auto statement::bind( + util::zstring_view param_name, std::optional mstr) + -> statement& +{ + if (mstr) + return bind(param_name, *mstr); + else + return bind_null(param_name); +} + +auto statement::bind( + util::zstring_view param_name, std::optional mx) -> statement& +{ + if (mx) + return bind(param_name, *mx); + else + return bind_null(param_name); +} -connection::connection(::sqlite3* dbc) - : dbc_{dbc}, mut_{::sqlite3_db_mutex(dbc)} +auto statement::into_reader() && -> row_reader { + return row_reader{std::move(stmt_)}; } -connection::connection(connection const&) = delete; +auto noop_binder(statement&) -> void {} + +connection::connection(::sqlite3* dbc) : dbc_{dbc} {} + connection::connection(connection&& c) noexcept { dbc_ = c.dbc_; - mut_ = c.mut_; c.dbc_ = nullptr; - c.mut_ = nullptr; } -auto connection::query( - std::string const& sql, std::function const& bf) - -> row_reader +auto prepare( + ::sqlite3* dbc, util::zstring_view& sql, + std::shared_ptr guard = nullptr) -> std::optional { + if (guard && !guard->for_db(dbc)) + throw std::invalid_argument{ + "provided mutex guard does not apply to provided database" + }; + if (!guard) + guard.reset(new mutex_guard{dbc}); ::sqlite3_stmt* pstmt = nullptr; char const* sql_tail = nullptr; - auto sql_size = util::int_from_size(sql.size()); - if (!sql_size.has_value() || *sql_size >= std::numeric_limits::max() - 1) + auto sql_len = util::int_from_size(sql.length()); + if (!sql_len.has_value() || *sql_len >= std::numeric_limits::max() - 1) throw std::invalid_argument{"provided input text too large"}; - do_guarded( - mut_, - [&](auto const& guard) -> void - { - if (auto s = ::sqlite3_prepare_v2( - dbc_, sql.data(), *sql_size + 1, &pstmt, &sql_tail); - s != SQLITE_OK) - { - if (pstmt != nullptr) - { - // Use contract_assert when having a compiler with - // contracts available - ::sqlite3_finalize(pstmt); - throw std::logic_error{ - "expected stmt to be null after failed preparation" - }; - } - throw error{guard, s, dbc_}; - } - }); + if (auto s = ::sqlite3_prepare_v2( + dbc, sql.c_str(), *sql_len + 1, &pstmt, &sql_tail); + s != SQLITE_OK) + { + if (pstmt) + { + // Use contract_assert when having a compiler with + // contracts available + ::sqlite3_finalize(pstmt); + throw std::logic_error{ + "expected stmt to be null after failed preparation" + }; + } + throw error{s, dbc}; + } if (!pstmt) + return std::nullopt; + if (sql_tail < sql || sql_tail > sql + sql.length()) + throw std::runtime_error{"expected SQL tail to be non-null"}; + sql = util::zstring_view{ + sql_tail, sql.length() - static_cast(sql_tail - sql.c_str()) + }; + return statement{locked_statement{pstmt, std::move(guard)}}; +} + +auto do_query( + ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf, + std::shared_ptr guard = nullptr) -> row_reader +{ + auto mstmt = prepare(dbc, sql, std::move(guard)); + if (!mstmt) throw std::invalid_argument{"provided input text contains no SQL"}; - auto stmt = statement{pstmt}; - if (sql_tail && std::strlen(sql_tail) > 0) + if (sql.length() > 0) // what remains after querying throw std::invalid_argument{ "provided input text contains more than one SQL statement" }; - auto b = binder{stmt}; - bf(b); - return row_reader{std::move(stmt)}; + bf(*mstmt); + return std::move(*mstmt).into_reader(); } -auto connection::exec( - std::string const& sql, std::function const& bf) -> void +auto do_exec( + ::sqlite3* dbc, util::zstring_view sql, bindfn const& bf, + std::shared_ptr guard = nullptr) -> void { - auto reader = query(sql, bf); + auto reader = do_query(dbc, sql, bf, std::move(guard)); while (reader.next()) ; } +auto connection::query(util::zstring_view sql, bindfn const& bf) -> row_reader +{ + return do_query(dbc_, sql, bf); +} + +auto connection::exec(util::zstring_view sql, bindfn const& bf) -> void +{ + return do_exec(dbc_, sql, bf); +} + connection::~connection() { std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); } -auto open(std::string const& filename) -> connection +auto open(util::zstring_view filename) -> connection { ::sqlite3* dbc = nullptr; auto s = ::sqlite3_open_v2( @@ -204,15 +282,71 @@ auto open(std::string const& filename) -> connection { if (dbc) { - do_guarded( - dbc, [&](auto const& guard) -> void { throw error{guard, s, dbc}; }); + throw error{s, dbc}; } else { throw error{s}; } } - return connection{dbc}; + auto w = connection{dbc}; + w.exec("PRAGMA foreign_keys = ON"); + return w; +} + +tx::tx(connection& dbc) + : dbc_{util::not_null{&dbc}}, + guard_{std::make_shared(dbc_->dbc_)} +{ + exec("BEGIN"); +} + +[[nodiscard]] auto tx::query(util::zstring_view sql, bindfn const& bf) + -> row_reader +{ + try + { + return do_query(dbc_->dbc_, sql, bf, guard_); + } + catch (std::exception const&) + { + commit_ = false; + throw; + } +} + +auto tx::exec(util::zstring_view sql, bindfn const& bf) -> void +{ + try + { + do_exec(dbc_->dbc_, sql, bf, guard_); + } + catch (std::exception const&) + { + commit_ = false; + throw; + } +} + +auto tx::exec_first(util::zstring_view& sql) -> void +{ + try + { + auto mstmt = prepare(dbc_->dbc_, sql, guard_); + if (!mstmt) + { + sql = util::zstring_view{sql.c_str() + sql.length(), 0}; + return; + } + auto reader = std::move(*mstmt).into_reader(); + while (reader.next()) + ; + } + catch (std::exception const&) + { + commit_ = false; + throw; + } } } // namespace routemon::sqlite3 diff --git a/server/src/sqlite3.cppm b/server/src/sqlite3.cppm index b771c49..3348b0b 100644 --- a/server/src/sqlite3.cppm +++ b/server/src/sqlite3.cppm @@ -28,18 +28,17 @@ concept scannable = scannable_prim || optional_of; class mutex_guard { - explicit mutex_guard(::sqlite3_mutex* mut) noexcept; - - friend auto - do_guarded(::sqlite3_mutex* mut, std::invocable auto f) - -> decltype(f(std::declval())); + ::sqlite3* dbc_; public: + explicit mutex_guard(::sqlite3* dbc) noexcept; mutex_guard(mutex_guard const&) = delete; + mutex_guard(mutex_guard&& rhs) = delete; + auto operator=(mutex_guard const&) -> mutex_guard& = delete; + auto operator=(mutex_guard&& rhs) -> mutex_guard& = delete; ~mutex_guard(); -private: - ::sqlite3_mutex* mut_; + auto for_db(::sqlite3 const* dbc) const -> bool { return dbc_ == dbc; } }; class error : public std::exception @@ -48,40 +47,68 @@ class error : public std::exception std::string message_; public: - explicit error(mutex_guard const&, int code, ::sqlite3* dbc); + explicit error(int code, ::sqlite3* dbc); explicit error(int code); [[nodiscard]] auto what() const noexcept -> char const* override; [[nodiscard]] auto code() const noexcept -> int; }; -class statement +class statement; +class row_reader; + +// TODO: make consumable and mark release_guard only callable when unconsumed? +// Same might have to for release_guard in row_reader. +class locked_statement { ::sqlite3_stmt* stmt_; + std::shared_ptr guard_; + + friend class statement; + friend class row_reader; + +public: + explicit locked_statement( + ::sqlite3_stmt* stmt, std::shared_ptr dbc_locked); + locked_statement(locked_statement const&) = delete; + locked_statement(locked_statement&& s) noexcept; + ~locked_statement(); +}; + +class statement +{ + locked_statement stmt_; + + auto param_idx(util::zstring_view name) -> int; + auto bind_null(util::zstring_view param_name) -> statement&; public: - explicit statement(::sqlite3_stmt* stmt); - statement(statement const&) = delete; - statement(statement&& s) noexcept; - ~statement(); - auto get() -> ::sqlite3_stmt*; + explicit statement(locked_statement&& stmt); + + auto bind(util::zstring_view param_name, std::string_view str) -> statement&; + auto bind(util::zstring_view param_name, std::int64_t x) -> statement&; + auto bind(util::zstring_view param_name, std::optional str) + -> statement&; + auto bind(util::zstring_view param_name, std::optional x) + -> statement&; + auto into_reader() && -> row_reader; }; class row_reader { - statement stmt_; + locked_statement stmt_; - explicit row_reader(statement stmt); + friend class statement; - friend class connection; + explicit row_reader(locked_statement&& stmt); auto is_null(int col) -> bool; auto ncols() -> std::size_t; - auto scan(int col, std::string& s) -> void; - auto scan(int col, double& v) -> void; - auto scan(int col, std::int64_t& v) -> void; - auto scan(int col, optional_of auto& v) -> void + auto scan_col(int col, std::string& s) -> void; + auto scan_col(int col, double& v) -> void; + auto scan_col(int col, std::int64_t& v) -> void; + auto scan_col(int col, optional_of auto& v) -> void { if (is_null(col)) { @@ -90,7 +117,7 @@ class row_reader else { typename std::remove_cvref_t::value_type tmp; - scan(col, tmp); + scan_col(col, tmp); v = std::move(tmp); } } @@ -105,10 +132,19 @@ public: "more scanning arguments provided than columns in result set" }; auto col = 0; - (..., scan(col++, args)); + (..., scan_col(col++, args)); } - auto scan_single(scannable auto&... args) -> void + template + auto scan() -> std::tuple + { + std::tuple res; + auto& [... elems] = res; + scan(elems...); + return res; + } + + auto scan_row_max1(scannable auto&... args) -> void { if (!next()) throw std::logic_error{"no row in result set"}; @@ -118,46 +154,69 @@ public: throw std::logic_error{"more than one row in result set"}; } } -}; - -class binder -{ - statement& stmt_; - explicit binder(statement& stmt); + template + auto scan_row_max1() -> std::tuple + { + std::tuple res; + auto& [... elems] = res; + scan_row_max1(elems...); + return res; + } +}; - friend class connection; +// TODO: consider making this a concept instead. +using bindfn = std::functionvoid>; -public: - auto text(std::string const& param_name, std::string_view str) -> void; - - static auto noop(binder&) -> void; -}; +auto noop_binder(statement&) -> void; export class connection { ::sqlite3* dbc_; - ::sqlite3_mutex* mut_; explicit connection(::sqlite3* dbc); - friend auto open(std::string const& filename) -> connection; + friend auto open(util::zstring_view filename) -> connection; + friend class tx; public: connection(connection const&) = delete; connection(connection&& c) noexcept; - [[nodiscard]] auto query( - std::string const& sql, - std::function const& bf = binder::noop) -> row_reader; + [[nodiscard]] auto + query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; - auto exec( - std::string const& sql, - std::function const& bf = binder::noop) -> void; + auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; ~connection(); }; -export auto open(std::string const& filename) -> connection; +// TODO: define behavior when user issues queries that affect the +// transaction itself. +export class tx +{ + bool commit_ = true; + util::not_null dbc_; + std::shared_ptr guard_; + +public: + explicit tx(connection& dbc); + + ~tx() + { + if (commit_) + exec("COMMIT"); + else + exec("ROLLBACK"); + } + + [[nodiscard]] auto + query(util::zstring_view sql, bindfn const& bf = noop_binder) -> row_reader; + + auto exec(util::zstring_view sql, bindfn const& bf = noop_binder) -> void; + auto exec_first(util::zstring_view& sql) -> void; +}; + +export auto open(util::zstring_view filename) -> connection; } // namespace routemon::sqlite3 diff --git a/server/src/srv.cpp b/server/src/srv.cpp index 5de0fc5..287f838 100644 --- a/server/src/srv.cpp +++ b/server/src/srv.cpp @@ -13,11 +13,14 @@ module; #include +#include + module routemon:srv$impl; import std; import :gpx; import :srv; +import :rwgps.webhook; namespace beast = boost::beast; namespace chrono = std::chrono; @@ -330,9 +333,10 @@ struct raw_deflate_body }; }; -auto parse_timestamp(std::string_view in) -> std::optional +auto parse_timestamp_mins(std::string_view in) + -> std::optional> { - auto res = time::timestamp{}; + auto res = time::timestamp{}; auto is = std::istringstream{in}; is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res); return is.fail() ? std::nullopt : std::make_optional(res); @@ -344,13 +348,13 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) auto l = l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string()); - auto cp_begin = time::timestamp{}; - auto cp_end = time::timestamp{}; + auto cp_begin = time::timestamp{}; + auto cp_end = time::timestamp{}; auto const params = ctx.target.params(); if (auto it = params.find("cpbegin"); it != params.end()) { - auto mts = parse_timestamp((*it).value); + auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ @@ -390,7 +394,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) } if (auto it = params.find("cpend"); it != params.end()) { - auto mts = parse_timestamp((*it).value); + auto mts = parse_timestamp_mins((*it).value); if (!mts) { auto tpl = problem::tpl{ @@ -442,7 +446,7 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) "Begin of check period must be before end of check period")), http::keep_alive{false}); } - auto cp = time::period{cp_begin, cp_end}; + auto cp = time::period{cp_begin, cp_end}; auto gpx_file = gpx::file{}; try @@ -487,7 +491,8 @@ auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r) // TODO: catch handler exceptions and return 500 when raised? // (keep-alive depends on whether whole request was read) auto mres = inner_.process_gpx( - ctx.trace_id, std::move(gpx_file), time::period_seq{cp}); + ctx.trace_id, std::move(gpx_file), + time::period_seq{cp}); if (!mres) { auto tpl = problem::tpl{ @@ -521,8 +526,109 @@ auto handler::handle_sysinfo(l0_ctx ctx, http::readable_request r) co_return rsp; } -handler::handler(log::logger const& l, api::handler&& inner) - : l_{l.sub("handler")}, inner_{std::move(inner)} +auto decode_hexnib(char c) -> std::optional +{ + if ('a' <= c && c <= 'f') + return c - 'a' + 10; + if ('A' <= c && c <= 'F') + return c - 'A' + 10; + if ('0' <= c && c <= '9') + return c - '0'; + return std::nullopt; +} + +auto parse_timestamp_secs(std::string_view in) + -> std::optional> +{ + auto res = time::timestamp{}; + auto is = std::istringstream{in}; + is >> std::chrono::parse("%FT%TZ", res); + return is.fail() ? std::nullopt : std::make_optional(res); +} + +auto handler::handle_rwgps_webhook(l0_ctx ctx, http::readable_request r) + -> net::awaitable +{ + if (r.p->get()[bhttp::field::content_type] != "application/json") + { + // TODO: 415 Unsupported Media Type + // (respond Accept-Post: application/json) + throw std::runtime_error{"unhandled: unsupported media type provided"}; + } + + auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]); + if (!mrwgps_ts) + { + // TODO: 400 Bad Request + throw std::runtime_error{ + "failed to parse ISO 8601 date/time in x-rwgps-datetime header" + }; + } + + // TODO: better to instead copy the expected API key to a buffer of + // (at least) the size of the input API key and to compare those two + // buffers? Then this operation should be Ω/Θ(API key provided in + // request) + auto req_api_key = r.p->get()["x-rwgps-api-key"]; + auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X'); + std::memcpy( + req_api_key_copy.data(), req_api_key.data(), + std::min(req_api_key.size(), rwgps_creds_->api_key().size())); + + if (CRYPTO_memcmp( + req_api_key_copy.data(), rwgps_creds_->api_key().data(), + rwgps_creds_->api_key().size())) + { + // TODO: Unauthorized + // TODO: constant-time comparison + throw std::runtime_error{"unhandled: mismatching API key provided"}; + } + + auto rwgps_sig = r.p->get()["x-rwgps-signature"]; + auto rwgps_sig_decoded = std::array{}; + + if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size()) + { + // TODO: Bad request + throw std::runtime_error{"unhandled: bad signature provided"}; + } + + for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate) + { + auto mhi = decode_hexnib(rwgps_sig[static_cast(i) * 2]); + auto mlo = decode_hexnib(rwgps_sig[static_cast(i) * 2 + 1]); + if (!mhi || !mlo) + { + throw std::runtime_error{"TODO: INVALID SIGNATURE"}; + } + static_assert(std::same_as); + b = static_cast((*mhi << 4) | *mlo); + } + + auto req = co_await http:: + read_request>( + ctx, std::move(r), rwgps_creds_->api_secret()); + + if (req.body().mac() != rwgps_sig_decoded) + { + throw std::runtime_error{"unhandled: incorrect signature provided"}; + } + + // TODO: handle conversion failure gracefully + inner_.rwgps_webhook( + *mrwgps_ts, json::value_to(req.body().get())); + + auto rsp = http::make_rsp( + bhttp::status::ok, http::keep_alive{true}); + rsp.prepare_payload(); + co_return rsp; +} + +handler::handler( + log::logger const& l, api::handler&& inner, + std::shared_ptr rwgps_creds) + : l_{l.sub("handler")}, inner_{std::move(inner)}, + rwgps_creds_{std::move(rwgps_creds)} { } @@ -536,11 +642,15 @@ auto handler::make_routes() -> http::route_tree> .post = handler(&handler::handle_process_gpx), }} .no_subtrees()}, - {"sysinfo", http::dtree{ - { - .get = handler(&handler::handle_sysinfo), - } - }.no_subtrees()}, + {"sysinfo", http::dtree{{ + .get = handler(&handler::handle_sysinfo), + }} + .no_subtrees()}, + {"webhook", http::dtree{}.named_subtrees({ + {"rwgps", http::dtree{ + {.post = handler(&handler::handle_rwgps_webhook)} + }.no_subtrees()}, + })}, }); } @@ -557,8 +667,9 @@ auto server::make_global_middleware(config::http_server const& cfg) server::server( log::logger const& l, config::http_server const& cfg, - locale::selector&& lsel, api::handler&& inner) - : handler_{l, std::move(inner)}, + std::shared_ptr rwgps_creds, locale::selector&& lsel, + api::handler&& inner) + : handler_{l, std::move(inner), std::move(rwgps_creds)}, srv_{ l, http::router{ diff --git a/server/src/srv.cppm b/server/src/srv.cppm index b06dc3b..2a389c9 100644 --- a/server/src/srv.cppm +++ b/server/src/srv.cppm @@ -6,6 +6,7 @@ export module routemon:srv; import :api; import :http.server; +import :rwgps; namespace routemon::srv { @@ -13,6 +14,7 @@ class handler { log::logger l_; api::handler inner_; + std::shared_ptr rwgps_creds_; public: using outer_ctx = http::base_ctx; @@ -25,8 +27,13 @@ private: auto handle_sysinfo(l0_ctx ctx, http::readable_request r) -> net::awaitable; + auto handle_rwgps_webhook(l0_ctx ctx, http::readable_request r) + -> net::awaitable; + public: - handler(log::logger const& l, api::handler&& inner); + handler( + log::logger const& l, api::handler&& inner, + std::shared_ptr rwgps_creds); auto make_routes() -> http::route_tree>; }; @@ -42,7 +49,8 @@ export class server public: server( log::logger const& l, config::http_server const& cfg, - locale::selector&& lsel, api::handler&& inner); + std::shared_ptr rwgps_creds, locale::selector&& lsel, + api::handler&& inner); auto spawn(net::io_context& ioc) -> void; }; diff --git a/server/src/time.cpp b/server/src/time.cpp index 8f99dd2..9849761 100644 --- a/server/src/time.cpp +++ b/server/src/time.cpp @@ -2,172 +2,11 @@ module routemon:time$impl; import :time; -export namespace routemon::time { +namespace routemon::time { -using timestamp = std::chrono::time_point; - -period::period(timestamp start, timestamp end) : start_{start}, end_{end} -{ - if (start >= end) - { - throw std::invalid_argument("period: start should be before end"); - } -} - -auto period::intersect(period other) const -> std::optional -{ - auto const new_start = start_ < other.start() ? other.start() : start_; - auto const new_end = other.end() < end_ ? other.end() : end_; - return new_start < new_end ? std::make_optional(period{new_start, new_end}) - : std::nullopt; -} - -auto period::except(period other) const - -> std::pair, std::optional> -{ - auto const before_start = start_; - auto const before_end = other.start(); - auto const after_start = end_; - auto const after_end = other.end(); - std::optional before, after; - if (before_start < before_end) - before = period{before_start, before_end}; - if (after_start < after_end) - after = period{after_end, after_start}; - return std::make_pair(before, after); -} - -auto period::start() const -> timestamp { return start_; } -auto period::end() const -> timestamp { return end_; } - -period_seq::period_seq(std::vector periods) - : periods_{std::move(periods)} -{ - for (auto i = 0uz; i < periods_.size(); i++) - { - if (i + 1 < periods_.size()) - { - if (periods_[i].end() >= periods_[i + 1].start()) - { - throw std::logic_error{"period_seq: vector provided to private " - "constructor not ordered properly"}; - } - } - } -} - -period_seq::period_seq(period singleton) : periods_{singleton} {} - -auto period_seq::intersect(period_seq const& other) const -> period_seq -{ - auto it1 = periods_.begin(); - auto end1 = periods_.end(); - auto it2 = other.periods_.begin(); - auto end2 = other.periods_.end(); - - auto res = std::vector{}; - while (it1 != end1 && it2 != end2) - { - auto overlap = it1->intersect(*it2); - if (overlap) - { - res.push_back(*overlap); - if (it1->end() < it2->end()) - { - it1++; - } - else - { - it2++; - } - } - else - { - if (it1->end() < it2->start()) - { - it1++; - } - else - { - it2++; - } - } - } - - return period_seq{res}; -} - -auto period_seq::except(period_seq const& other) const -> period_seq -{ - // This code was pretty tricky to write, I wouldn't be surprised if it - // has some bugs in it. - - auto it1 = periods_.begin(); - auto end1 = periods_.end(); - auto it2 = other.periods_.begin(); - auto end2 = other.periods_.end(); - - auto res = std::vector{}; - if (it1 == end1) - return period_seq{res}; - if (it2 == end2) - return period_seq{periods_}; - auto period1 = period{*it1++}; - - while (it1 != end1 && it2 != end2) - { - if (period1.end() <= it2->start()) - { - res.push_back(period1); - period1 = *it1++; - } - else if (it2->end() <= period1.start()) - { - it2++; - } - else /* period1.begin() < it2->end() && it2->begin() < - period1.end() */ - { - auto const [mbefore, mafter] = period1.except(*it2); - if (mbefore) - res.push_back(*mbefore); - if (mafter) - { - period1 = *mafter; - } - else - { - period1 = *it1++; - } - } - } - - return period_seq{res}; -} - -auto period_seq::periods() const -> std::vector const& -{ - return periods_; -} - -auto operator<<(std::ostream& os, period const& p) -> std::ostream& -{ - return os << "[" << p.start() << ", " << p.end() << ")"; -} - -auto operator<<(std::ostream& os, period_seq const& ps) -> std::ostream& +auto iso8601_secs(timestamp ts) -> std::string { - os << "{"; - auto it = ps.periods().begin(); - while (it != ps.periods().end()) - { - os << " " << *it; - if (++it != ps.periods().end()) - { - os << ","; - } - } - return os << " }"; + return std::format("{0:%F}T{0:%T}Z", ts); } } // namespace routemon::time diff --git a/server/src/time.cppm b/server/src/time.cppm index 0007839..32df737 100644 --- a/server/src/time.cppm +++ b/server/src/time.cppm @@ -4,28 +4,33 @@ import std; export namespace routemon::time { -using timestamp = std::chrono::time_point; +template +using timestamp = std::chrono::time_point; +auto iso8601_secs(timestamp ts) -> std::string; + +template class period { // Assuming [start, end). Unfortunately the DATEX II model is not // clear about this. - timestamp start_; - timestamp end_; + timestamp start_; + timestamp end_; public: - explicit period(timestamp start, timestamp end); + explicit period(timestamp start, timestamp end); [[nodiscard]] auto intersect(period other) const -> std::optional; [[nodiscard]] auto except(period other) const -> std::pair, std::optional>; - [[nodiscard]] auto start() const -> timestamp; - [[nodiscard]] auto end() const -> timestamp; + [[nodiscard]] auto start() const -> timestamp; + [[nodiscard]] auto end() const -> timestamp; }; +template class period_seq { - std::vector periods_; + std::vector> periods_; // The way lt and ge are ordered makes a difference for how the sorting // (insertion based on lower_bound) works. Do not carelessly reorder this. @@ -37,11 +42,11 @@ class period_seq // O(n log n) template S> - requires std::same_as, period> - static auto consolidate(I begin, S end) -> std::vector + requires std::same_as, period> + static auto consolidate(I begin, S end) -> std::vector> { - auto periods = std::vector{}; - auto preds = std::vector>{}; + auto periods = std::vector>{}; + auto preds = std::vector, lt_ge>>{}; for (auto it = begin; it != end; it++) { @@ -89,23 +94,221 @@ class period_seq return periods; } - explicit period_seq(std::vector periods); + explicit period_seq(std::vector> periods); public: template S> - requires std::same_as, period> + requires std::same_as, period> explicit period_seq(I begin, S end) : periods_{consolidate(begin, end)} { } - explicit period_seq(period singleton); + explicit period_seq(period singleton); [[nodiscard]] auto intersect(period_seq const& other) const -> period_seq; [[nodiscard]] auto except(period_seq const& other) const -> period_seq; - [[nodiscard]] auto periods() const -> std::vector const&; + [[nodiscard]] auto periods() const -> std::vector> const&; }; -auto operator<<(std::ostream& os, period const& p) -> std::ostream&; -auto operator<<(std::ostream& os, period_seq const& ps) -> std::ostream&; +template +auto operator<<(std::ostream& os, period const& p) -> std::ostream&; + +template +auto operator<<(std::ostream& os, period_seq const& ps) + -> std::ostream&; + +} // namespace routemon::time + +namespace routemon::time { + +template +period::period(timestamp start, timestamp end) + : start_{start}, end_{end} +{ + if (start >= end) + { + throw std::invalid_argument{"period: start should be before end"}; + } +} + +template +auto period::intersect(period other) const -> std::optional +{ + auto const new_start = start_ < other.start() ? other.start() : start_; + auto const new_end = other.end() < end_ ? other.end() : end_; + return new_start < new_end ? std::make_optional(period{new_start, new_end}) + : std::nullopt; +} + +template +auto period::except(period other) const + -> std::pair, std::optional> +{ + auto const before_start = start_; + auto const before_end = other.start(); + auto const after_start = end_; + auto const after_end = other.end(); + std::optional before, after; + if (before_start < before_end) + before = period{before_start, before_end}; + if (after_start < after_end) + after = period{after_end, after_start}; + return std::make_pair(before, after); +} + +template +auto period::start() const -> timestamp +{ + return start_; +} + +template +auto period::end() const -> timestamp +{ + return end_; +} + +template +period_seq::period_seq(std::vector> periods) + : periods_{std::move(periods)} +{ + for (auto i = 0uz; i < periods_.size(); i++) + { + if (i + 1 < periods_.size()) + { + if (periods_[i].end() >= periods_[i + 1].start()) + { + throw std::logic_error{"period_seq: vector provided to private " + "constructor not ordered properly"}; + } + } + } +} + +template +period_seq::period_seq(period singleton) + : periods_{singleton} +{ +} + +template +auto period_seq::intersect(period_seq const& other) const + -> period_seq +{ + auto it1 = periods_.begin(); + auto end1 = periods_.end(); + auto it2 = other.periods_.begin(); + auto end2 = other.periods_.end(); + + auto res = std::vector>{}; + while (it1 != end1 && it2 != end2) + { + auto overlap = it1->intersect(*it2); + if (overlap) + { + res.push_back(*overlap); + if (it1->end() < it2->end()) + { + it1++; + } + else + { + it2++; + } + } + else + { + if (it1->end() < it2->start()) + { + it1++; + } + else + { + it2++; + } + } + } + + return period_seq{res}; +} + +template +auto period_seq::except(period_seq const& other) const -> period_seq +{ + // This code was pretty tricky to write, I wouldn't be surprised if it + // has some bugs in it. + + auto it1 = periods_.begin(); + auto end1 = periods_.end(); + auto it2 = other.periods_.begin(); + auto end2 = other.periods_.end(); + + auto res = std::vector>{}; + if (it1 == end1) + return period_seq{res}; + if (it2 == end2) + return period_seq{periods_}; + auto period1 = period{*it1++}; + + while (it1 != end1 && it2 != end2) + { + if (period1.end() <= it2->start()) + { + res.push_back(period1); + period1 = *it1++; + } + else if (it2->end() <= period1.start()) + { + it2++; + } + else /* period1.begin() < it2->end() && it2->begin() < + period1.end() */ + { + auto const [mbefore, mafter] = period1.except(*it2); + if (mbefore) + res.push_back(*mbefore); + if (mafter) + { + period1 = *mafter; + } + else + { + period1 = *it1++; + } + } + } + + return period_seq{res}; +} + +template +auto period_seq::periods() const + -> std::vector> const& +{ + return periods_; +} + +template +auto operator<<(std::ostream& os, period const& p) -> std::ostream& +{ + return os << "[" << p.start() << ", " << p.end() << ")"; +} + +template +auto operator<<(std::ostream& os, period_seq const& ps) + -> std::ostream& +{ + os << "{"; + auto it = ps.periods().begin(); + while (it != ps.periods().end()) + { + os << " " << *it; + if (++it != ps.periods().end()) + { + os << ","; + } + } + return os << " }"; +} } // namespace routemon::time diff --git a/server/src/trace.cpp b/server/src/trace.cpp index f2935a9..cc51604 100644 --- a/server/src/trace.cpp +++ b/server/src/trace.cpp @@ -1,9 +1,3 @@ -module; - -// Might as well since we're using OpenSSL -#include -#include - module routemon:trace$impl; import :trace; diff --git a/server/src/util.cppm b/server/src/util.cppm index 2857fe5..986e350 100644 --- a/server/src/util.cppm +++ b/server/src/util.cppm @@ -20,14 +20,9 @@ constexpr auto parse_double( { auto x = 0.0; auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); - if (ec == std::errc{}) - { - return x; - } - else - { + if (ec != std::errc{}) return std::nullopt; - } + return x; } constexpr auto parse_float( @@ -37,14 +32,20 @@ constexpr auto parse_float( { auto x = 0.0; auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); - if (ec == std::errc{}) - { - return x; - } - else - { + if (ec != std::errc{}) return std::nullopt; - } + return x; +} + +export template +constexpr auto parse_int(std::string_view s, int base = 10) noexcept + -> std::optional +{ + auto x = T{}; + auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, base); + if (ec != std::errc{}) + return std::nullopt; + return x; } template @@ -107,10 +108,14 @@ public: { } + constexpr zstring_view(std::string s) : zstring_view{s.c_str(), s.length()} {} + constexpr auto length() const -> std::size_t { return length_; } constexpr auto c_str() const -> char const* { return s_; } + constexpr auto empty() const -> bool { return length() == 0; } + constexpr operator std::string_view() const { return std::string_view{s_, length_}; @@ -239,3 +244,26 @@ public: explicit not_null(lazy_zstring_view s) -> not_null; } // namespace routemon::util + +template <> +struct std::formatter +{ + template + constexpr auto parse(ParseContext& ctx) -> ParseContext::iterator + { + auto it = ctx.begin(); + if (it != ctx.end() && *it != '}') + throw std::format_error{ + "unexpected formatting arguments for util::zstring_view" + }; + return it; + } + + template + auto format(routemon::util::zstring_view s, FmtContext& ctx) const + -> FmtContext::iterator + { + return std::ranges::copy(std::string_view{s.c_str(), s.length()}, ctx.out()) + .out; + } +}; diff --git a/server/src/xml.cppm b/server/src/xml.cppm index ffaf159..2d186da 100644 --- a/server/src/xml.cppm +++ b/server/src/xml.cppm @@ -250,8 +250,8 @@ public: struct position { - std::size_t line; - std::size_t col; + std::uint64_t line; + std::uint64_t col; }; class executor @@ -443,8 +443,8 @@ public: [[nodiscard]] inline auto position() -> position { return { - .line = XML_GetCurrentLineNumber(p_), - .col = XML_GetCurrentColumnNumber(p_), + .line = XML_GetCurrentLineNumber64(p_), + .col = XML_GetCurrentColumnNumber64(p_), }; } -- cgit v1.3.1