84 lines
2.4 KiB
C++
84 lines
2.4 KiB
C++
/*
|
|
* main.cpp
|
|
* MontaukOS Network Time Protocol service
|
|
* Copyright (c) 2026 Daniel Hammer
|
|
*/
|
|
|
|
#include <montauk/config.h>
|
|
#include <montauk/ntp.h>
|
|
#include <montauk/service_log.h>
|
|
#include <montauk/string.h>
|
|
#include <montauk/syscall.h>
|
|
#include <libc/stdio.h>
|
|
|
|
static constexpr uint64_t RETRY_INTERVAL_MS =
|
|
montauk::ntp::MIN_QUERY_INTERVAL_MS;
|
|
static constexpr uint64_t SYNC_INTERVAL_MS = 60ULL * 60ULL * 1000ULL;
|
|
static constexpr uint64_t CONFIG_POLL_MS = 5000;
|
|
|
|
static void log(const char* message) {
|
|
char line[256];
|
|
snprintf(line, sizeof(line), "ntp: %s", message);
|
|
montauk::service_log(line);
|
|
}
|
|
|
|
static bool load_settings(char* server, int server_cap) {
|
|
auto cfg = montauk::config::load("ntp");
|
|
bool enabled = cfg.get_bool("ntp.enabled", true);
|
|
montauk::strncpy(server, cfg.get_string("ntp.server", "pool.ntp.org"),
|
|
server_cap);
|
|
cfg.destroy();
|
|
if (!server[0])
|
|
montauk::strncpy(server, "pool.ntp.org", server_cap);
|
|
return enabled;
|
|
}
|
|
|
|
extern "C" void _start() {
|
|
log("service started");
|
|
|
|
char active_server[128] = {};
|
|
bool was_enabled = false;
|
|
uint64_t next_attempt = 0;
|
|
|
|
for (;;) {
|
|
char server[128];
|
|
bool enabled = load_settings(server, sizeof(server));
|
|
bool server_changed = !montauk::streq(server, active_server);
|
|
if (server_changed) {
|
|
montauk::strncpy(active_server, server, sizeof(active_server));
|
|
next_attempt = 0;
|
|
}
|
|
|
|
if (!enabled) {
|
|
was_enabled = false;
|
|
next_attempt = 0;
|
|
montauk::sleep_ms(CONFIG_POLL_MS);
|
|
continue;
|
|
}
|
|
if (!was_enabled) {
|
|
was_enabled = true;
|
|
next_attempt = 0;
|
|
}
|
|
|
|
uint64_t now = montauk::get_milliseconds();
|
|
if (next_attempt != 0 && now < next_attempt) {
|
|
montauk::sleep_ms(CONFIG_POLL_MS);
|
|
continue;
|
|
}
|
|
|
|
montauk::abi::NetCfg net = {};
|
|
montauk::get_netcfg(&net);
|
|
if (net.ipAddress == 0 || net.dnsServer == 0) {
|
|
next_attempt = now + RETRY_INTERVAL_MS;
|
|
montauk::sleep_ms(CONFIG_POLL_MS);
|
|
continue;
|
|
}
|
|
|
|
int result = montauk::ntp::synchronize(server);
|
|
log(montauk::ntp::result_string(result));
|
|
next_attempt = montauk::get_milliseconds() +
|
|
(result == montauk::ntp::OK ? SYNC_INTERVAL_MS : RETRY_INTERVAL_MS);
|
|
montauk::sleep_ms(CONFIG_POLL_MS);
|
|
}
|
|
}
|