summaryrefslogtreecommitdiffstats
path: root/server/src/main.cpp
blob: f5d233b35ca390e6323ee689b09ff064abe295a6 (about) (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#include <boost/asio.hpp>
#include <malloc.h> // for malloc_trim(3)
#include <openssl/crypto.h>

import std;
import routemon;

namespace chrono = std::chrono;
namespace net = boost::asio;

using namespace std::literals::string_view_literals;

enum class exit_status
{
  success,
  failure,
  bad_usage,
};

struct secure_buf
{
  void* p;
  std::size_t size = 0;

  secure_buf(secure_buf const&) = delete;
  secure_buf(secure_buf&&) = delete;

  auto operator=(secure_buf const&) -> secure_buf& = delete;
  auto operator=(secure_buf&&) -> secure_buf& = delete;

  secure_buf(std::size_t size) : p{OPENSSL_malloc(size)}
  {
    if (!this->p)
      throw std::bad_alloc{};
  }

  ~secure_buf() { OPENSSL_clear_free(this->p, this->size); }
};

auto ltrim_ws(std::string_view s) -> std::string_view
{
  if (auto i = s.find_first_not_of(" \t\r\n"); i != std::string_view::npos)
    s.remove_prefix(i);
  return s;
}
auto rtrim_ws(std::string_view s) -> std::string_view
{
  if (auto i = s.find_last_not_of(" \t\r\n"); i != std::string_view::npos)
    return s.substr(0, i + 1);
  return s;
}
auto trim_ws(std::string_view s) -> std::string_view
{
  return rtrim_ws(ltrim_ws(s));
}

// TODO: make own secure string type using the OpenSSL primitives
template <std::size_t max_size>
auto read_secret_to_string(std::string const& filename) -> std::string
{
  static_assert(max_size <= 65536); // sounds reasonable enough?

  auto f = std::ifstream{filename, std::ios::binary};
  if (!f)
    throw std::system_error{
      errno, std::generic_category(),
      std::format("opening secret located at {}", filename)
    };
  auto buf_cap = max_size;
  auto buf = secure_buf{max_size};
  f.read(static_cast<char*>(buf.p), static_cast<std::streamsize>(buf_cap));
  buf.size = static_cast<std::size_t>(f.gcount());
  f.seekg(0, std::ios::end);
  if (f.peek() != std::ifstream::traits_type::eof())
    throw std::runtime_error{"secret is bigger than allowed"};

  return std::string{trim_ws(
      std::string_view{static_cast<char const*>(buf.p), buf.size})};
}

auto server_main(routemon::log::logger& l, routemon::config::app config)
    -> exit_status
{
  auto lgen = routemon::locale::make_generator();
  auto default_locale = lgen->generate("en_US.UTF-8");
  auto locales = {
    default_locale,
    lgen->generate("nl_NL.UTF-8"),
    lgen->generate("en_GB.UTF-8"),
  };
  auto lsel = routemon::locale::selector{locales, default_locale};

  auto ioc = net::io_context{1 /* concurrency hint */};

  auto dbc = std::shared_ptr<routemon::database::connection>{};
  try
  {
    dbc = routemon::database::open(config.database.sqlite3_filename);
  }
  catch (std::exception const& e)
  {
    l.with("filename", config.database.sqlite3_filename)
        .error("Failed to open database: {}", e.what());
    return exit_status::failure;
  }

  auto rwgps_creds = std::shared_ptr<routemon::rwgps::credentials>{};
  try
  {
    rwgps_creds.reset(new routemon::rwgps::credentials{
      // TODO: bad secrets handling. Too little information for proper error
      // reporting.
      read_secret_to_string<4096>(config.rwgps.api_key_filename),
      read_secret_to_string<4096>(config.rwgps.api_secret_filename),
      read_secret_to_string<4096>(config.rwgps.auth_token_filename),
    });
  }
  catch (std::exception const& e)
  {
    l.error("Failed to read RWGPS credentials: {}", e.what());
    return exit_status::failure;
  }

  l.with("filename", config.situations.datex2_filename)
      .info("Loading situations");
  auto const before_load = chrono::steady_clock::now();
  auto d2loader = routemon::datex2::loader{};
  auto pub = routemon::datex2::situation_publication{};
  try
  {
    pub =
        d2loader.load_situation_publication(config.situations.datex2_filename);
  }
  catch (std::exception const& e)
  {
    l.error("Failed to load DATEX II situations publication: {}", e.what());
    return exit_status::failure;
  }
  if (!d2loader.warnings().empty())
  {
    auto const& warns = d2loader.warnings();
    l.warn(
        "Encountered {} unique warning(s) while loading DATEX II situations "
        "publication",
        warns.size());
    auto i = 0uz;
    for (auto it = warns.begin(); it != warns.end();
         it = warns.upper_bound(*it))
    {
      l.warn("Warning {} (appeared {}×): {}", ++i, warns.count(*it), *it);
    }
  }
  // Processing the feed is by far the most memory-intensive operation
  // during the run time of this application (at the moment); the
  // resident set will likely never be this big again. So we ask libc
  // to return as much memory as possible to the OS.
  malloc_trim(0);
  auto const after_load = chrono::steady_clock::now();
  auto const dur_load =
      chrono::duration_cast<chrono::milliseconds>(after_load - before_load);
  l.info("Loading situations finished in {}", dur_load);

  auto handler = routemon::api::handler{l, dbc, std::move(pub)};
  auto http_server = routemon::http::server{
    l, config.http_server, rwgps_creds, std::move(lsel), std::move(handler),
  };
  http_server.spawn(ioc);
  ioc.run();

  l.error("I/O context stopped");
  return exit_status::failure;
}

auto migrate_main(
    routemon::log::logger& l, routemon::config::app config,
    std::int64_t target_db_version) -> exit_status
{
  auto m = std::unique_ptr<routemon::database::migrator>{};
  try
  {
    m.reset(new routemon::database::migrator{
      l, config.database.sqlite3_filename, config.database.migrations_dir
    });
  }
  catch (std::exception const& e)
  {
    l.with("filename", config.database.sqlite3_filename)
        .error("Failed to open database: {}", e.what());
    return exit_status::failure;
  }

  try
  {
    m->migrate_to(target_db_version);
  }
  catch (std::exception const& e)
  {
    l.error("Failed to migrate database: {}", e.what());
    return exit_status::failure;
  }

  return exit_status::success;
}

// Arguments not including own name (so argv[1..]).
auto real_main(std::span<char const*> args) -> exit_status
{
  auto const sink = routemon::log::make_sink(routemon::log::level::info);
  auto l = routemon::log::logger{sink};

  auto load_config = [&](char const* config_filename)
      -> std::expected<routemon::config::app, exit_status>
  {
    try
    {
      auto const config = routemon::config::load_file(config_filename);
      sink->set_level(config.logger.level);
      return config;
    }
    catch (std::exception const& e)
    {
      l.with("filename", std::string_view{config_filename})
          .error("Failed to load configuration: {}", e.what());
      return std::unexpected{exit_status::failure};
    }
  };

  if (args.size() <= 0)
  {
    l.error(
        "Fatal: expected at least a subcommand argument (∈ {{migrate, "
        "server}}), got {} arguments",
        args.size());
    return exit_status::bad_usage;
  }

  if (args[0] == "server"sv)
  {
    args = args.subspan<1>();
    if (args.size() != 1)
    {
      l.error(
          "Fatal: expected exactly one argument (the configuration file "
          "location), got {}",
          args.size());
      return exit_status::bad_usage;
    }
    auto mconfig = load_config(args[0]);
    if (!mconfig)
      return mconfig.error();
    return server_main(l, std::move(*mconfig));
  }
  else if (args[0] == "migrate"sv)
  {
    args = args.subspan<1>();
    if (args.size() != 2)
    {
      l.error(
          "Fatal: expected exactly two arguments (the configuration file "
          "location and database version to migrate to), got {}",
          args.size());
      return exit_status::bad_usage;
    }
    auto mconfig = load_config(args[0]);
    if (!mconfig)
      return mconfig.error();
    auto mtarget_db_version = routemon::util::parse_int<std::int64_t>(args[1]);
    if (!mtarget_db_version || *mtarget_db_version < 0)
    {
      l.error(
          "Fatal: could not parse target database version ({}) as a "
          "non-negative integer",
          args[1]);
      return exit_status::bad_usage;
    }
    return migrate_main(l, std::move(*mconfig), *mtarget_db_version);
  }
  else
  {
    l.error("Fatal: unrecognized subcommand {}", args[0]);
    return exit_status::bad_usage;
  }
}

auto main(int argc, char* argv[]) -> int
{
  if (argc < 1)
  {
    std::cout << "Fatal: argument count below one" << std::endl;
    return EXIT_FAILURE;
  }
  auto res = real_main(
      std::span{
        const_cast<char const**>(argv + 1), static_cast<std::size_t>(argc - 1)
      });
  switch (res)
  {
  case exit_status::success:
    return EXIT_SUCCESS;
  case exit_status::failure:
    return EXIT_FAILURE;
  case exit_status::bad_usage:
    return 2;
  }
}