This source file includes following definitions.
- load_clock_timestamp
- main
#include "sd-event.h"
#include "sd-daemon.h"
#include "mkdir.h"
#include "capability.h"
#include "clock-util.h"
#include "network-util.h"
#include "timesyncd-manager.h"
#include "timesyncd-conf.h"
static int load_clock_timestamp(uid_t uid, gid_t gid) {
_cleanup_close_ int fd = -1;
usec_t min = TIME_EPOCH * USEC_PER_SEC;
usec_t ct;
int r;
fd = open("/var/lib/systemd/clock", O_RDWR|O_CLOEXEC, 0644);
if (fd >= 0) {
struct stat st;
usec_t stamp;
r = fstat(fd, &st);
if (r >= 0) {
stamp = timespec_load(&st.st_mtim);
if (stamp > min)
min = stamp;
}
fchmod(fd, 0644);
fchown(fd, uid, gid);
} else
touch_file("/var/lib/systemd/clock", true, min, uid, gid, 0644);
ct = now(CLOCK_REALTIME);
if (ct < min) {
struct timespec ts;
char date[FORMAT_TIMESTAMP_MAX];
log_info("System clock time unset or jumped backwards, restoring from recorded timestamp: %s",
format_timestamp(date, sizeof(date), min));
if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, min)) < 0)
log_error("Failed to restore system clock: %m");
}
return 0;
}
int main(int argc, char *argv[]) {
_cleanup_(manager_freep) Manager *m = NULL;
const char *user = "systemd-timesync";
uid_t uid;
gid_t gid;
int r;
log_set_target(LOG_TARGET_AUTO);
log_set_facility(LOG_CRON);
log_parse_environment();
log_open();
umask(0022);
if (argc != 1) {
log_error("This program does not take arguments.");
r = -EINVAL;
goto finish;
}
r = get_user_creds(&user, &uid, &gid, NULL, NULL);
if (r < 0) {
log_error("Cannot resolve user name %s: %s", user, strerror(-r));
goto finish;
}
r = load_clock_timestamp(uid, gid);
if (r < 0)
goto finish;
r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
if (r < 0)
goto finish;
assert_se(sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1) == 0);
r = manager_new(&m);
if (r < 0) {
log_error("Failed to allocate manager: %s", strerror(-r));
goto finish;
}
if (clock_is_localtime() > 0) {
log_info("The system is configured to read the RTC time in the local time zone. "
"This mode can not be fully supported. All system time to RTC updates are disabled.");
m->rtc_local_time = true;
}
r = manager_parse_config_file(m);
if (r < 0)
log_warning("Failed to parse configuration file: %s", strerror(-r));
log_debug("systemd-timesyncd running as pid %lu", (unsigned long) getpid());
sd_notify(false,
"READY=1\n"
"STATUS=Daemon is running");
if (network_is_online()) {
r = manager_connect(m);
if (r < 0)
goto finish;
}
r = sd_event_loop(m->event);
if (r < 0) {
log_error("Failed to run event loop: %s", strerror(-r));
goto finish;
}
if (m->sync)
touch("/var/lib/systemd/clock");
sd_event_get_exit_code(m->event, &r);
finish:
sd_notify(false,
"STOPPING=1\n"
"STATUS=Shutting down...");
return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}