summaryrefslogtreecommitdiffstats
path: root/server
diff options
context:
space:
mode:
authorRutger Broekhoff2026-11-30 21:27:55 +0100
committerRutger Broekhoff2026-11-30 21:27:55 +0100
commit7bba7176194c4d1d9c7066f8eda7a94491d924e6 (patch)
treea9a171e8608786e09d6342729ee13b8471c0c9c2 /server
parent02475e05ccd1aa15c6a6163834f28bfebbef796f (diff)
downloadroutemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.tar.gz
routemon-7bba7176194c4d1d9c7066f8eda7a94491d924e6.zip
Cleanups and updates
Diffstat (limited to 'server')
-rw-r--r--server/CMakeLists.txt72
-rw-r--r--server/CMakePresets.json8
-rw-r--r--server/README11
-rw-r--r--server/migrations/2_rwgps_up.sql2
-rw-r--r--server/src/api.cppm2
-rw-r--r--server/src/config.cpp15
-rw-r--r--server/src/config.cppm11
-rw-r--r--server/src/database/connection.cpp (renamed from server/src/database.cpp)64
-rw-r--r--server/src/database/connection.cppm30
-rw-r--r--server/src/database/migrator.cpp (renamed from server/src/migrate.cppm)104
-rw-r--r--server/src/database/migrator.cppm26
-rw-r--r--server/src/database/schema.cpp59
-rw-r--r--server/src/database/schema.cppm (renamed from server/src/database.cppm)37
-rw-r--r--server/src/database/sqlite3.cpp (renamed from server/src/sqlite3.cpp)25
-rw-r--r--server/src/database/sqlite3.cppm (renamed from server/src/sqlite3.cppm)10
-rw-r--r--server/src/http/core/client.cpp (renamed from server/src/http_client.cpp)8
-rw-r--r--server/src/http/core/client.cppm (renamed from server/src/http_client.cppm)8
-rw-r--r--server/src/http/core/common.cpp (renamed from server/src/http_common.cpp)8
-rw-r--r--server/src/http/core/common.cppm (renamed from server/src/http_common.cppm)6
-rw-r--r--server/src/http/core/server.cpp (renamed from server/src/http_server.cpp)8
-rw-r--r--server/src/http/core/server.cppm (renamed from server/src/http_server.cppm)8
-rw-r--r--server/src/http/ext/gpx.cpp139
-rw-r--r--server/src/http/ext/gpx.cppm128
-rw-r--r--server/src/http/ext/hmac_openssl.cppm173
-rw-r--r--server/src/http/ext/json.cpp34
-rw-r--r--server/src/http/ext/json.cppm65
-rw-r--r--server/src/http/ext/raw_deflate.cppm134
-rw-r--r--server/src/http/handler.cpp348
-rw-r--r--server/src/http/handler.cppm41
-rw-r--r--server/src/http/server.cpp61
-rw-r--r--server/src/http/server.cppm31
-rw-r--r--server/src/main.cpp9
-rw-r--r--server/src/routemon.cppm6
-rw-r--r--server/src/rwgps.cppm4
-rw-r--r--server/src/rwgps_webhook.cppm237
-rw-r--r--server/src/srv.cpp684
-rw-r--r--server/src/srv.cppm58
-rw-r--r--server/src/trace.cpp8
38 files changed, 1461 insertions, 1221 deletions
diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt
index b8fd37a..8fa681a 100644
--- a/server/CMakeLists.txt
+++ b/server/CMakeLists.txt
@@ -27,50 +27,60 @@ add_link_options(
27add_library(routemon_lib) 27add_library(routemon_lib)
28target_sources(routemon_lib 28target_sources(routemon_lib
29 PUBLIC FILE_SET CXX_MODULES FILES 29 PUBLIC FILE_SET CXX_MODULES FILES
30 src/api.cppm
31 src/api.cpp 30 src/api.cpp
32 src/database.cppm 31 src/api.cppm
33 src/database.cpp
34 src/config.cppm
35 src/config.cpp 32 src/config.cpp
36 src/datex2.cppm 33 src/config.cppm
34 src/database/connection.cpp
35 src/database/connection.cppm
36 src/database/migrator.cpp
37 src/database/migrator.cppm
38 src/database/schema.cpp
39 src/database/schema.cppm
40 src/database/sqlite3.cpp
41 src/database/sqlite3.cppm
37 src/datex2.cpp 42 src/datex2.cpp
38 src/gpx.cppm 43 src/datex2.cppm
44 src/geo/geo.cppm
45 src/geo/utm.cppm
46 src/geo/utm_multizonal.cppm
47 src/geo/utm_zone_local.cppm
48 src/geo/wgs84.cppm
39 src/gpx.cpp 49 src/gpx.cpp
40 src/http_client.cppm 50 src/gpx.cppm
41 src/http_client.cpp 51 src/http/core/client.cpp
42 src/http_common.cppm 52 src/http/core/client.cppm
43 src/http_common.cpp 53 src/http/core/common.cpp
44 src/http_server.cppm 54 src/http/core/common.cppm
45 src/http_server.cpp 55 src/http/core/server.cpp
46 src/locale.cppm 56 src/http/core/server.cppm
57 src/http/ext/gpx.cpp
58 src/http/ext/gpx.cppm
59 src/http/ext/hmac_openssl.cppm
60 src/http/ext/json.cpp
61 src/http/ext/json.cppm
62 src/http/ext/raw_deflate.cppm
63 src/http/handler.cpp
64 src/http/handler.cppm
65 src/http/server.cpp
66 src/http/server.cppm
47 src/locale.cpp 67 src/locale.cpp
48 src/log.cppm 68 src/locale.cppm
49 src/log.cpp 69 src/log.cpp
50 src/migrate.cppm 70 src/log.cppm
51 src/problem.cppm
52 src/problem.cpp 71 src/problem.cpp
72 src/problem.cppm
53 src/routemon.cppm 73 src/routemon.cppm
54 src/rwgps.cppm
55 src/rwgps.cpp 74 src/rwgps.cpp
56 src/rwgps_webhook.cppm 75 src/rwgps.cppm
57 src/sqlite3.cppm
58 src/sqlite3.cpp
59 src/srv.cppm
60 src/srv.cpp
61 src/time.cppm
62 src/time.cpp 76 src/time.cpp
63 src/trace.cppm 77 src/time.cppm
64 src/trace.cpp 78 src/trace.cpp
65 src/util.cppm 79 src/trace.cppm
66 src/util.cpp 80 src/util.cpp
67 src/xml.cppm 81 src/util.cppm
68 src/xml.cpp 82 src/xml.cpp
69 src/geo/geo.cppm 83 src/xml.cppm
70 src/geo/utm.cppm
71 src/geo/utm_multizonal.cppm
72 src/geo/utm_zone_local.cppm
73 src/geo/wgs84.cppm
74) 84)
75 85
76add_executable(routemon src/main.cpp) 86add_executable(routemon src/main.cpp)
diff --git a/server/CMakePresets.json b/server/CMakePresets.json
index ae7fd67..c0878b6 100644
--- a/server/CMakePresets.json
+++ b/server/CMakePresets.json
@@ -6,22 +6,18 @@
6 "binaryDir": "${sourceDir}/build", 6 "binaryDir": "${sourceDir}/build",
7 "generator": "Ninja", 7 "generator": "Ninja",
8 "cacheVariables": { 8 "cacheVariables": {
9 "CMAKE_CXX_STANDARD": "26",
10 "CMAKE_COLOR_DIAGNOSTICS": true, 9 "CMAKE_COLOR_DIAGNOSTICS": true,
11 "CMAKE_EXPERIMENTAL_CXX_IMPORT_STD": "f35a9ac6-8463-4d38-8eec-5d6008153e7d",
12 "CMAKE_CXX_EXTENSIONS": false, 10 "CMAKE_CXX_EXTENSIONS": false,
13 "CMAKE_CXX_MODULE_STD": true, 11 "CMAKE_CXX_STANDARD": "26",
14 "CMAKE_EXPORT_COMPILE_COMMANDS": true 12 "CMAKE_EXPORT_COMPILE_COMMANDS": true
15 } 13 }
16 }, 14 },
17 { 15 {
18 "name": "nix-derivation", 16 "name": "nix-derivation",
19 "cacheVariables": { 17 "cacheVariables": {
20 "CMAKE_CXX_STANDARD": "26",
21 "CMAKE_COLOR_DIAGNOSTICS": true, 18 "CMAKE_COLOR_DIAGNOSTICS": true,
22 "CMAKE_EXPERIMENTAL_CXX_IMPORT_STD": "451f2fe2-a8a2-47c3-bc32-94786d8fc91b",
23 "CMAKE_CXX_EXTENSIONS": false, 19 "CMAKE_CXX_EXTENSIONS": false,
24 "CMAKE_CXX_MODULE_STD": true, 20 "CMAKE_CXX_STANDARD": "26",
25 "CMAKE_EXPORT_COMPILE_COMMANDS": true 21 "CMAKE_EXPORT_COMPILE_COMMANDS": true
26 } 22 }
27 } 23 }
diff --git a/server/README b/server/README
index 04d5d5a..f9e8e09 100644
--- a/server/README
+++ b/server/README
@@ -8,9 +8,10 @@ $ cmake --build build
8 8
9# Dependencies (and versions known to work) 9# Dependencies (and versions known to work)
10 10
11- CMake 4.3.4 11- CMake 4.5.1
12- clang version 22.1.6 12- clang version 23.1.5
13- Boost 1.91 13- Boost 1.92
14- Expat 2.10.0
15- ICU 78.3
16- OpenSSL 4.1.0
14- pugixml 1.16 17- pugixml 1.16
15- OpenSSL
16- ICU \ No newline at end of file
diff --git a/server/migrations/2_rwgps_up.sql b/server/migrations/2_rwgps_up.sql
index 569479b..f5fd704 100644
--- a/server/migrations/2_rwgps_up.sql
+++ b/server/migrations/2_rwgps_up.sql
@@ -18,5 +18,5 @@ CREATE TABLE rwgps_notification_target_collection (
18 type_ TEXT, -- NULL if unknown 18 type_ TEXT, -- NULL if unknown
19 url TEXT, 19 url TEXT,
20 CHECK (type_ IN ('pinned')), 20 CHECK (type_ IN ('pinned')),
21 FOREIGN KEY (notification_id) REFERENCES rwgps_notification (id) 21 FOREIGN KEY (notification_id) REFERENCES rwgps_notification (id) ON DELETE CASCADE
22) STRICT; 22) STRICT;
diff --git a/server/src/api.cppm b/server/src/api.cppm
index 7e71413..a0ab878 100644
--- a/server/src/api.cppm
+++ b/server/src/api.cppm
@@ -6,7 +6,7 @@ module;
6export module routemon:api; 6export module routemon:api;
7 7
8import std; 8import std;
9import :database; 9import :database.connection;
10import :datex2; 10import :datex2;
11import :geo.wgs84; 11import :geo.wgs84;
12import :geo.utm.multizonal; 12import :geo.utm.multizonal;
diff --git a/server/src/config.cpp b/server/src/config.cpp
index 9231232..ec49aeb 100644
--- a/server/src/config.cpp
+++ b/server/src/config.cpp
@@ -138,11 +138,12 @@ auto tag_invoke(
138 [](object_reader& r) -> rwgps 138 [](object_reader& r) -> rwgps
139 { 139 {
140 return { 140 return {
141 .api_key_filename = r.expect_at<std::string>("api_key_filename"), 141 .api_key_filename =
142 r.expect_at<std::filesystem::path>("api_key_filename"),
142 .api_secret_filename = 143 .api_secret_filename =
143 r.expect_at<std::string>("api_secret_filename"), 144 r.expect_at<std::filesystem::path>("api_secret_filename"),
144 .auth_token_filename = 145 .auth_token_filename =
145 r.expect_at<std::string>("auth_token_filename"), 146 r.expect_at<std::filesystem::path>("auth_token_filename"),
146 }; 147 };
147 }); 148 });
148} 149}
@@ -156,7 +157,8 @@ auto tag_invoke(
156 [](object_reader& r) -> situations 157 [](object_reader& r) -> situations
157 { 158 {
158 return { 159 return {
159 .datex2_filename = r.expect_at<std::string>("datex2_filename"), 160 .datex2_filename =
161 r.expect_at<std::filesystem::path>("datex2_filename"),
160 }; 162 };
161 }); 163 });
162} 164}
@@ -170,7 +172,10 @@ auto tag_invoke(
170 [](object_reader& r) -> database 172 [](object_reader& r) -> database
171 { 173 {
172 return { 174 return {
173 .sqlite3_filename = r.expect_at<std::string>("sqlite3_filename"), 175 .sqlite3_filename =
176 r.expect_at<std::filesystem::path>("sqlite3_filename"),
177 .migrations_dir =
178 r.expect_at<std::filesystem::path>("migrations_dir"),
174 }; 179 };
175 }); 180 });
176} 181}
diff --git a/server/src/config.cppm b/server/src/config.cppm
index 01e1055..9c37457 100644
--- a/server/src/config.cppm
+++ b/server/src/config.cppm
@@ -7,19 +7,20 @@ namespace routemon::config {
7 7
8export struct rwgps 8export struct rwgps
9{ 9{
10 std::string api_key_filename = {}; 10 std::filesystem::path api_key_filename = {};
11 std::string api_secret_filename = {}; 11 std::filesystem::path api_secret_filename = {};
12 std::string auth_token_filename = {}; 12 std::filesystem::path auth_token_filename = {};
13}; 13};
14 14
15export struct situations 15export struct situations
16{ 16{
17 std::string datex2_filename = {}; 17 std::filesystem::path datex2_filename = {};
18}; 18};
19 19
20export struct database 20export struct database
21{ 21{
22 std::string sqlite3_filename = {}; 22 std::filesystem::path sqlite3_filename = {};
23 std::filesystem::path migrations_dir = {};
23}; 24};
24 25
25export struct http_server 26export struct http_server
diff --git a/server/src/database.cpp b/server/src/database/connection.cpp
index c1f9ab2..fcdf15f 100644
--- a/server/src/database.cpp
+++ b/server/src/database/connection.cpp
@@ -1,67 +1,9 @@
1module routemon:database$impl; 1module routemon:database.connection$impl;
2 2
3import :database; 3import :database.connection;
4 4
5namespace routemon::database { 5namespace routemon::database {
6 6
7namespace schema {
8
9constexpr std::int64_t expected_version = 2;
10
11auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string>
12{
13 switch (c)
14 {
15 case rwgps_notification_cause::unknown:
16 return std::nullopt;
17 case rwgps_notification_cause::created:
18 return "created";
19 case rwgps_notification_cause::updated:
20 return "updated";
21 case rwgps_notification_cause::deleted:
22 return "deleted";
23 case rwgps_notification_cause::added:
24 return "added";
25 case rwgps_notification_cause::removed:
26 return "removed";
27 }
28}
29
30auto try_to_string(rwgps_notification_item_type t) -> std::optional<std::string>
31{
32 switch (t)
33 {
34 case rwgps_notification_item_type::unknown:
35 return std::nullopt;
36 case rwgps_notification_item_type::trip:
37 return "trip";
38 case rwgps_notification_item_type::route:
39 return "route";
40 case rwgps_notification_item_type::event:
41 return "event";
42 case rwgps_notification_item_type::event_participant:
43 return "event_participant";
44 case rwgps_notification_item_type::club_member:
45 return "club_member";
46 case rwgps_notification_item_type::authorization:
47 return "authorization";
48 }
49}
50
51auto try_to_string(rwgps_notification_target_collection_type t)
52 -> std::optional<std::string>
53{
54 switch (t)
55 {
56 case rwgps_notification_target_collection_type::unknown:
57 return std::nullopt;
58 case rwgps_notification_target_collection_type::pinned:
59 return "pinned";
60 }
61};
62
63} // namespace schema
64
65auto connection::insert_rwgps_notifications( 7auto connection::insert_rwgps_notifications(
66 std::vector<std::pair< 8 std::vector<std::pair<
67 schema::rwgps_notification, 9 schema::rwgps_notification,
@@ -108,7 +50,7 @@ auto connection::insert_rwgps_notifications(
108 } 50 }
109} 51}
110 52
111auto open(util::zstring_view filename) -> std::shared_ptr<connection> 53auto open(std::filesystem::path const& filename) -> std::shared_ptr<connection>
112{ 54{
113 auto dbc = sqlite3::open(filename); 55 auto dbc = sqlite3::open(filename);
114 try 56 try
diff --git a/server/src/database/connection.cppm b/server/src/database/connection.cppm
new file mode 100644
index 0000000..22e6495
--- /dev/null
+++ b/server/src/database/connection.cppm
@@ -0,0 +1,30 @@
1export module routemon:database.connection;
2
3import std;
4import :database.schema;
5import :database.sqlite3;
6import :time;
7
8namespace routemon::database {
9
10export class connection
11{
12 sqlite3::connection dbc_;
13
14 explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {}
15
16 friend auto open(std::filesystem::path const& filename)
17 -> std::shared_ptr<connection>;
18
19public:
20 auto insert_rwgps_notifications(
21 std::vector<std::pair<
22 schema::rwgps_notification,
23 std::optional<schema::rwgps_notification_target_collection>
24 >>& notifs) -> void;
25};
26
27export auto open(std::filesystem::path const& filename)
28 -> std::shared_ptr<connection>;
29
30} // namespace routemon::database
diff --git a/server/src/migrate.cppm b/server/src/database/migrator.cpp
index e5cd52a..d6c7926 100644
--- a/server/src/migrate.cppm
+++ b/server/src/database/migrator.cpp
@@ -2,15 +2,15 @@ module;
2 2
3#include <cassert> 3#include <cassert>
4 4
5export module routemon:migrate; 5export module routemon:database.migrator$impl;
6 6
7import :log; 7import :database.migrator;
8import :sqlite3;
9 8
10namespace routemon::migrate { 9namespace routemon::database {
11 10
12auto load_migrations(std::int64_t current_version, std::int64_t target_version) 11auto load_migrations(
13 -> std::vector<std::string> 12 std::filesystem::path const& dir, std::int64_t current_version,
13 std::int64_t target_version) -> std::vector<std::string>
14{ 14{
15 if (current_version < 0 || target_version < 0) 15 if (current_version < 0 || target_version < 0)
16 throw std::invalid_argument{"database versions must be nonnegative"}; 16 throw std::invalid_argument{"database versions must be nonnegative"};
@@ -25,7 +25,7 @@ auto load_migrations(std::int64_t current_version, std::int64_t target_version)
25 std::vector<std::optional<std::pair<std::filesystem::path, std::string>>>{ 25 std::vector<std::optional<std::pair<std::filesystem::path, std::string>>>{
26 static_cast<std::size_t>(target_version - current_version) 26 static_cast<std::size_t>(target_version - current_version)
27 }; 27 };
28 for (auto const& entry : std::filesystem::directory_iterator{"migrations"}) 28 for (auto const& entry : std::filesystem::directory_iterator{dir})
29 { 29 {
30 if (!std::filesystem::is_regular_file(entry.status())) 30 if (!std::filesystem::is_regular_file(entry.status()))
31 continue; 31 continue;
@@ -69,58 +69,54 @@ auto load_migrations(std::int64_t current_version, std::int64_t target_version)
69 | std::ranges::to<std::vector<std::string>>(); 69 | std::ranges::to<std::vector<std::string>>();
70} 70}
71 71
72export class migrator 72auto migrator::current_version() -> std::int64_t
73{ 73{
74 log::logger l_; 74 if (auto const [has_migrations_table] =
75 sqlite3::connection dbc_; 75 dbc_.query(
76 76 "SELECT COUNT(*) FROM sqlite_schema WHERE "
77 auto current_version() -> std::int64_t 77 "type IS 'table' AND "
78 { 78 "name IS 'migration'")
79 if (auto const [has_migrations_table] = 79 .scan_row_max1<std::int64_t>();
80 dbc_.query( 80 has_migrations_table)
81 "SELECT COUNT(*) FROM sqlite_schema WHERE " 81 return std::get<0>(dbc_.query("SELECT version FROM migration")
82 "type IS 'table' AND " 82 .scan_row_max1<std::int64_t>());
83 "name IS 'migration'") 83 return 0;
84 .scan_row_max1<std::int64_t>(); 84}
85 has_migrations_table)
86 return std::get<0>(dbc_.query("SELECT version FROM migration")
87 .scan_row_max1<std::int64_t>());
88 return 0;
89 }
90
91public:
92 explicit migrator(log::logger const& l, std::string const& filename)
93 : l_{l.sub("migrator")}, dbc_{sqlite3::open(filename)}
94 {
95 }
96 85
97 auto migrate_to(std::int64_t target_version) -> void 86migrator::migrator(
98 { 87 log::logger const& l, std::filesystem::path const& db_filename,
99 // Part of function contract. Consider throwing instead? 88 std::filesystem::path migrations_dir)
100 if (target_version < 0) 89 : l_{l.sub("migrator")}, dbc_{sqlite3::open(db_filename)},
101 throw std::invalid_argument{ 90 migrations_dir_{std::move(migrations_dir)}
102 "target database version must be nonnegative" 91{
103 }; 92}
104 93
105 auto current = current_version(); 94auto migrator::migrate_to(std::int64_t target_version) -> void
106 auto const migration_sqls = load_migrations(current, target_version); 95{
96 // Part of function contract. Consider throwing instead?
97 if (target_version < 0)
98 throw std::invalid_argument{"target database version must be nonnegative"};
107 99
108 for (auto const& sql : migration_sqls) 100 auto current = current_version();
109 { 101 auto const migration_sqls =
110 l_.info("Migrating from schema version {} to {}", current, current + 1); 102 load_migrations(migrations_dir_, current, target_version);
111 migrate_step(++current, sql);
112 }
113 }
114 103
115 auto migrate_step(std::int64_t target_version, util::zstring_view sql) -> void 104 for (auto const& sql : migration_sqls)
116 { 105 {
117 auto tx = sqlite3::tx{dbc_}; 106 l_.info("Migrating from schema version {} to {}", current, current + 1);
118 while (!sql.empty()) 107 migrate_step(++current, sql);
119 tx.exec_first(sql);
120 tx.exec(
121 "UPDATE migration SET version = :version",
122 [target_version](auto& s) { s.bind(":version", target_version); });
123 } 108 }
124}; 109}
110
111auto migrator::migrate_step(std::int64_t target_version, util::zstring_view sql)
112 -> void
113{
114 auto tx = sqlite3::tx{dbc_};
115 while (!sql.empty())
116 tx.exec_first(sql);
117 tx.exec(
118 "UPDATE migration SET version = :version",
119 [target_version](auto& s) { s.bind(":version", target_version); });
120}
125 121
126} // namespace routemon::migrate 122} // namespace routemon::database
diff --git a/server/src/database/migrator.cppm b/server/src/database/migrator.cppm
new file mode 100644
index 0000000..d7fbfc3
--- /dev/null
+++ b/server/src/database/migrator.cppm
@@ -0,0 +1,26 @@
1export module routemon:database.migrator;
2
3import :database.sqlite3;
4import :log;
5
6namespace routemon::database {
7
8export class migrator
9{
10 log::logger l_;
11 sqlite3::connection dbc_;
12 std::filesystem::path migrations_dir_;
13
14 auto current_version() -> std::int64_t;
15
16public:
17 explicit migrator(
18 log::logger const& l, std::filesystem::path const& db_filename,
19 std::filesystem::path migrations_dir);
20
21 auto migrate_to(std::int64_t target_version) -> void;
22 auto migrate_step(std::int64_t target_version, util::zstring_view sql)
23 -> void;
24};
25
26} // namespace routemon::database
diff --git a/server/src/database/schema.cpp b/server/src/database/schema.cpp
new file mode 100644
index 0000000..addc1f8
--- /dev/null
+++ b/server/src/database/schema.cpp
@@ -0,0 +1,59 @@
1module routemon:database.schema$impl;
2
3import :database.schema;
4
5namespace routemon::database::schema {
6
7auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string>
8{
9 switch (c)
10 {
11 case rwgps_notification_cause::unknown:
12 return std::nullopt;
13 case rwgps_notification_cause::created:
14 return "created";
15 case rwgps_notification_cause::updated:
16 return "updated";
17 case rwgps_notification_cause::deleted:
18 return "deleted";
19 case rwgps_notification_cause::added:
20 return "added";
21 case rwgps_notification_cause::removed:
22 return "removed";
23 }
24}
25
26auto try_to_string(rwgps_notification_item_type t) -> std::optional<std::string>
27{
28 switch (t)
29 {
30 case rwgps_notification_item_type::unknown:
31 return std::nullopt;
32 case rwgps_notification_item_type::trip:
33 return "trip";
34 case rwgps_notification_item_type::route:
35 return "route";
36 case rwgps_notification_item_type::event:
37 return "event";
38 case rwgps_notification_item_type::event_participant:
39 return "event_participant";
40 case rwgps_notification_item_type::club_member:
41 return "club_member";
42 case rwgps_notification_item_type::authorization:
43 return "authorization";
44 }
45}
46
47auto try_to_string(rwgps_notification_target_collection_type t)
48 -> std::optional<std::string>
49{
50 switch (t)
51 {
52 case rwgps_notification_target_collection_type::unknown:
53 return std::nullopt;
54 case rwgps_notification_target_collection_type::pinned:
55 return "pinned";
56 }
57};
58
59} // namespace routemon::database::schema
diff --git a/server/src/database.cppm b/server/src/database/schema.cppm
index 83616d2..a34edef 100644
--- a/server/src/database.cppm
+++ b/server/src/database/schema.cppm
@@ -1,12 +1,11 @@
1export module routemon:database; 1export module routemon:database.schema;
2 2
3import std; 3import std;
4import :sqlite3;
5import :time; 4import :time;
6 5
7namespace routemon::database { 6namespace routemon::database::schema {
8 7
9namespace schema { 8constexpr std::int64_t expected_version = 2;
10 9
11enum class rwgps_notification_cause 10enum class rwgps_notification_cause
12{ 11{
@@ -18,6 +17,8 @@ enum class rwgps_notification_cause
18 removed, 17 removed,
19}; 18};
20 19
20auto try_to_string(rwgps_notification_cause c) -> std::optional<std::string>;
21
21enum class rwgps_notification_item_type 22enum class rwgps_notification_item_type
22{ 23{
23 unknown, 24 unknown,
@@ -29,12 +30,18 @@ enum class rwgps_notification_item_type
29 authorization, 30 authorization,
30}; 31};
31 32
33auto try_to_string(rwgps_notification_item_type t)
34 -> std::optional<std::string>;
35
32enum rwgps_notification_target_collection_type 36enum rwgps_notification_target_collection_type
33{ 37{
34 unknown, 38 unknown,
35 pinned, 39 pinned,
36}; 40};
37 41
42auto try_to_string(rwgps_notification_target_collection_type t)
43 -> std::optional<std::string>;
44
38struct rwgps_notification_target_collection 45struct rwgps_notification_target_collection
39{ 46{
40 std::int64_t notification_id = 0; 47 std::int64_t notification_id = 0;
@@ -57,24 +64,4 @@ struct rwgps_notification
57 rwgps_notification_cause action; 64 rwgps_notification_cause action;
58}; 65};
59 66
60} // namespace schema 67} // namespace routemon::database::schema
61
62export class connection
63{
64 sqlite3::connection dbc_;
65
66 explicit connection(sqlite3::connection dbc) : dbc_{std::move(dbc)} {}
67
68 friend auto open(util::zstring_view filename) -> std::shared_ptr<connection>;
69
70public:
71 auto insert_rwgps_notifications(
72 std::vector<std::pair<
73 schema::rwgps_notification,
74 std::optional<schema::rwgps_notification_target_collection>
75 >>& notifs) -> void;
76};
77
78export auto open(util::zstring_view filename) -> std::shared_ptr<connection>;
79
80} // namespace routemon::database
diff --git a/server/src/sqlite3.cpp b/server/src/database/sqlite3.cpp
index 243cf41..35d4fec 100644
--- a/server/src/sqlite3.cpp
+++ b/server/src/database/sqlite3.cpp
@@ -2,11 +2,11 @@ module;
2 2
3#include <sqlite3.h> 3#include <sqlite3.h>
4 4
5module routemon:sqlite3$impl; 5module routemon:database.sqlite3$impl;
6 6
7import :sqlite3; 7import :database.sqlite3;
8 8
9namespace routemon::sqlite3 { 9namespace routemon::database::sqlite3 {
10 10
11mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc} 11mutex_guard::mutex_guard(::sqlite3* dbc) noexcept : dbc_{dbc}
12{ 12{
@@ -270,7 +270,7 @@ connection::~connection()
270 std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr)); 270 std::ignore = ::sqlite3_close(std::exchange(dbc_, nullptr));
271} 271}
272 272
273auto open(util::zstring_view filename) -> connection 273auto open(std::filesystem::path const& filename) -> connection
274{ 274{
275 ::sqlite3* dbc = nullptr; 275 ::sqlite3* dbc = nullptr;
276 auto s = ::sqlite3_open_v2( 276 auto s = ::sqlite3_open_v2(
@@ -290,7 +290,22 @@ auto open(util::zstring_view filename) -> connection
290 } 290 }
291 } 291 }
292 auto w = connection{dbc}; 292 auto w = connection{dbc};
293
293 w.exec("PRAGMA foreign_keys = ON"); 294 w.exec("PRAGMA foreign_keys = ON");
295 auto foreign_keys_on = std::int64_t{};
296 try
297 {
298 w.query("PRAGMA foreign_keys").scan_row_max1(foreign_keys_on);
299 }
300 catch (std::exception& e)
301 {
302 throw std::runtime_error{
303 "used SQLite version does not seem to support foreign key enforcement"
304 };
305 }
306 if (foreign_keys_on != 1)
307 throw std::runtime_error{"failed to enable foreign key enforcement"};
308
294 return w; 309 return w;
295} 310}
296 311
@@ -349,4 +364,4 @@ auto tx::exec_first(util::zstring_view& sql) -> void
349 } 364 }
350} 365}
351 366
352} // namespace routemon::sqlite3 367} // namespace routemon::database::sqlite3
diff --git a/server/src/sqlite3.cppm b/server/src/database/sqlite3.cppm
index 3348b0b..2216109 100644
--- a/server/src/sqlite3.cppm
+++ b/server/src/database/sqlite3.cppm
@@ -1,4 +1,4 @@
1export module routemon:sqlite3; 1export module routemon:database.sqlite3;
2 2
3import std; 3import std;
4import :util; 4import :util;
@@ -10,7 +10,7 @@ extern "C"
10 using sqlite3_stmt = struct sqlite3_stmt; 10 using sqlite3_stmt = struct sqlite3_stmt;
11} 11}
12 12
13namespace routemon::sqlite3 { 13namespace routemon::database::sqlite3 {
14 14
15template <class T, template <class U> concept C> 15template <class T, template <class U> concept C>
16concept optional_of = requires { 16concept optional_of = requires {
@@ -176,7 +176,7 @@ export class connection
176 176
177 explicit connection(::sqlite3* dbc); 177 explicit connection(::sqlite3* dbc);
178 178
179 friend auto open(util::zstring_view filename) -> connection; 179 friend auto open(std::filesystem::path const& filename) -> connection;
180 friend class tx; 180 friend class tx;
181 181
182public: 182public:
@@ -217,6 +217,6 @@ public:
217 auto exec_first(util::zstring_view& sql) -> void; 217 auto exec_first(util::zstring_view& sql) -> void;
218}; 218};
219 219
220export auto open(util::zstring_view filename) -> connection; 220export auto open(std::filesystem::path const& filename) -> connection;
221 221
222} // namespace routemon::sqlite3 222} // namespace routemon::database::sqlite3
diff --git a/server/src/http_client.cpp b/server/src/http/core/client.cpp
index 0f3d9e6..c0143b0 100644
--- a/server/src/http_client.cpp
+++ b/server/src/http/core/client.cpp
@@ -4,11 +4,11 @@ module;
4#include <boost/beast/core.hpp> 4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp> 5#include <boost/beast/http.hpp>
6 6
7module routemon:http.client$impl; 7module routemon:http.core.client$impl;
8 8
9import :http.client; 9import :http.core.client;
10 10
11namespace routemon::http { 11namespace routemon::http::core {
12 12
13client::client(net::io_context& ioc) : ioc_{ioc}, resolver_{ioc} 13client::client(net::io_context& ioc) : ioc_{ioc}, resolver_{ioc}
14{ 14{
@@ -17,4 +17,4 @@ client::client(net::io_context& ioc) : ioc_{ioc}, resolver_{ioc}
17 net::ssl::verify_peer | net::ssl::verify_fail_if_no_peer_cert); 17 net::ssl::verify_peer | net::ssl::verify_fail_if_no_peer_cert);
18} 18}
19 19
20} // namespace routemon::http 20} // namespace routemon::http::core
diff --git a/server/src/http_client.cppm b/server/src/http/core/client.cppm
index accd5c0..ada4f03 100644
--- a/server/src/http_client.cppm
+++ b/server/src/http/core/client.cppm
@@ -6,15 +6,15 @@ module;
6#include <boost/beast/core.hpp> 6#include <boost/beast/core.hpp>
7#include <boost/beast/http.hpp> 7#include <boost/beast/http.hpp>
8 8
9export module routemon:http.client; 9export module routemon:http.core.client;
10 10
11export import :http.common; 11export import :http.core.common;
12 12
13namespace net = boost::asio; 13namespace net = boost::asio;
14namespace ssl = net::ssl; 14namespace ssl = net::ssl;
15using tcp = net::ip::tcp; 15using tcp = net::ip::tcp;
16 16
17namespace routemon::http { 17namespace routemon::http::core {
18 18
19export class client 19export class client
20{ 20{
@@ -62,4 +62,4 @@ public:
62 } 62 }
63}; 63};
64 64
65} // namespace routemon::http 65} // namespace routemon::http::core
diff --git a/server/src/http_common.cpp b/server/src/http/core/common.cpp
index 1c60d60..bc3ef31 100644
--- a/server/src/http_common.cpp
+++ b/server/src/http/core/common.cpp
@@ -3,11 +3,11 @@ module;
3#include <boost/beast/core.hpp> 3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp> 4#include <boost/beast/http.hpp>
5 5
6module routemon:http.common$impl; 6module routemon:http.core.common$impl;
7 7
8import :http.common; 8import :http.core.common;
9 9
10namespace routemon::http { 10namespace routemon::http::core {
11 11
12supported_verb::supported_verb(supported_verb_t value) : value{value} {} 12supported_verb::supported_verb(supported_verb_t value) : value{value} {}
13 13
@@ -105,4 +105,4 @@ auto verb_set::to_string() const -> std::string
105 return ss.str(); 105 return ss.str();
106} 106}
107 107
108} // namespace routemon::http 108} // namespace routemon::http::core
diff --git a/server/src/http_common.cppm b/server/src/http/core/common.cppm
index f56c92b..e8fbe42 100644
--- a/server/src/http_common.cppm
+++ b/server/src/http/core/common.cppm
@@ -3,7 +3,7 @@ module;
3#include <boost/beast/core.hpp> 3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp> 4#include <boost/beast/http.hpp>
5 5
6export module routemon:http.common; 6export module routemon:http.core.common;
7 7
8namespace beast = boost::beast; 8namespace beast = boost::beast;
9export namespace bhttp = beast::http; 9export namespace bhttp = beast::http;
@@ -35,7 +35,7 @@ concept body_reader = is_body_reader<T>::value;
35 35
36} // namespace boost::beast 36} // namespace boost::beast
37 37
38namespace routemon::http { 38namespace routemon::http::core {
39 39
40struct supported_verb 40struct supported_verb
41{ 41{
@@ -76,4 +76,4 @@ export struct verb_set
76static_assert(sizeof(verb_set) == 1); 76static_assert(sizeof(verb_set) == 1);
77static_assert(alignof(verb_set) == 1); 77static_assert(alignof(verb_set) == 1);
78 78
79} // namespace routemon::http 79} // namespace routemon::http::core
diff --git a/server/src/http_server.cpp b/server/src/http/core/server.cpp
index ff96091..f204dfb 100644
--- a/server/src/http_server.cpp
+++ b/server/src/http/core/server.cpp
@@ -10,14 +10,14 @@ module;
10#include <boost/json/serialize.hpp> 10#include <boost/json/serialize.hpp>
11#include <boost/url.hpp> 11#include <boost/url.hpp>
12 12
13module routemon:http.server$impl; 13module routemon:http.core.server$impl;
14 14
15import :http.server; 15import :http.core.server;
16import :trace; 16import :trace;
17 17
18namespace chrono = std::chrono; 18namespace chrono = std::chrono;
19 19
20namespace routemon::http { 20namespace routemon::http::core {
21 21
22auto presponse::header() -> bhttp::response_header<bhttp::fields>& 22auto presponse::header() -> bhttp::response_header<bhttp::fields>&
23{ 23{
@@ -206,4 +206,4 @@ auto server::spawn(net::io_context& ioc) -> void
206 }); 206 });
207} 207}
208 208
209} // namespace routemon::http 209} // namespace routemon::http::core
diff --git a/server/src/http_server.cppm b/server/src/http/core/server.cppm
index b75ada3..dbef975 100644
--- a/server/src/http_server.cppm
+++ b/server/src/http/core/server.cppm
@@ -10,18 +10,18 @@ module;
10#include <boost/json/serialize.hpp> 10#include <boost/json/serialize.hpp>
11#include <boost/url.hpp> 11#include <boost/url.hpp>
12 12
13export module routemon:http.server; 13export module routemon:http.core.server;
14 14
15import std; 15import std;
16import :config; 16import :config;
17import :trace; 17import :trace;
18import :http.common; 18import :http.core.common;
19import :problem; 19import :problem;
20 20
21namespace net = boost::asio; 21namespace net = boost::asio;
22using tcp = net::ip::tcp; 22using tcp = net::ip::tcp;
23 23
24namespace routemon::http { 24namespace routemon::http::core {
25 25
26struct readable_request 26struct readable_request
27{ 27{
@@ -796,4 +796,4 @@ public:
796 auto spawn(net::io_context& ioc) -> void; 796 auto spawn(net::io_context& ioc) -> void;
797}; 797};
798 798
799} // namespace routemon::http 799} // namespace routemon::http::core
diff --git a/server/src/http/ext/gpx.cpp b/server/src/http/ext/gpx.cpp
new file mode 100644
index 0000000..c1f565f
--- /dev/null
+++ b/server/src/http/ext/gpx.cpp
@@ -0,0 +1,139 @@
1module;
2
3#include <boost/beast/core.hpp>
4
5module routemon:http.ext.gpx$impl;
6
7import :http.ext.gpx;
8
9namespace chrono = std::chrono;
10
11namespace routemon::http::ext::gpx {
12
13auto parse_error_category_impl::name() const noexcept -> char const*
14{
15 return "gpx_parse";
16}
17
18auto parse_error_category_impl::message(int condition) const noexcept
19 -> std::string
20{
21 std::ignore = condition;
22 return "failed to parse GPX file";
23}
24
25auto parse_error_category() noexcept -> parse_error_category_impl const&
26{
27 static auto const inst = parse_error_category_impl{};
28 return inst;
29}
30
31auto parse_error() noexcept -> std::error_code
32{
33 return std::error_code{1, parse_error_category()};
34}
35
36auto parse_result::set_exception(std::exception_ptr ex) noexcept -> void
37{
38 res_ = ex;
39}
40
41auto parse_result::set_gpx_file(routemon::gpx::file&& f) noexcept -> void
42{
43 res_ = std::move(f);
44}
45
46auto parse_result::init_parse_duration(
47 chrono::steady_clock::duration dur) noexcept -> void
48{
49 init_parse_dur_ = dur;
50}
51
52[[nodiscard]] auto parse_result::init_parse_duration() const noexcept
53 -> chrono::steady_clock::duration
54{
55 return init_parse_dur_;
56}
57
58auto parse_result::put_parse_duration(
59 chrono::steady_clock::duration dur) noexcept -> void
60{
61 put_parse_dur_ = dur;
62}
63
64[[nodiscard]] auto parse_result::put_parse_duration() const noexcept
65 -> chrono::steady_clock::duration
66{
67 return put_parse_dur_;
68}
69
70auto parse_result::finish_parse_duration(
71 chrono::steady_clock::duration dur) noexcept -> void
72{
73 finish_parse_dur_ = dur;
74}
75
76[[nodiscard]] auto parse_result::finish_parse_duration() const noexcept
77 -> chrono::steady_clock::duration
78{
79 return finish_parse_dur_;
80}
81
82auto parse_result::unwrap() -> routemon::gpx::file&&
83{
84 return std::visit(
85 util::overloaded{
86 [](std::exception_ptr ex) -> routemon::gpx::file&&
87 {
88 if (ex)
89 std::rethrow_exception(ex);
90 else
91 throw std::runtime_error{"no GPX file parse result available"};
92 },
93 [](routemon::gpx::file&& f) -> routemon::gpx::file&&
94 { return std::move(f); },
95 },
96 std::move(res_));
97}
98
99auto body::reader::init(
100 boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
101 -> void
102{
103 auto const init_start = chrono::steady_clock::now();
104 try
105 {
106 r_.init();
107 ec = {};
108 }
109 catch (std::exception& ex)
110 {
111 res_->set_exception(std::current_exception());
112 ec = parse_error();
113 }
114 res_->init_parse_duration(chrono::steady_clock::now() - init_start);
115}
116
117auto body::reader::finish(beast::error_code& ec) noexcept -> void
118{
119 auto const finish_start = chrono::steady_clock::now();
120 try
121 {
122 if (buf_.size() > 0)
123 {
124 r_.put(std::string_view{buf_});
125 buf_.clear();
126 }
127
128 res_->set_gpx_file(r_.finish());
129 ec = {};
130 }
131 catch (std::exception& ex)
132 {
133 res_->set_exception(std::current_exception());
134 ec = parse_error();
135 }
136 res_->finish_parse_duration(chrono::steady_clock::now() - finish_start);
137}
138
139} // namespace routemon::http::ext::gpx
diff --git a/server/src/http/ext/gpx.cppm b/server/src/http/ext/gpx.cppm
new file mode 100644
index 0000000..69763d8
--- /dev/null
+++ b/server/src/http/ext/gpx.cppm
@@ -0,0 +1,128 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5
6export module routemon:http.ext.gpx;
7
8import std;
9import :gpx;
10import :http.core.common;
11
12namespace chrono = std::chrono;
13
14namespace routemon::http::ext::gpx {
15
16class parse_error_category_impl : public std::error_category
17{
18public:
19 auto name() const noexcept -> char const* override;
20 auto message(int condition) const noexcept -> std::string override;
21};
22
23auto parse_error_category() noexcept -> parse_error_category_impl const&;
24
25auto parse_error() noexcept -> std::error_code;
26
27class parse_result
28{
29 chrono::steady_clock::duration init_parse_dur_;
30 chrono::steady_clock::duration put_parse_dur_;
31 chrono::steady_clock::duration finish_parse_dur_;
32 std::variant<std::exception_ptr, routemon::gpx::file> res_;
33
34public:
35 auto set_exception(std::exception_ptr ex) noexcept -> void;
36 auto set_gpx_file(routemon::gpx::file&& f) noexcept -> void;
37
38 auto init_parse_duration(chrono::steady_clock::duration dur) noexcept -> void;
39 [[nodiscard]] auto init_parse_duration() const noexcept
40 -> chrono::steady_clock::duration;
41 auto put_parse_duration(chrono::steady_clock::duration dur) noexcept -> void;
42 [[nodiscard]] auto put_parse_duration() const noexcept
43 -> chrono::steady_clock::duration;
44 auto finish_parse_duration(chrono::steady_clock::duration dur) noexcept
45 -> void;
46 [[nodiscard]] auto finish_parse_duration() const noexcept
47 -> chrono::steady_clock::duration;
48
49 auto unwrap() -> routemon::gpx::file&&;
50};
51
52struct body
53{
54 using value_type = parse_result;
55
56 class reader
57 {
58 routemon::gpx::reader r_;
59 util::not_null<value_type*> res_;
60 std::inplace_vector<char, 4096> buf_;
61
62 public:
63 template <bool isRequest, bhttp::concepts::fields Fields>
64 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v) : res_{&v}
65 {
66 res_->init_parse_duration({});
67 res_->put_parse_duration({});
68 res_->finish_parse_duration({});
69 }
70
71 // The following methods (which are called by Beast) are marked
72 // noexcept, since Beast does not ensure that exceptions thrown
73 // here are appropriately directed to the caller of
74 // (async_)read(_some), so throwing here might cause the program
75 // to crash.
76
77 auto
78 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
79 -> void;
80
81 auto
82 put(beast::concepts::const_buffer_sequence auto b,
83 beast::error_code& ec) noexcept -> std::size_t
84 {
85 auto const put_start = chrono::steady_clock::now();
86 auto total = 0uz;
87 try
88 {
89 for (auto cur_in_buf : beast::buffers_range(b))
90 {
91 while (cur_in_buf.size() > 0)
92 {
93 auto to_read =
94 std::min(cur_in_buf.size(), buf_.max_size() - buf_.size());
95 buf_.append_range(
96 std::span{
97 static_cast<char const*>(cur_in_buf.data()), to_read
98 });
99 cur_in_buf += to_read;
100 total += to_read;
101
102 if (buf_.size() == buf_.max_size())
103 {
104 r_.put(std::string_view{buf_});
105 buf_.clear();
106 }
107 }
108 }
109 ec = {};
110 }
111 catch (std::exception& ex)
112 {
113 res_->set_exception(std::current_exception());
114 ec = parse_error();
115 }
116 res_->put_parse_duration(
117 res_->put_parse_duration()
118 + (chrono::steady_clock::now() - put_start));
119 return total;
120 }
121
122 auto finish(beast::error_code& ec) noexcept -> void;
123 };
124};
125static_assert(bhttp::concepts::body<body>);
126static_assert(bhttp::concepts::body_reader<body>);
127
128} // namespace routemon::http::ext::gpx
diff --git a/server/src/http/ext/hmac_openssl.cppm b/server/src/http/ext/hmac_openssl.cppm
index 52ccb86..b196094 100644
--- a/server/src/http/ext/hmac_openssl.cppm
+++ b/server/src/http/ext/hmac_openssl.cppm
@@ -1,10 +1,179 @@
1module; 1module;
2 2
3#include <boost/asio/ssl/error.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6
3#include <openssl/evp.h> 7#include <openssl/evp.h>
4#include <openssl/params.h> 8#include <openssl/params.h>
5 9
6export module routemon:hmac_openssl; 10export module routemon:http.ext.hmac_openssl;
11
12import std;
13import :http.core.common;
14import :util;
15
16namespace {
7 17
8namespace routemon::hmac_openssl { 18namespace net = boost::asio;
9 19
10} 20}
21
22namespace routemon::http::ext::hmac_openssl {
23
24// TODO: constrain T? What are appropriate constraints?
25template <typename T>
26class readable
27{
28 std::string_view key_;
29 std::optional<std::array<std::uint8_t, 32>> mac_;
30 T res_;
31
32 template <bhttp::concepts::body_reader Sub>
33 friend struct body_reader;
34
35public:
36 template <typename... Args>
37 explicit readable(std::string_view key, Args&&... args)
38 : key_{key}, res_{std::forward<Args>(args)...}
39 {
40 }
41
42 template <typename Self>
43 constexpr auto get(this Self&& self) -> auto&&
44 {
45 return std::forward<Self>(self).res_;
46 }
47
48 auto mac() const -> std::optional<std::array<std::uint8_t, 32>>
49 {
50 return mac_;
51 }
52};
53
54template <bhttp::concepts::body_reader Sub>
55class body_reader
56{
57 EVP_MAC* mac_ = nullptr;
58 EVP_MAC_CTX* ctx_ = nullptr;
59
60 util::not_null<readable<typename Sub::value_type>*> v_;
61 Sub::reader subr_;
62 beast::error_code ec_;
63
64public:
65 template <bool isRequest, bhttp::concepts::fields Fields>
66 explicit body_reader(
67 bhttp::header<isRequest, Fields>& h,
68 readable<typename Sub::value_type>& v)
69 : v_{util::not_null{&v}},
70 subr_{h, v.get()} // we are not supposed to use v yet, but this just
71 // computes an address, so it should be fine
72 {
73 }
74
75 ~body_reader()
76 {
77 ::EVP_MAC_CTX_free(ctx_);
78 ::EVP_MAC_free(mac_);
79 }
80
81 // TODO: move to impl. unit.
82 auto init(boost::optional<std::uint64_t> n, beast::error_code& ec) noexcept
83 -> void
84 {
85 // https://docs.openssl.org/master/man3/EVP_MAC/#examples
86 mac_ = ::EVP_MAC_fetch(nullptr, "HMAC", nullptr);
87 if (!mac_)
88 {
89 ec_ = ec = make_error_code(std::errc::not_enough_memory);
90 return;
91 }
92
93 ctx_ = ::EVP_MAC_CTX_new(mac_);
94 if (!ctx_)
95 {
96 ec_ = ec = make_error_code(std::errc::not_enough_memory);
97 return;
98 }
99
100 char sha256[] = "SHA256";
101 ::OSSL_PARAM const params[] = {
102 OSSL_PARAM_utf8_string("digest", sha256, sizeof(sha256) - 1),
103 OSSL_PARAM_END
104 };
105 if (!::EVP_MAC_init(
106 ctx_, reinterpret_cast<unsigned char const*>(v_->key_.data()),
107 v_->key_.size(), params))
108 {
109 ec_ = ec = beast::error_code{
110 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
111 };
112 return;
113 }
114
115 subr_.init(n, ec);
116 }
117
118 auto
119 put(beast::concepts::const_buffer_sequence auto b,
120 beast::error_code& ec) noexcept -> std::size_t
121 {
122 if ((ec = ec_))
123 return 0uz;
124
125 auto const total_read = subr_.put(b, ec);
126 if (total_read > 0)
127 {
128 auto remaining = total_read;
129 for (auto const buf : beast::buffers_range(b))
130 {
131 auto const to_hash_from_this_buf = std::min(remaining, buf.size());
132 if (!::EVP_MAC_update(
133 ctx_, static_cast<unsigned char const*>(buf.data()),
134 to_hash_from_this_buf))
135 {
136 ec_ = ec = beast::error_code{
137 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
138 };
139 return total_read;
140 }
141 remaining -= to_hash_from_this_buf;
142 }
143 }
144 return total_read;
145 }
146
147 auto finish(beast::error_code& ec) noexcept -> void
148 {
149 auto got_mac_len = 0uz;
150 auto got_mac = std::array<std::uint8_t, 32>{};
151 if (!::EVP_MAC_final(ctx_, got_mac.data(), &got_mac_len, got_mac.size()))
152 {
153 ec = beast::error_code{
154 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
155 };
156 return;
157 }
158 assert(got_mac_len == got_mac.size());
159 v_->mac_ = got_mac;
160 subr_.finish(ec);
161 }
162};
163
164template <bhttp::concepts::body Sub>
165struct body
166{
167 using value_type = readable<typename Sub::value_type>;
168};
169
170template <bhttp::concepts::body Sub>
171 requires bhttp::concepts::body_reader<Sub>
172struct body<Sub>
173{
174 using value_type = readable<typename Sub::value_type>;
175
176 using reader = body_reader<Sub>;
177};
178
179} // namespace routemon::http::ext::hmac_openssl
diff --git a/server/src/http/ext/json.cpp b/server/src/http/ext/json.cpp
new file mode 100644
index 0000000..f03d336
--- /dev/null
+++ b/server/src/http/ext/json.cpp
@@ -0,0 +1,34 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/json/stream_parser.hpp>
5
6module routemon:http.ext.json$impl;
7
8import :http.ext.json;
9
10namespace routemon::http::ext::json {
11
12namespace {
13
14namespace json = boost::json;
15
16} // namespace
17
18auto body::reader::init(
19 boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
20 -> void
21{
22 p_.reset();
23 ec = {};
24}
25
26auto body::reader::finish(beast::error_code& ec) noexcept -> void
27{
28 p_.finish(ec);
29 if (ec)
30 return;
31 *v_ = p_.release();
32}
33
34} // namespace routemon::http::ext::json
diff --git a/server/src/http/ext/json.cppm b/server/src/http/ext/json.cppm
index e69de29..4097253 100644
--- a/server/src/http/ext/json.cppm
+++ b/server/src/http/ext/json.cppm
@@ -0,0 +1,65 @@
1module;
2
3#include <boost/beast/core.hpp>
4#include <boost/beast/http.hpp>
5#include <boost/json/stream_parser.hpp>
6
7export module routemon:http.ext.json;
8
9import std;
10import :http.core.common;
11import :util;
12
13namespace routemon::http::ext::json {
14
15namespace {
16
17namespace json = boost::json;
18
19} // namespace
20
21struct body
22{
23 using value_type = json::value;
24
25 class reader
26 {
27 json::stream_parser p_;
28 util::not_null<value_type*> v_;
29
30 public:
31 template <bool isRequest, bhttp::concepts::fields Fields>
32 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v)
33 : v_{util::not_null{&v}}
34 {
35 }
36
37 auto
38 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
39 -> void;
40
41 auto
42 put(beast::concepts::const_buffer_sequence auto b,
43 beast::error_code& ec) noexcept -> std::size_t
44 {
45 ec = {};
46
47 auto wrote = 0uz;
48 for (auto const buf : beast::buffers_range(b))
49 {
50 p_.write(static_cast<char const*>(buf.data()), buf.size(), ec);
51 wrote += buf.size();
52 if (ec)
53 break;
54 }
55 return wrote;
56 }
57
58 auto finish(beast::error_code& ec) noexcept -> void;
59 };
60};
61
62static_assert(bhttp::concepts::body<body>);
63static_assert(bhttp::concepts::body_reader<body>);
64
65} // namespace routemon::http::ext::json
diff --git a/server/src/http/ext/raw_deflate.cppm b/server/src/http/ext/raw_deflate.cppm
new file mode 100644
index 0000000..ee7da2f
--- /dev/null
+++ b/server/src/http/ext/raw_deflate.cppm
@@ -0,0 +1,134 @@
1module;
2
3#include <boost/asio/buffer.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <boost/beast/zlib.hpp>
7
8export module routemon:http.ext.raw_deflate;
9
10import :http.core.common;
11
12namespace routemon::http::ext::raw_deflate {
13
14namespace {
15
16namespace net = boost::asio;
17
18}
19
20template <bhttp::concepts::body_reader Inner>
21struct body
22{
23 using value_type = Inner::value_type;
24
25 class reader
26 {
27 static constexpr auto const chunk_size = 16384;
28
29 Inner::reader r_;
30 bool stream_ended_ = false;
31 beast::zlib::z_params zs_ = {};
32 beast::zlib::inflate_stream inflate_strm_ = {};
33 std::unique_ptr<std::array<char, chunk_size>> in_buf_ = nullptr;
34 std::unique_ptr<std::array<char, chunk_size>> out_buf_ = nullptr;
35
36 auto inflate_chunk(beast::error_code& ec) -> void
37 {
38 assert(zs_.avail_in > 0);
39 zs_.next_in = in_buf_->data();
40
41 do
42 {
43 zs_.avail_out = out_buf_->size();
44 zs_.next_out = out_buf_->data();
45
46 inflate_strm_.write(zs_, beast::zlib::Flush::none, ec);
47 assert(ec != beast::zlib::error::stream_error);
48 if (ec == beast::zlib::error::need_buffers)
49 ec = {};
50 if (ec == beast::zlib::error::end_of_stream)
51 {
52 ec = {};
53 stream_ended_ = true;
54 }
55 if (ec)
56 break;
57
58 auto have = chunk_size - zs_.avail_out;
59 auto cbuf =
60 net::buffer(static_cast<void const*>(out_buf_->data()), have);
61
62 auto inner_ec = beast::error_code{};
63 do
64 cbuf += r_.put(cbuf, inner_ec);
65 while (cbuf.size() > 0 && !inner_ec);
66 if (inner_ec)
67 {
68 ec = inner_ec;
69 break;
70 }
71 }
72 while (zs_.avail_out == 0);
73
74 // In the last case (stream_ended_), the user has sent too much data
75 assert(zs_.avail_in == 0 || ec || stream_ended_);
76 }
77
78 public:
79 template <bool isRequest, bhttp::concepts::fields Fields>
80 explicit reader(bhttp::header<isRequest, Fields>& hdr, value_type& v)
81 : r_{hdr, v}
82 {
83 }
84
85 auto
86 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
87 -> void
88 {
89 in_buf_.reset(new std::array<char, chunk_size>{});
90 out_buf_.reset(new std::array<char, chunk_size>{});
91 ec = {};
92 }
93
94 auto
95 put(beast::concepts::const_buffer_sequence auto b,
96 beast::error_code& ec) noexcept -> std::size_t
97 {
98 auto in_buf = net::buffer(in_buf_->data(), in_buf_->size());
99 in_buf += zs_.avail_in;
100
101 auto consumed_from_b = net::buffer_copy(in_buf, b);
102 zs_.avail_in += consumed_from_b;
103
104 if (zs_.avail_in == in_buf_->size())
105 inflate_chunk(ec);
106 else
107 ec = {};
108
109 return consumed_from_b;
110 }
111
112 auto finish(beast::error_code& ec) noexcept -> void
113 {
114 ec = {};
115 if (zs_.avail_in > 0)
116 inflate_chunk(ec);
117 if (!ec && !stream_ended_)
118 ec = beast::zlib::error::stream_error;
119 if (stream_ended_ && zs_.avail_in > 0)
120 // client sent data past deflate stream end
121 ec = beast::zlib::error::stream_error;
122
123 in_buf_.reset();
124 out_buf_.reset();
125 inflate_strm_.reset();
126 if (!ec)
127 {
128 r_.finish(ec);
129 }
130 }
131 };
132};
133
134} // namespace routemon::http::ext::raw_deflate
diff --git a/server/src/http/handler.cpp b/server/src/http/handler.cpp
new file mode 100644
index 0000000..d755c16
--- /dev/null
+++ b/server/src/http/handler.cpp
@@ -0,0 +1,348 @@
1module;
2
3#include <boost/asio/awaitable.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <boost/config.hpp>
7#include <boost/json.hpp>
8
9#include <openssl/crypto.h>
10
11module routemon:http.handler$impl;
12
13import std;
14import :gpx;
15import :http.server;
16import :http.ext.gpx;
17import :http.ext.hmac_openssl;
18import :http.ext.json;
19import :http.ext.raw_deflate;
20
21namespace beast = boost::beast;
22namespace json = boost::json;
23namespace net = boost::asio;
24
25namespace routemon::http {
26
27auto parse_timestamp_mins(std::string_view in)
28 -> std::optional<time::timestamp<std::chrono::minutes>>
29{
30 auto res = time::timestamp<std::chrono::minutes>{};
31 auto is = std::istringstream{in};
32 is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res);
33 return is.fail() ? std::nullopt : std::make_optional(res);
34}
35
36auto parse_timestamp_secs(std::string_view in)
37 -> std::optional<time::timestamp<std::chrono::seconds>>
38{
39 auto res = time::timestamp<std::chrono::seconds>{};
40 auto is = std::istringstream{in};
41 is >> std::chrono::parse("%FT%TZ", res);
42 return is.fail() ? std::nullopt : std::make_optional(res);
43}
44
45auto handler::handle_process_gpx(l0_ctx ctx, core::readable_request r)
46 -> net::awaitable<core::presponse>
47{
48 auto l =
49 l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string());
50
51 auto cp_begin = time::timestamp<std::chrono::minutes>{};
52 auto cp_end = time::timestamp<std::chrono::minutes>{};
53
54 auto const params = ctx.target.params();
55 if (auto it = params.find("cpbegin"); it != params.end())
56 {
57 auto mts = parse_timestamp_mins((*it).value);
58 if (!mts)
59 {
60 auto tpl = problem::tpl{
61 .status = bhttp::status::bad_request,
62 .title = translate("Query parameter has bad value"),
63 .type_uri =
64 "https://routemon.fautchen.eu/problems/query-param-bad-value",
65 };
66 co_return core::problem_rsp(
67 ctx, tpl.instantiate(), core::keep_alive{false});
68 }
69 cp_begin = *mts;
70
71 ++it;
72 if (it != params.end() && (*it).key == "cpbegin")
73 {
74 auto tpl = problem::tpl{
75 .status = bhttp::status::bad_request,
76 .title = translate("Query parameter provided too many times"),
77 .type_uri = "https://routemon.fautchen.eu/problems/"
78 "query-param-too-many-occurrences",
79 };
80 co_return core::problem_rsp(
81 ctx, tpl.instantiate(), core::keep_alive{false});
82 }
83 }
84 else
85 {
86 auto tpl = problem::tpl{
87 .status = bhttp::status::bad_request,
88 .title = translate("Required query parameter not provided"),
89 .type_uri = "https://routemon.fautchen.eu/problems/"
90 "required-query-param-not-provided",
91 };
92 co_return core::problem_rsp(
93 ctx, tpl.instantiate(), core::keep_alive{false});
94 }
95 if (auto it = params.find("cpend"); it != params.end())
96 {
97 auto mts = parse_timestamp_mins((*it).value);
98 if (!mts)
99 {
100 auto tpl = problem::tpl{
101 .status = bhttp::status::bad_request,
102 .title = translate("Query parameter has bad value"),
103 .type_uri =
104 "https://routemon.fautchen.eu/problems/query-param-bad-value",
105 };
106 co_return core::problem_rsp(
107 ctx, tpl.instantiate(), core::keep_alive{false});
108 }
109 cp_end = *mts;
110
111 ++it;
112 if (it != params.end() && (*it).key == "cpend")
113 {
114 auto tpl = problem::tpl{
115 .status = bhttp::status::bad_request,
116 .title = translate("Query parameter provided too many times"),
117 .type_uri = "https://routemon.fautchen.eu/problems/"
118 "query-param-too-many-occurrences",
119 };
120 co_return core::problem_rsp(
121 ctx, tpl.instantiate(), core::keep_alive{false});
122 }
123 }
124 else
125 {
126 auto tpl = problem::tpl{
127 .status = bhttp::status::bad_request,
128 .title = translate("Required query parameter not provided"),
129 .type_uri = "https://routemon.fautchen.eu/problems/"
130 "required-query-param-not-provided",
131 };
132 co_return core::problem_rsp(
133 ctx, tpl.instantiate(), core::keep_alive{false});
134 }
135
136 if (cp_begin >= cp_end)
137 {
138 auto tpl = problem::tpl{
139 .status = bhttp::status::bad_request,
140 .title = translate("Invalid check period provided"),
141 .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period",
142 };
143 co_return core::problem_rsp(
144 ctx,
145 tpl.instantiate().set_detail(translate(
146 "Begin of check period must be before end of check period")),
147 core::keep_alive{false});
148 }
149 auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end};
150
151 auto gpx_file = gpx::file{};
152 try
153 {
154 l.debug("Reading GPX request body");
155 auto const before_read_gpx = chrono::steady_clock::now();
156 auto parse_res =
157 r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw"
158 ? std::move((co_await core::read_request<
159 ext::raw_deflate::body<ext::gpx::body>
160 >(ctx, std::move(r)))
161 .body())
162 : std::move((co_await core::read_request<ext::gpx::body>(
163 ctx, std::move(r)))
164 .body());
165 l.debug(
166 "Read GPX request body in {}; init took {}, actual parsing {}, "
167 "finishing {}",
168 chrono::duration<double, std::milli>{
169 chrono::steady_clock::now() - before_read_gpx
170 },
171 chrono::duration<double, std::milli>{parse_res.init_parse_duration()},
172 chrono::duration<double, std::milli>{parse_res.put_parse_duration()},
173 chrono::duration<double, std::milli>{
174 parse_res.finish_parse_duration()
175 });
176 gpx_file = std::move(parse_res.unwrap());
177 }
178 catch (std::exception& ex)
179 {
180 l_.warn("Failed to parse GPX file: {}", ex.what());
181 // TODO: more detailed problem reporting
182 auto tpl = problem::tpl{
183 .status = bhttp::status::bad_request,
184 .title = translate("Failed to parse GPX file"),
185 .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed",
186 };
187 co_return core::problem_rsp(
188 ctx, tpl.instantiate(), core::keep_alive{false});
189 }
190
191 // TODO: catch handler exceptions and return 500 when raised?
192 // (keep-alive depends on whether whole request was read)
193 auto mres = inner_.process_gpx(
194 ctx.trace_id, std::move(gpx_file),
195 time::period_seq<std::chrono::minutes>{cp});
196 if (!mres)
197 {
198 auto tpl = problem::tpl{
199 .status = bhttp::status::internal_server_error,
200 .title = translate("Internal server error"),
201 .type_uri = "https://routemon.fautchen.eu/problems/"
202 "internal-server-error",
203 };
204 co_return core::problem_rsp(ctx, tpl.instantiate(), core::keep_alive{true});
205 }
206
207 auto rsp = core::make_rsp<bhttp::string_body>(
208 bhttp::status::ok, core::keep_alive{true});
209 rsp.set(bhttp::field::content_type, "application/json");
210 rsp.body() = json::serialize(json::value_from(*mres));
211 rsp.prepare_payload();
212 co_return rsp;
213}
214
215auto handler::handle_sysinfo(l0_ctx ctx, core::readable_request r)
216 -> net::awaitable<core::presponse>
217{
218 auto req = co_await core::read_empty_request(ctx, std::move(r));
219 auto info = inner_.sysinfo();
220
221 auto rsp = core::make_rsp<bhttp::string_body>(
222 bhttp::status::ok, core::keep_alive{true});
223 rsp.set(bhttp::field::content_type, "application/json");
224 rsp.body() = json::serialize(json::value_from(info));
225 rsp.prepare_payload();
226 co_return rsp;
227}
228
229auto decode_hexnib(char c) -> std::optional<std::uint8_t>
230{
231 if ('a' <= c && c <= 'f')
232 return c - 'a' + 10;
233 if ('A' <= c && c <= 'F')
234 return c - 'A' + 10;
235 if ('0' <= c && c <= '9')
236 return c - '0';
237 return std::nullopt;
238}
239
240auto handler::handle_rwgps_webhook(l0_ctx ctx, core::readable_request r)
241 -> net::awaitable<core::presponse>
242{
243 if (r.p->get()[bhttp::field::content_type] != "application/json")
244 {
245 // TODO: 415 Unsupported Media Type
246 // (respond Accept-Post: application/json)
247 throw std::runtime_error{"unhandled: unsupported media type provided"};
248 }
249
250 auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]);
251 if (!mrwgps_ts)
252 {
253 // TODO: 400 Bad Request
254 throw std::runtime_error{
255 "failed to parse ISO 8601 date/time in x-rwgps-datetime header"
256 };
257 }
258
259 // TODO: better to instead copy the expected API key to a buffer of
260 // (at least) the size of the input API key and to compare those two
261 // buffers? Then this operation should be Ω/Θ(API key provided in
262 // request)
263 auto req_api_key = r.p->get()["x-rwgps-api-key"];
264 auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X');
265 std::memcpy(
266 req_api_key_copy.data(), req_api_key.data(),
267 std::min(req_api_key.size(), rwgps_creds_->api_key().size()));
268
269 if (CRYPTO_memcmp(
270 req_api_key_copy.data(), rwgps_creds_->api_key().data(),
271 rwgps_creds_->api_key().size()))
272 {
273 // TODO: Unauthorized
274 // TODO: constant-time comparison
275 throw std::runtime_error{"unhandled: mismatching API key provided"};
276 }
277
278 auto rwgps_sig = r.p->get()["x-rwgps-signature"];
279 auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{};
280
281 if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size())
282 {
283 // TODO: Bad request
284 throw std::runtime_error{"unhandled: bad signature provided"};
285 }
286
287 for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate)
288 {
289 auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]);
290 auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]);
291 if (!mhi || !mlo)
292 {
293 throw std::runtime_error{"TODO: INVALID SIGNATURE"};
294 }
295 static_assert(std::same_as<decltype(b), std::uint8_t&>);
296 b = static_cast<std::uint8_t>((*mhi << 4) | *mlo);
297 }
298
299 auto req = co_await core::
300 read_request<http::ext::hmac_openssl::body<http::ext::json::body>>(
301 ctx, std::move(r), rwgps_creds_->api_secret());
302
303 if (req.body().mac() != rwgps_sig_decoded)
304 {
305 throw std::runtime_error{"unhandled: incorrect signature provided"};
306 }
307
308 // TODO: handle conversion failure gracefully
309 inner_.rwgps_webhook(
310 *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get()));
311
312 auto rsp = core::make_rsp<bhttp::empty_body>(
313 bhttp::status::ok, core::keep_alive{true});
314 rsp.prepare_payload();
315 co_return rsp;
316}
317
318handler::handler(
319 log::logger const& l, api::handler&& inner,
320 std::shared_ptr<rwgps::credentials> rwgps_creds)
321 : l_{l.sub("handler")}, inner_{std::move(inner)},
322 rwgps_creds_{std::move(rwgps_creds)}
323{
324}
325
326auto handler::make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>>
327{
328 auto handler = [this]<class MemFn>(MemFn member)
329 { return std::bind_front(member, this); };
330
331 return core::dtree<core::routed_ctx<outer_ctx>>{}.named_subtrees({
332 {"gpx", core::dtree<l0_ctx>{{
333 .post = handler(&handler::handle_process_gpx),
334 }}
335 .no_subtrees()},
336 {"sysinfo", core::dtree<l0_ctx>{{
337 .get = handler(&handler::handle_sysinfo),
338 }}
339 .no_subtrees()},
340 {"webhook", core::dtree<l0_ctx>{}.named_subtrees({
341 {"rwgps", core::dtree<l0_ctx>{
342 {.post = handler(&handler::handle_rwgps_webhook)}
343 }.no_subtrees()},
344 })},
345 });
346}
347
348} // namespace routemon::http
diff --git a/server/src/http/handler.cppm b/server/src/http/handler.cppm
new file mode 100644
index 0000000..d28e765
--- /dev/null
+++ b/server/src/http/handler.cppm
@@ -0,0 +1,41 @@
1module;
2
3#include <boost/asio/awaitable.hpp>
4
5export module routemon:http.handler;
6
7import :api;
8import :http.core.server;
9import :rwgps;
10
11namespace routemon::http {
12
13class handler
14{
15 log::logger l_;
16 api::handler inner_;
17 std::shared_ptr<rwgps::credentials> rwgps_creds_;
18
19public:
20 using outer_ctx = core::base_ctx;
21 using l0_ctx = core::routed_ctx<outer_ctx>;
22
23private:
24 auto handle_process_gpx(l0_ctx ctx, core::readable_request r)
25 -> net::awaitable<core::presponse>;
26
27 auto handle_sysinfo(l0_ctx ctx, core::readable_request r)
28 -> net::awaitable<core::presponse>;
29
30 auto handle_rwgps_webhook(l0_ctx ctx, core::readable_request r)
31 -> net::awaitable<core::presponse>;
32
33public:
34 handler(
35 log::logger const& l, api::handler&& inner,
36 std::shared_ptr<rwgps::credentials> rwgps_creds);
37
38 auto make_routes() -> core::route_tree<core::routed_ctx<outer_ctx>>;
39};
40
41} // namespace routemon::http
diff --git a/server/src/http/server.cpp b/server/src/http/server.cpp
new file mode 100644
index 0000000..ddb8243
--- /dev/null
+++ b/server/src/http/server.cpp
@@ -0,0 +1,61 @@
1module;
2
3#include <boost/asio/as_tuple.hpp>
4#include <boost/asio/awaitable.hpp>
5#include <boost/asio/co_spawn.hpp>
6#include <boost/asio/ip/tcp.hpp>
7#include <boost/beast/core.hpp>
8#include <boost/beast/http.hpp>
9#include <boost/beast/zlib.hpp>
10#include <boost/config.hpp>
11#include <boost/json.hpp>
12#include <boost/locale/generator.hpp>
13
14#include <expat.h>
15
16#include <openssl/crypto.h>
17
18module routemon:http.server$impl;
19
20import std;
21import :gpx;
22import :http.server;
23import :http.ext.hmac_openssl;
24import :http.ext.json;
25
26namespace beast = boost::beast;
27namespace chrono = std::chrono;
28namespace json = boost::json;
29namespace net = boost::asio;
30using tcp = boost::asio::ip::tcp;
31
32namespace routemon::http {
33
34auto server::make_global_middleware(config::http_server const& cfg)
35 -> core::middleware_t<core::base_ctx, handler::outer_ctx>
36{
37 return core::
38 middleware_compose<core::base_ctx, core::base_ctx, core::base_ctx>(
39 core::expose_content_language_middleware<core::base_ctx>,
40 middleware_compose<core::base_ctx, core::base_ctx, core::base_ctx>(
41 core::expose_trace_id_middleware<core::base_ctx>,
42 core::cors_middleware<core::base_ctx>(cfg.allow_origins)));
43}
44
45server::server(
46 log::logger const& l, config::http_server const& cfg,
47 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
48 api::handler&& inner)
49 : handler_{l, std::move(inner), std::move(rwgps_creds)},
50 srv_{
51 l,
52 core::router{
53 l, std::move(lsel), make_global_middleware(cfg), handler_.make_routes()
54 }
55 }
56{
57}
58
59auto server::spawn(net::io_context& ioc) -> void { srv_.spawn(ioc); }
60
61} // namespace routemon::http
diff --git a/server/src/http/server.cppm b/server/src/http/server.cppm
new file mode 100644
index 0000000..7b30deb
--- /dev/null
+++ b/server/src/http/server.cppm
@@ -0,0 +1,31 @@
1module;
2
3#include <boost/asio/io_context.hpp>
4
5export module routemon:http.server;
6
7import :api;
8import :http.core.server;
9import :http.handler;
10import :rwgps;
11
12namespace routemon::http {
13
14export class server
15{
16 handler handler_;
17 core::server srv_;
18
19 static auto make_global_middleware(config::http_server const& cfg)
20 -> core::middleware_t<core::base_ctx, handler::outer_ctx>;
21
22public:
23 server(
24 log::logger const& l, config::http_server const& cfg,
25 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
26 api::handler&& inner);
27
28 auto spawn(net::io_context& ioc) -> void;
29};
30
31} // namespace routemon::http
diff --git a/server/src/main.cpp b/server/src/main.cpp
index df750d9..f5d233b 100644
--- a/server/src/main.cpp
+++ b/server/src/main.cpp
@@ -161,7 +161,7 @@ auto server_main(routemon::log::logger& l, routemon::config::app config)
161 l.info("Loading situations finished in {}", dur_load); 161 l.info("Loading situations finished in {}", dur_load);
162 162
163 auto handler = routemon::api::handler{l, dbc, std::move(pub)}; 163 auto handler = routemon::api::handler{l, dbc, std::move(pub)};
164 auto http_server = routemon::srv::server{ 164 auto http_server = routemon::http::server{
165 l, config.http_server, rwgps_creds, std::move(lsel), std::move(handler), 165 l, config.http_server, rwgps_creds, std::move(lsel), std::move(handler),
166 }; 166 };
167 http_server.spawn(ioc); 167 http_server.spawn(ioc);
@@ -175,11 +175,12 @@ auto migrate_main(
175 routemon::log::logger& l, routemon::config::app config, 175 routemon::log::logger& l, routemon::config::app config,
176 std::int64_t target_db_version) -> exit_status 176 std::int64_t target_db_version) -> exit_status
177{ 177{
178 auto m = std::unique_ptr<routemon::migrate::migrator>{}; 178 auto m = std::unique_ptr<routemon::database::migrator>{};
179 try 179 try
180 { 180 {
181 m.reset( 181 m.reset(new routemon::database::migrator{
182 new routemon::migrate::migrator{l, config.database.sqlite3_filename}); 182 l, config.database.sqlite3_filename, config.database.migrations_dir
183 });
183 } 184 }
184 catch (std::exception const& e) 185 catch (std::exception const& e)
185 { 186 {
diff --git a/server/src/routemon.cppm b/server/src/routemon.cppm
index 8946cf5..8f2acfd 100644
--- a/server/src/routemon.cppm
+++ b/server/src/routemon.cppm
@@ -1,12 +1,12 @@
1export module routemon; 1export module routemon;
2export import :api; 2export import :api;
3export import :config; 3export import :config;
4export import :database; 4export import :database.connection;
5export import :database.migrator;
5export import :datex2; 6export import :datex2;
6export import :gpx; 7export import :gpx;
8export import :http.server;
7export import :locale; 9export import :locale;
8export import :log; 10export import :log;
9export import :migrate;
10export import :srv;
11export import :rwgps; 11export import :rwgps;
12export import :util; 12export import :util;
diff --git a/server/src/rwgps.cppm b/server/src/rwgps.cppm
index 880ea3a..0aed7a3 100644
--- a/server/src/rwgps.cppm
+++ b/server/src/rwgps.cppm
@@ -6,7 +6,7 @@ module;
6export module routemon:rwgps; 6export module routemon:rwgps;
7 7
8import std; 8import std;
9import :http.client; 9import :http.core.client;
10import :log; 10import :log;
11 11
12namespace net = boost::asio; 12namespace net = boost::asio;
@@ -118,7 +118,7 @@ public:
118export class client 118export class client
119{ 119{
120 log::logger l_; 120 log::logger l_;
121 http::client hc_; 121 http::core::client hc_;
122 std::shared_ptr<credentials> creds_; 122 std::shared_ptr<credentials> creds_;
123 123
124 auto get_routes_page(std::size_t page) -> get_routes_response; 124 auto get_routes_page(std::size_t page) -> get_routes_response;
diff --git a/server/src/rwgps_webhook.cppm b/server/src/rwgps_webhook.cppm
deleted file mode 100644
index 5a1df37..0000000
--- a/server/src/rwgps_webhook.cppm
+++ /dev/null
@@ -1,237 +0,0 @@
1module;
2
3#include <boost/asio/ssl/error.hpp>
4#include <boost/beast/core.hpp>
5#include <boost/beast/http.hpp>
6#include <boost/json/stream_parser.hpp>
7
8#include <openssl/err.h>
9#include <openssl/evp.h>
10#include <openssl/params.h>
11
12export module routemon:rwgps.webhook;
13
14import :http.common;
15import :util;
16import std;
17
18namespace {
19
20namespace net = boost::asio;
21namespace json = boost::json;
22
23} // namespace
24
25namespace routemon::rwgps::webhook {
26
27// TODO: constrain T? What are appropriate constraints?
28template <typename T>
29class hmac_readable
30{
31 std::string_view key_;
32 std::optional<std::array<std::uint8_t, 32>> mac_;
33 T res_;
34
35 template <bhttp::concepts::body_reader Sub>
36 friend struct hmac_body_reader;
37
38public:
39 template <typename... Args>
40 explicit hmac_readable(std::string_view key, Args&&... args)
41 : key_{key}, res_{std::forward<Args>(args)...}
42 {
43 }
44
45 template <class Self>
46 constexpr auto get(this Self&& self) -> auto&&
47 {
48 return std::forward<Self>(self).res_;
49 }
50
51 auto mac() const -> std::optional<std::array<std::uint8_t, 32>>
52 {
53 return mac_;
54 }
55};
56
57template <bhttp::concepts::body_reader Sub>
58class hmac_body_reader
59{
60 EVP_MAC* mac_ = nullptr;
61 EVP_MAC_CTX* ctx_ = nullptr;
62
63 util::not_null<hmac_readable<typename Sub::value_type>*> v_;
64 Sub::reader subr_;
65 beast::error_code ec_;
66
67public:
68 template <bool isRequest, bhttp::concepts::fields Fields>
69 explicit hmac_body_reader(
70 bhttp::header<isRequest, Fields>& h,
71 hmac_readable<typename Sub::value_type>& v)
72 : v_{util::not_null{&v}},
73 subr_{h, v.get()} // we are not supposed to use v yet, but this just
74 // computes an address, so it should be fine
75 {
76 }
77
78 ~hmac_body_reader()
79 {
80 ::EVP_MAC_CTX_free(ctx_);
81 ::EVP_MAC_free(mac_);
82 }
83
84 // TODO: move to impl. unit.
85 auto init(boost::optional<std::uint64_t> n, beast::error_code& ec) noexcept
86 -> void
87 {
88 // https://docs.openssl.org/master/man3/EVP_MAC/#examples
89 mac_ = ::EVP_MAC_fetch(nullptr, "HMAC", nullptr);
90 if (!mac_)
91 {
92 ec_ = ec = make_error_code(std::errc::not_enough_memory);
93 return;
94 }
95
96 ctx_ = ::EVP_MAC_CTX_new(mac_);
97 if (!ctx_)
98 {
99 ec_ = ec = make_error_code(std::errc::not_enough_memory);
100 return;
101 }
102
103 char sha256[] = "SHA256";
104 ::OSSL_PARAM const params[] = {
105 OSSL_PARAM_utf8_string("digest", sha256, sizeof(sha256) - 1),
106 OSSL_PARAM_END
107 };
108 if (!::EVP_MAC_init(
109 ctx_, reinterpret_cast<unsigned char const*>(v_->key_.data()),
110 v_->key_.size(), params))
111 {
112 ec_ = ec = beast::error_code{
113 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
114 };
115 return;
116 }
117
118 subr_.init(n, ec);
119 }
120
121 auto
122 put(beast::concepts::const_buffer_sequence auto b,
123 beast::error_code& ec) noexcept -> std::size_t
124 {
125 if ((ec = ec_))
126 return 0uz;
127
128 auto const total_read = subr_.put(b, ec);
129 if (total_read > 0)
130 {
131 auto remaining = total_read;
132 for (auto const buf : beast::buffers_range(b))
133 {
134 auto const to_hash_from_this_buf = std::min(remaining, buf.size());
135 if (!::EVP_MAC_update(
136 ctx_, static_cast<unsigned char const*>(buf.data()),
137 to_hash_from_this_buf))
138 {
139 ec_ = ec = beast::error_code{
140 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
141 };
142 return total_read;
143 }
144 remaining -= to_hash_from_this_buf;
145 }
146 }
147 return total_read;
148 }
149
150 auto finish(beast::error_code& ec) noexcept
151 {
152 auto got_mac_len = 0uz;
153 auto got_mac = std::array<std::uint8_t, 32>{};
154 if (!::EVP_MAC_final(ctx_, got_mac.data(), &got_mac_len, got_mac.size()))
155 {
156 ec = beast::error_code{
157 static_cast<int>(::ERR_get_error()), net::error::get_ssl_category()
158 };
159 return;
160 }
161 assert(got_mac_len == got_mac.size());
162 v_->mac_ = got_mac;
163 subr_.finish(ec);
164 }
165};
166
167template <bhttp::concepts::body Sub>
168struct hmac_body
169{
170 using value_type = hmac_readable<typename Sub::value_type>;
171};
172
173template <bhttp::concepts::body Sub>
174 requires bhttp::concepts::body_reader<Sub>
175struct hmac_body<Sub>
176{
177 using value_type = hmac_readable<typename Sub::value_type>;
178
179 using reader = hmac_body_reader<Sub>;
180};
181
182struct json_body
183{
184 using value_type = json::value;
185
186 class reader
187 {
188 json::stream_parser p_;
189 util::not_null<value_type*> v_;
190
191 public:
192 template <bool isRequest, bhttp::concepts::fields Fields>
193 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v)
194 : v_{util::not_null{&v}}
195 {
196 }
197
198 // TODO: move to impl. unit.
199 auto
200 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
201 -> void
202 {
203 p_.reset();
204 ec = {};
205 }
206
207 auto
208 put(beast::concepts::const_buffer_sequence auto b,
209 beast::error_code& ec) noexcept -> std::size_t
210 {
211 ec = {};
212
213 auto wrote = 0uz;
214 for (auto const buf : beast::buffers_range(b))
215 {
216 p_.write(static_cast<char const*>(buf.data()), buf.size(), ec);
217 wrote += buf.size();
218 if (ec)
219 break;
220 }
221 return wrote;
222 }
223
224 auto finish(beast::error_code& ec) noexcept
225 {
226 p_.finish(ec);
227 if (ec)
228 return;
229 *v_ = p_.release();
230 }
231 };
232};
233
234static_assert(bhttp::concepts::body<hmac_body<json_body>>);
235static_assert(bhttp::concepts::body_reader<hmac_body<json_body>>);
236
237} // namespace routemon::rwgps::webhook
diff --git a/server/src/srv.cpp b/server/src/srv.cpp
deleted file mode 100644
index 287f838..0000000
--- a/server/src/srv.cpp
+++ /dev/null
@@ -1,684 +0,0 @@
1module;
2
3#include <boost/asio/as_tuple.hpp>
4#include <boost/asio/awaitable.hpp>
5#include <boost/asio/co_spawn.hpp>
6#include <boost/asio/ip/tcp.hpp>
7#include <boost/beast/core.hpp>
8#include <boost/beast/http.hpp>
9#include <boost/beast/zlib.hpp>
10#include <boost/config.hpp>
11#include <boost/json.hpp>
12#include <boost/locale/generator.hpp>
13
14#include <expat.h>
15
16#include <openssl/crypto.h>
17
18module routemon:srv$impl;
19
20import std;
21import :gpx;
22import :srv;
23import :rwgps.webhook;
24
25namespace beast = boost::beast;
26namespace chrono = std::chrono;
27namespace json = boost::json;
28namespace net = boost::asio;
29using tcp = boost::asio::ip::tcp;
30
31namespace routemon::srv {
32
33class gpx_parse_error_category_impl : public std::error_category
34{
35public:
36 auto name() const noexcept -> char const* override { return "gpx_parse"; }
37
38 auto message(int condition) const noexcept -> std::string override
39 {
40 std::ignore = condition;
41 return "failed to parse GPX file";
42 }
43};
44
45auto gpx_parse_error_category() noexcept -> gpx_parse_error_category_impl const&
46{
47 static auto const inst = gpx_parse_error_category_impl{};
48 return inst;
49}
50
51auto gpx_parse_error() noexcept -> std::error_code
52{
53 return std::error_code{1, gpx_parse_error_category()};
54}
55
56class gpx_parse_result
57{
58 chrono::steady_clock::duration init_parse_dur_;
59 chrono::steady_clock::duration put_parse_dur_;
60 chrono::steady_clock::duration finish_parse_dur_;
61 std::variant<std::exception_ptr, gpx::file> res_;
62
63public:
64 auto set_exception(std::exception_ptr ex) noexcept { res_ = ex; }
65 auto set_gpx_file(gpx::file&& f) noexcept { res_ = std::move(f); }
66
67 auto init_parse_duration(chrono::steady_clock::duration dur) noexcept
68 {
69 init_parse_dur_ = dur;
70 }
71 [[nodiscard]] auto init_parse_duration() const noexcept
72 -> chrono::steady_clock::duration
73 {
74 return init_parse_dur_;
75 }
76 auto put_parse_duration(chrono::steady_clock::duration dur) noexcept
77 {
78 put_parse_dur_ = dur;
79 }
80 [[nodiscard]] auto put_parse_duration() const noexcept
81 -> chrono::steady_clock::duration
82 {
83 return put_parse_dur_;
84 }
85 auto finish_parse_duration(chrono::steady_clock::duration dur) noexcept
86 {
87 finish_parse_dur_ = dur;
88 }
89 [[nodiscard]] auto finish_parse_duration() const noexcept
90 -> chrono::steady_clock::duration
91 {
92 return finish_parse_dur_;
93 }
94
95 auto unwrap() -> gpx::file&&
96 {
97 return std::visit(
98 util::overloaded{
99 [](std::exception_ptr ex) -> gpx::file&&
100 {
101 if (ex)
102 std::rethrow_exception(ex);
103 else
104 throw std::runtime_error{"no GPX file parse result available"};
105 },
106 [](gpx::file&& f) -> gpx::file&& { return std::move(f); },
107 },
108 std::move(res_));
109 }
110};
111
112struct readable_gpx_body
113{
114 using value_type = gpx_parse_result;
115
116 class reader
117 {
118 gpx::reader r_;
119 util::not_null<value_type*> res_;
120 std::inplace_vector<char, 4096> buf_;
121
122 public:
123 template <bool isRequest, bhttp::concepts::fields Fields>
124 explicit reader(bhttp::header<isRequest, Fields>&, value_type& v) : res_{&v}
125 {
126 res_->init_parse_duration({});
127 res_->put_parse_duration({});
128 res_->finish_parse_duration({});
129 }
130
131 // The following methods (which are called by Beast) are marked
132 // noexcept, since Beast does not ensure that exceptions thrown
133 // here are appropriately directed to the caller of
134 // (async_)read(_some), so throwing here might cause the program
135 // to crash.
136
137 auto
138 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
139 -> void
140 {
141 auto const init_start = chrono::steady_clock::now();
142 try
143 {
144 r_.init();
145 ec = {};
146 }
147 catch (std::exception& ex)
148 {
149 res_->set_exception(std::current_exception());
150 ec = gpx_parse_error();
151 }
152 res_->init_parse_duration(chrono::steady_clock::now() - init_start);
153 }
154
155 auto
156 put(beast::concepts::const_buffer_sequence auto b,
157 beast::error_code& ec) noexcept -> std::size_t
158 {
159 auto const put_start = chrono::steady_clock::now();
160 auto total = 0uz;
161 try
162 {
163 for (auto cur_in_buf : beast::buffers_range(b))
164 {
165 while (cur_in_buf.size() > 0)
166 {
167 auto to_read =
168 std::min(cur_in_buf.size(), buf_.max_size() - buf_.size());
169 buf_.append_range(
170 std::span{
171 static_cast<char const*>(cur_in_buf.data()), to_read
172 });
173 cur_in_buf += to_read;
174 total += to_read;
175
176 if (buf_.size() == buf_.max_size())
177 {
178 r_.put(std::string_view{buf_});
179 buf_.clear();
180 }
181 }
182 }
183 ec = {};
184 }
185 catch (std::exception& ex)
186 {
187 res_->set_exception(std::current_exception());
188 ec = gpx_parse_error();
189 }
190 res_->put_parse_duration(
191 res_->put_parse_duration()
192 + (chrono::steady_clock::now() - put_start));
193 return total;
194 }
195
196 auto finish(beast::error_code& ec) noexcept
197 {
198 auto const finish_start = chrono::steady_clock::now();
199 try
200 {
201 if (buf_.size() > 0)
202 {
203 r_.put(std::string_view{buf_});
204 buf_.clear();
205 }
206
207 res_->set_gpx_file(r_.finish());
208 ec = {};
209 }
210 catch (std::exception& ex)
211 {
212 res_->set_exception(std::current_exception());
213 ec = gpx_parse_error();
214 }
215 res_->finish_parse_duration(chrono::steady_clock::now() - finish_start);
216 }
217 };
218};
219static_assert(bhttp::concepts::body<readable_gpx_body>);
220static_assert(bhttp::concepts::body_reader<readable_gpx_body>);
221
222template <bhttp::concepts::body_reader Inner>
223struct raw_deflate_body
224{
225 using value_type = Inner::value_type;
226
227 class reader
228 {
229 static constexpr auto const chunk_size = 16384;
230
231 Inner::reader r_;
232 bool stream_ended_ = false;
233 beast::zlib::z_params zs_ = {};
234 beast::zlib::inflate_stream inflate_strm_ = {};
235 std::unique_ptr<std::array<char, chunk_size>> in_buf_ = nullptr;
236 std::unique_ptr<std::array<char, chunk_size>> out_buf_ = nullptr;
237
238 auto inflate_chunk(beast::error_code& ec) -> void
239 {
240 assert(zs_.avail_in > 0);
241 zs_.next_in = in_buf_->data();
242
243 do
244 {
245 zs_.avail_out = out_buf_->size();
246 zs_.next_out = out_buf_->data();
247
248 inflate_strm_.write(zs_, beast::zlib::Flush::none, ec);
249 assert(ec != beast::zlib::error::stream_error);
250 if (ec == beast::zlib::error::need_buffers)
251 ec = {};
252 if (ec == beast::zlib::error::end_of_stream)
253 {
254 ec = {};
255 stream_ended_ = true;
256 }
257 if (ec)
258 break;
259
260 auto have = chunk_size - zs_.avail_out;
261 auto cbuf =
262 net::buffer(static_cast<void const*>(out_buf_->data()), have);
263
264 auto inner_ec = beast::error_code{};
265 do
266 cbuf += r_.put(cbuf, inner_ec);
267 while (cbuf.size() > 0 && !inner_ec);
268 if (inner_ec)
269 {
270 ec = inner_ec;
271 break;
272 }
273 }
274 while (zs_.avail_out == 0);
275
276 // In the last case (stream_ended_), the user has sent too much data
277 assert(zs_.avail_in == 0 || ec || stream_ended_);
278 }
279
280 public:
281 template <bool isRequest, bhttp::concepts::fields Fields>
282 explicit reader(bhttp::header<isRequest, Fields>& hdr, value_type& v)
283 : r_{hdr, v}
284 {
285 }
286
287 auto
288 init(boost::optional<std::uint64_t> /* n */, beast::error_code& ec) noexcept
289 -> void
290 {
291 in_buf_.reset(new std::array<char, chunk_size>{});
292 out_buf_.reset(new std::array<char, chunk_size>{});
293 ec = {};
294 }
295
296 auto
297 put(beast::concepts::const_buffer_sequence auto b,
298 beast::error_code& ec) noexcept -> std::size_t
299 {
300 auto in_buf = net::buffer(in_buf_->data(), in_buf_->size());
301 in_buf += zs_.avail_in;
302
303 auto consumed_from_b = net::buffer_copy(in_buf, b);
304 zs_.avail_in += consumed_from_b;
305
306 if (zs_.avail_in == in_buf_->size())
307 inflate_chunk(ec);
308 else
309 ec = {};
310
311 return consumed_from_b;
312 }
313
314 auto finish(beast::error_code& ec) noexcept
315 {
316 ec = {};
317 if (zs_.avail_in > 0)
318 inflate_chunk(ec);
319 if (!ec && !stream_ended_)
320 ec = beast::zlib::error::stream_error;
321 if (stream_ended_ && zs_.avail_in > 0)
322 // client sent data past deflate stream end
323 ec = beast::zlib::error::stream_error;
324
325 in_buf_.reset();
326 out_buf_.reset();
327 inflate_strm_.reset();
328 if (!ec)
329 {
330 r_.finish(ec);
331 }
332 }
333 };
334};
335
336auto parse_timestamp_mins(std::string_view in)
337 -> std::optional<time::timestamp<std::chrono::minutes>>
338{
339 auto res = time::timestamp<std::chrono::minutes>{};
340 auto is = std::istringstream{in};
341 is >> std::chrono::parse("%Y-%m-%dT%H:%MZ", res);
342 return is.fail() ? std::nullopt : std::make_optional(res);
343}
344
345auto handler::handle_process_gpx(l0_ctx ctx, http::readable_request r)
346 -> net::awaitable<http::presponse>
347{
348 auto l =
349 l_.sub("handle_process_gpx").with("trace_id", ctx.trace_id.as_string());
350
351 auto cp_begin = time::timestamp<std::chrono::minutes>{};
352 auto cp_end = time::timestamp<std::chrono::minutes>{};
353
354 auto const params = ctx.target.params();
355 if (auto it = params.find("cpbegin"); it != params.end())
356 {
357 auto mts = parse_timestamp_mins((*it).value);
358 if (!mts)
359 {
360 auto tpl = problem::tpl{
361 .status = bhttp::status::bad_request,
362 .title = translate("Query parameter has bad value"),
363 .type_uri =
364 "https://routemon.fautchen.eu/problems/query-param-bad-value",
365 };
366 co_return http::problem_rsp(
367 ctx, tpl.instantiate(), http::keep_alive{false});
368 }
369 cp_begin = *mts;
370
371 ++it;
372 if (it != params.end() && (*it).key == "cpbegin")
373 {
374 auto tpl = problem::tpl{
375 .status = bhttp::status::bad_request,
376 .title = translate("Query parameter provided too many times"),
377 .type_uri = "https://routemon.fautchen.eu/problems/"
378 "query-param-too-many-occurrences",
379 };
380 co_return http::problem_rsp(
381 ctx, tpl.instantiate(), http::keep_alive{false});
382 }
383 }
384 else
385 {
386 auto tpl = problem::tpl{
387 .status = bhttp::status::bad_request,
388 .title = translate("Required query parameter not provided"),
389 .type_uri = "https://routemon.fautchen.eu/problems/"
390 "required-query-param-not-provided",
391 };
392 co_return http::problem_rsp(
393 ctx, tpl.instantiate(), http::keep_alive{false});
394 }
395 if (auto it = params.find("cpend"); it != params.end())
396 {
397 auto mts = parse_timestamp_mins((*it).value);
398 if (!mts)
399 {
400 auto tpl = problem::tpl{
401 .status = bhttp::status::bad_request,
402 .title = translate("Query parameter has bad value"),
403 .type_uri =
404 "https://routemon.fautchen.eu/problems/query-param-bad-value",
405 };
406 co_return http::problem_rsp(
407 ctx, tpl.instantiate(), http::keep_alive{false});
408 }
409 cp_end = *mts;
410
411 ++it;
412 if (it != params.end() && (*it).key == "cpend")
413 {
414 auto tpl = problem::tpl{
415 .status = bhttp::status::bad_request,
416 .title = translate("Query parameter provided too many times"),
417 .type_uri = "https://routemon.fautchen.eu/problems/"
418 "query-param-too-many-occurrences",
419 };
420 co_return http::problem_rsp(
421 ctx, tpl.instantiate(), http::keep_alive{false});
422 }
423 }
424 else
425 {
426 auto tpl = problem::tpl{
427 .status = bhttp::status::bad_request,
428 .title = translate("Required query parameter not provided"),
429 .type_uri = "https://routemon.fautchen.eu/problems/"
430 "required-query-param-not-provided",
431 };
432 co_return http::problem_rsp(
433 ctx, tpl.instantiate(), http::keep_alive{false});
434 }
435
436 if (cp_begin >= cp_end)
437 {
438 auto tpl = problem::tpl{
439 .status = bhttp::status::bad_request,
440 .title = translate("Invalid check period provided"),
441 .type_uri = "https://routemon.fautchen.eu/problems/invalid-check-period",
442 };
443 co_return http::problem_rsp(
444 ctx,
445 tpl.instantiate().set_detail(translate(
446 "Begin of check period must be before end of check period")),
447 http::keep_alive{false});
448 }
449 auto cp = time::period<std::chrono::minutes>{cp_begin, cp_end};
450
451 auto gpx_file = gpx::file{};
452 try
453 {
454 l.debug("Reading GPX request body");
455 auto const before_read_gpx = chrono::steady_clock::now();
456 auto parse_res =
457 r.p->get()[bhttp::field::content_encoding] == "x-deflate-raw"
458 ? std::move((co_await http::
459 read_request<raw_deflate_body<readable_gpx_body>>(
460 ctx, std::move(r)))
461 .body())
462 : std::move((co_await http::read_request<readable_gpx_body>(
463 ctx, std::move(r)))
464 .body());
465 l.debug(
466 "Read GPX request body in {}; init took {}, actual parsing {}, "
467 "finishing {}",
468 chrono::duration<double, std::milli>{
469 chrono::steady_clock::now() - before_read_gpx
470 },
471 chrono::duration<double, std::milli>{parse_res.init_parse_duration()},
472 chrono::duration<double, std::milli>{parse_res.put_parse_duration()},
473 chrono::duration<double, std::milli>{
474 parse_res.finish_parse_duration()
475 });
476 gpx_file = std::move(parse_res.unwrap());
477 }
478 catch (std::exception& ex)
479 {
480 l_.warn("Failed to parse GPX file: {}", ex.what());
481 // TODO: more detailed problem reporting
482 auto tpl = problem::tpl{
483 .status = bhttp::status::bad_request,
484 .title = translate("Failed to parse GPX file"),
485 .type_uri = "https://routemon.fautchen.eu/problems/gpx-parse-failed",
486 };
487 co_return http::problem_rsp(
488 ctx, tpl.instantiate(), http::keep_alive{false});
489 }
490
491 // TODO: catch handler exceptions and return 500 when raised?
492 // (keep-alive depends on whether whole request was read)
493 auto mres = inner_.process_gpx(
494 ctx.trace_id, std::move(gpx_file),
495 time::period_seq<std::chrono::minutes>{cp});
496 if (!mres)
497 {
498 auto tpl = problem::tpl{
499 .status = bhttp::status::internal_server_error,
500 .title = translate("Internal server error"),
501 .type_uri = "https://routemon.fautchen.eu/problems/"
502 "internal-server-error",
503 };
504 co_return http::problem_rsp(ctx, tpl.instantiate(), http::keep_alive{true});
505 }
506
507 auto rsp = http::make_rsp<bhttp::string_body>(
508 bhttp::status::ok, http::keep_alive{true});
509 rsp.set(bhttp::field::content_type, "application/json");
510 rsp.body() = json::serialize(json::value_from(*mres));
511 rsp.prepare_payload();
512 co_return rsp;
513}
514
515auto handler::handle_sysinfo(l0_ctx ctx, http::readable_request r)
516 -> net::awaitable<http::presponse>
517{
518 auto req = co_await http::read_empty_request(ctx, std::move(r));
519 auto info = inner_.sysinfo();
520
521 auto rsp = http::make_rsp<bhttp::string_body>(
522 bhttp::status::ok, http::keep_alive{true});
523 rsp.set(bhttp::field::content_type, "application/json");
524 rsp.body() = json::serialize(json::value_from(info));
525 rsp.prepare_payload();
526 co_return rsp;
527}
528
529auto decode_hexnib(char c) -> std::optional<std::uint8_t>
530{
531 if ('a' <= c && c <= 'f')
532 return c - 'a' + 10;
533 if ('A' <= c && c <= 'F')
534 return c - 'A' + 10;
535 if ('0' <= c && c <= '9')
536 return c - '0';
537 return std::nullopt;
538}
539
540auto parse_timestamp_secs(std::string_view in)
541 -> std::optional<time::timestamp<std::chrono::seconds>>
542{
543 auto res = time::timestamp<std::chrono::seconds>{};
544 auto is = std::istringstream{in};
545 is >> std::chrono::parse("%FT%TZ", res);
546 return is.fail() ? std::nullopt : std::make_optional(res);
547}
548
549auto handler::handle_rwgps_webhook(l0_ctx ctx, http::readable_request r)
550 -> net::awaitable<http::presponse>
551{
552 if (r.p->get()[bhttp::field::content_type] != "application/json")
553 {
554 // TODO: 415 Unsupported Media Type
555 // (respond Accept-Post: application/json)
556 throw std::runtime_error{"unhandled: unsupported media type provided"};
557 }
558
559 auto mrwgps_ts = parse_timestamp_secs(r.p->get()["x-rwgps-datetime"]);
560 if (!mrwgps_ts)
561 {
562 // TODO: 400 Bad Request
563 throw std::runtime_error{
564 "failed to parse ISO 8601 date/time in x-rwgps-datetime header"
565 };
566 }
567
568 // TODO: better to instead copy the expected API key to a buffer of
569 // (at least) the size of the input API key and to compare those two
570 // buffers? Then this operation should be Ω/Θ(API key provided in
571 // request)
572 auto req_api_key = r.p->get()["x-rwgps-api-key"];
573 auto req_api_key_copy = std::string(rwgps_creds_->api_key().size(), 'X');
574 std::memcpy(
575 req_api_key_copy.data(), req_api_key.data(),
576 std::min(req_api_key.size(), rwgps_creds_->api_key().size()));
577
578 if (CRYPTO_memcmp(
579 req_api_key_copy.data(), rwgps_creds_->api_key().data(),
580 rwgps_creds_->api_key().size()))
581 {
582 // TODO: Unauthorized
583 // TODO: constant-time comparison
584 throw std::runtime_error{"unhandled: mismatching API key provided"};
585 }
586
587 auto rwgps_sig = r.p->get()["x-rwgps-signature"];
588 auto rwgps_sig_decoded = std::array<std::uint8_t, 32>{};
589
590 if (rwgps_sig.length() != 2 * rwgps_sig_decoded.size())
591 {
592 // TODO: Bad request
593 throw std::runtime_error{"unhandled: bad signature provided"};
594 }
595
596 for (auto [i, b] : rwgps_sig_decoded | std::views::enumerate)
597 {
598 auto mhi = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2]);
599 auto mlo = decode_hexnib(rwgps_sig[static_cast<std::size_t>(i) * 2 + 1]);
600 if (!mhi || !mlo)
601 {
602 throw std::runtime_error{"TODO: INVALID SIGNATURE"};
603 }
604 static_assert(std::same_as<decltype(b), std::uint8_t&>);
605 b = static_cast<std::uint8_t>((*mhi << 4) | *mlo);
606 }
607
608 auto req = co_await http::
609 read_request<rwgps::webhook::hmac_body<rwgps::webhook::json_body>>(
610 ctx, std::move(r), rwgps_creds_->api_secret());
611
612 if (req.body().mac() != rwgps_sig_decoded)
613 {
614 throw std::runtime_error{"unhandled: incorrect signature provided"};
615 }
616
617 // TODO: handle conversion failure gracefully
618 inner_.rwgps_webhook(
619 *mrwgps_ts, json::value_to<rwgps::webhook_request>(req.body().get()));
620
621 auto rsp = http::make_rsp<bhttp::empty_body>(
622 bhttp::status::ok, http::keep_alive{true});
623 rsp.prepare_payload();
624 co_return rsp;
625}
626
627handler::handler(
628 log::logger const& l, api::handler&& inner,
629 std::shared_ptr<rwgps::credentials> rwgps_creds)
630 : l_{l.sub("handler")}, inner_{std::move(inner)},
631 rwgps_creds_{std::move(rwgps_creds)}
632{
633}
634
635auto handler::make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>>
636{
637 auto handler = [this]<class MemFn>(MemFn member)
638 { return std::bind_front(member, this); };
639
640 return http::dtree<http::routed_ctx<outer_ctx>>{}.named_subtrees({
641 {"gpx", http::dtree<l0_ctx>{{
642 .post = handler(&handler::handle_process_gpx),
643 }}
644 .no_subtrees()},
645 {"sysinfo", http::dtree<l0_ctx>{{
646 .get = handler(&handler::handle_sysinfo),
647 }}
648 .no_subtrees()},
649 {"webhook", http::dtree<l0_ctx>{}.named_subtrees({
650 {"rwgps", http::dtree<l0_ctx>{
651 {.post = handler(&handler::handle_rwgps_webhook)}
652 }.no_subtrees()},
653 })},
654 });
655}
656
657auto server::make_global_middleware(config::http_server const& cfg)
658 -> http::middleware_t<http::base_ctx, handler::outer_ctx>
659{
660 return http::
661 middleware_compose<http::base_ctx, http::base_ctx, http::base_ctx>(
662 http::expose_content_language_middleware<http::base_ctx>,
663 middleware_compose<http::base_ctx, http::base_ctx, http::base_ctx>(
664 http::expose_trace_id_middleware<http::base_ctx>,
665 http::cors_middleware<http::base_ctx>(cfg.allow_origins)));
666}
667
668server::server(
669 log::logger const& l, config::http_server const& cfg,
670 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
671 api::handler&& inner)
672 : handler_{l, std::move(inner), std::move(rwgps_creds)},
673 srv_{
674 l,
675 http::router{
676 l, std::move(lsel), make_global_middleware(cfg), handler_.make_routes()
677 }
678 }
679{
680}
681
682auto server::spawn(net::io_context& ioc) -> void { srv_.spawn(ioc); }
683
684} // namespace routemon::srv
diff --git a/server/src/srv.cppm b/server/src/srv.cppm
deleted file mode 100644
index 2a389c9..0000000
--- a/server/src/srv.cppm
+++ /dev/null
@@ -1,58 +0,0 @@
1module;
2
3#include <boost/asio/awaitable.hpp>
4
5export module routemon:srv;
6
7import :api;
8import :http.server;
9import :rwgps;
10
11namespace routemon::srv {
12
13class handler
14{
15 log::logger l_;
16 api::handler inner_;
17 std::shared_ptr<rwgps::credentials> rwgps_creds_;
18
19public:
20 using outer_ctx = http::base_ctx;
21 using l0_ctx = http::routed_ctx<outer_ctx>;
22
23private:
24 auto handle_process_gpx(l0_ctx ctx, http::readable_request r)
25 -> net::awaitable<http::presponse>;
26
27 auto handle_sysinfo(l0_ctx ctx, http::readable_request r)
28 -> net::awaitable<http::presponse>;
29
30 auto handle_rwgps_webhook(l0_ctx ctx, http::readable_request r)
31 -> net::awaitable<http::presponse>;
32
33public:
34 handler(
35 log::logger const& l, api::handler&& inner,
36 std::shared_ptr<rwgps::credentials> rwgps_creds);
37
38 auto make_routes() -> http::route_tree<http::routed_ctx<outer_ctx>>;
39};
40
41export class server
42{
43 handler handler_;
44 http::server srv_;
45
46 static auto make_global_middleware(config::http_server const& cfg)
47 -> http::middleware_t<http::base_ctx, handler::outer_ctx>;
48
49public:
50 server(
51 log::logger const& l, config::http_server const& cfg,
52 std::shared_ptr<rwgps::credentials> rwgps_creds, locale::selector&& lsel,
53 api::handler&& inner);
54
55 auto spawn(net::io_context& ioc) -> void;
56};
57
58} // namespace routemon::srv
diff --git a/server/src/trace.cpp b/server/src/trace.cpp
index cc51604..d118fb1 100644
--- a/server/src/trace.cpp
+++ b/server/src/trace.cpp
@@ -4,7 +4,7 @@ import :trace;
4 4
5namespace routemon::trace { 5namespace routemon::trace {
6 6
7class psrng 7class prng
8{ 8{
9 mutable std::default_random_engine e_ = {}; 9 mutable std::default_random_engine e_ = {};
10 mutable std::uniform_int_distribution<std::uint64_t> distr_ = {}; 10 mutable std::uniform_int_distribution<std::uint64_t> distr_ = {};
@@ -17,9 +17,9 @@ public:
17 return distr_(e_); 17 return distr_(e_);
18 } 18 }
19 19
20 static auto instance() -> psrng const& 20 static auto instance() -> prng const&
21 { 21 {
22 static auto const inst = psrng{}; 22 static auto const inst = prng{};
23 return inst; 23 return inst;
24 } 24 }
25}; 25};
@@ -37,7 +37,7 @@ uuid7::uuid7()
37 if (std::countl_zero(unix_time_ms) < 16) 37 if (std::countl_zero(unix_time_ms) < 16)
38 throw std::runtime_error{"system time too great"}; 38 throw std::runtime_error{"system time too great"};
39 39
40 auto const& rng = psrng::instance(); 40 auto const& rng = prng::instance();
41 auto const rand1 = rng.next(); 41 auto const rand1 = rng.next();
42 auto const rand2 = rng.next(); 42 auto const rand2 = rng.next();
43 43