Debian Codegraph @

src/timesync/timesyncd.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4 #include <unistd.h>
5
6 #include "sd-event.h"
7 #include "sd-messages.h"
8
9 #include "bus-log-control-api.h"
10 #include "bus-object.h"
11 #include "clock-util.h"
12 #include "daemon-util.h"
13 #include "errno-util.h"
14 #include "fd-util.h"
15 #include "format-util.h"
16 #include "fs-util.h"
17 #include "log.h"
18 #include "main-func.h"
19 #include "network-util.h"
20 #include "process-util.h"
21 #include "service-util.h"
22 #include "timesyncd-bus.h"
23 #include "timesyncd-conf.h"
24 #include "timesyncd-manager.h"
25
26 static int advance_tstamp(int fd, usec_t epoch) {
27 assert(fd >= 0);
28
29 /* So here's the problem: whenever we read the timestamp we'd like to ensure the next time we won't
30 * restore the exact same time again, but one at least one step further (so that comparing mtimes of
31 * the timestamp file is a reliable check that timesync did its thing). But file systems have
32 * different timestamp accuracy: traditional fat has 2s granularity, and even ext2 and friends expose
33 * different granularity depending on selected inode size during formatting! Hence, to ensure the
34 * timestamp definitely is increased, here's what we'll do: we'll first try to increase the timestamp
35 * by 1μs, write that and read it back. If it was updated, great. But if it was not, we'll instead
36 * increase the timestamp by 10μs, and do the same, then 100μs, then 1ms, and so on, until it works,
37 * or we reach 10s. If it still didn't work then, the fs is just broken and we give up. */
38
39 usec_t target = MAX(epoch, now(CLOCK_REALTIME));
40
41 for (usec_t a = 1; a <= 10 * USEC_PER_SEC; a *= 10) { /* 1μs, 10μs, 100μs, 1ms, … 10s */
42 struct timespec ts[2];
43 struct stat new_st;
44
45 /* Bump to the maximum of the old timestamp advanced by the specified unit. */
46 usec_t c = usec_add(target, a);
47
48 timespec_store(&ts[0], c);
49 ts[1] = ts[0];
50
51 if (futimens(fd, ts) < 0) {
52 /* If this doesn't work at all, log and don't fail, but give up. */
53 log_warning_errno(errno, "Unable to update mtime of timestamp file, ignoring: %m");
54 return 0;
55 }
56
57 if (fstat(fd, &new_st) < 0)
58 return log_error_errno(errno, "Failed to stat timestamp file: %m");
59
60 if (timespec_load(&new_st.st_mtim) > target) {
61 log_debug("Successfully touched timestamp file.");
62 return 1;
63 }
64
65 log_debug("Tried to advance timestamp mtime by "USEC_FMT", but this didn't work, file system timestamp granularity too coarse?", a);
66 }
67
68 log_debug("Gave up trying to advance timestamp file.");
69 return 0;
70 }
71
72 static int load_clock_timestamp(void) {
73 usec_t epoch = TIME_EPOCH * USEC_PER_SEC, ct;
74 _cleanup_close_ int fd = -EBADF;
75 int r;
76
77 /* Let's try to make sure that the clock is always monotonically increasing, by saving the clock
78 * whenever we have a new NTP time, or when we shut down, and restoring it when we start again. This
79 * is particularly helpful on systems lacking a battery backed RTC. We also will adjust the time to
80 * at least the build time of systemd. */
81
82 fd = RET_NERRNO(open(TIMESYNCD_CLOCK_FILE, O_RDWR|O_CLOEXEC, 0644));
83 if (fd < 0) {
84 if (fd != -ENOENT)
85 log_warning_errno(fd, "Unable to open timestamp file "TIMESYNCD_CLOCK_FILE", ignoring: %m");
86
87 /* Create stamp file with the compiled-in date */
88 r = touch_file(TIMESYNCD_CLOCK_FILE, /* parents= */ false, epoch, UID_INVALID, GID_INVALID, MODE_INVALID);
89 if (r < 0)
90 log_debug_errno(r, "Failed to create %s, ignoring: %m", TIMESYNCD_CLOCK_FILE);
91 } else {
92 struct stat st;
93
94 /* Check if the recorded time is later than the compiled-in one */
95 if (fstat(fd, &st) < 0)
96 return log_error_errno(errno, "Unable to stat timestamp file "TIMESYNCD_CLOCK_FILE": %m");
97
98 epoch = MAX(epoch, timespec_load(&st.st_mtim));
99
100 (void) advance_tstamp(fd, epoch);
101 }
102
103 ct = now(CLOCK_REALTIME);
104 if (ct > epoch)
105 return 0;
106
107 /* Not that it matters much, but we actually restore the clock to n+1 here rather than n, simply
108 * because we read n as time previously already and we want to progress here, i.e. not report the
109 * same time again. */
110 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(epoch + 1)) < 0) {
111 log_warning_errno(errno, "Failed to advance system clock, ignoring: %m");
112 return 0;
113 }
114
115 log_struct(LOG_INFO,
116 LOG_MESSAGE_ID(SD_MESSAGE_TIME_BUMP_STR),
117 LOG_ITEM("REALTIME_USEC=" USEC_FMT, epoch + 1),
118 LOG_ITEM("DIRECTION=forwards"),
119 LOG_MESSAGE("System clock time advanced to %s: %s",
120 epoch > TIME_EPOCH * USEC_PER_SEC ? "recorded timestamp" : "built-in epoch",
121 FORMAT_TIMESTAMP(epoch + 1)));
122 return 0;
123 }
124
125 static int run(int argc, char *argv[]) {
126 _cleanup_(manager_freep) Manager *m = NULL;
127 _unused_ _cleanup_(notify_on_cleanup) const char *notify_message = NULL;
128 int r;
129
130 log_set_facility(LOG_CRON);
131 log_setup();
132
133 r = service_parse_argv("systemd-timesyncd.service",
134 "Network time synchronization",
135 BUS_IMPLEMENTATIONS(&manager_object, &log_control_object),
136 /* runtime_scope= */ NULL,
137 argc, argv);
138 if (r <= 0)
139 return r;
140
141 umask(0022);
142
143 if (argc != 1)
144 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments.");
145
146 r = load_clock_timestamp();
147 if (r < 0)
148 return r;
149
150 r = manager_new(&m);
151 if (r < 0)
152 return log_error_errno(r, "Failed to allocate manager: %m");
153
154 r = manager_connect_bus(m);
155 if (r < 0)
156 return log_error_errno(r, "Could not connect to bus: %m");
157
158 if (clock_is_localtime(NULL) > 0) {
159 log_info("The system is configured to read the RTC time in the local time zone. "
160 "This mode cannot be fully supported. All system time to RTC updates are disabled.");
161 m->rtc_local_time = true;
162 }
163
164 r = manager_parse_config_file(m);
165 if (r < 0)
166 log_warning_errno(r, "Failed to parse configuration file: %m");
167
168 r = manager_parse_fallback_string(m, NTP_SERVERS);
169 if (r < 0)
170 return log_error_errno(r, "Failed to parse fallback server strings: %m");
171
172 log_debug("systemd-timesyncd running as pid " PID_FMT, getpid_cached());
173
174 notify_message = notify_start("READY=1\n"
175 "STATUS=Daemon is running",
176 NOTIFY_STOPPING_MESSAGE);
177
178 r = manager_setup_save_time_event(m);
179 if (r < 0)
180 return r;
181
182 if (network_is_online()) {
183 r = manager_connect(m);
184 if (r < 0)
185 return r;
186 }
187
188 r = sd_event_loop(m->event);
189 if (r < 0)
190 return log_error_errno(r, "Failed to run event loop: %m");
191
192 /* Save the current time in the file system on exit. */
193 r = touch(TIMESYNCD_CLOCK_FILE);
194 if (r < 0)
195 log_debug_errno(r, "Failed to touch "TIMESYNCD_CLOCK_FILE", ignoring: %m");
196
197 return 0;
198 }
199
200 DEFINE_MAIN_FUNCTION(run);