]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/timesync/timesyncd.c
man/soft-reboot: order surviving services before shutdown.target
[thirdparty/systemd.git] / src / timesync / timesyncd.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <sys/stat.h>
4 #include <sys/types.h>
5
6 #include "sd-daemon.h"
7 #include "sd-event.h"
8 #include "sd-messages.h"
9
10 #include "capability-util.h"
11 #include "clock-util.h"
12 #include "daemon-util.h"
13 #include "fd-util.h"
14 #include "fs-util.h"
15 #include "main-func.h"
16 #include "mkdir-label.h"
17 #include "network-util.h"
18 #include "process-util.h"
19 #include "signal-util.h"
20 #include "timesyncd-bus.h"
21 #include "timesyncd-conf.h"
22 #include "timesyncd-manager.h"
23 #include "user-util.h"
24
25 static int advance_tstamp(int fd, const struct stat *st) {
26 assert_se(fd >= 0);
27 assert_se(st);
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 = MAX3(now(CLOCK_REALTIME),
40 TIME_EPOCH * USEC_PER_SEC,
41 timespec_load(&st->st_mtim));
42
43 for (usec_t a = 1; a <= 10 * USEC_PER_SEC; a *= 10) { /* 1μs, 10μs, 100μs, 1ms, … 10s */
44 struct timespec ts[2];
45 struct stat new_st;
46
47 /* Bump to the maximum of the old timestamp advanced by the specified unit, */
48 usec_t c = usec_add(target, a);
49
50 timespec_store(&ts[0], c);
51 ts[1] = ts[0];
52
53 if (futimens(fd, ts) < 0) {
54 /* If this doesn't work at all, log, don't fail but give up */
55 log_warning_errno(errno, "Unable to update mtime of timestamp file, ignoring: %m");
56 return 0;
57 }
58
59 if (fstat(fd, &new_st) < 0)
60 return log_error_errno(errno, "Failed to stat timestamp file: %m");
61
62 if (timespec_load(&new_st.st_mtim) > target) {
63 log_debug("Successfully bumped timestamp file.");
64 return 1;
65 }
66
67 log_debug("Tried to advance timestamp file by " USEC_FMT ", but this didn't work, file system timestamp granularity too coarse?", a);
68 }
69
70 log_debug("Gave up trying to advance timestamp file.");
71 return 0;
72 }
73
74 static int load_clock_timestamp(uid_t uid, gid_t gid) {
75 usec_t min = TIME_EPOCH * USEC_PER_SEC, ct;
76 _cleanup_close_ int fd = -EBADF;
77 int r;
78
79 /* Let's try to make sure that the clock is always monotonically increasing, by saving the clock
80 * whenever we have a new NTP time, or when we shut down, and restoring it when we start again. This
81 * is particularly helpful on systems lacking a battery backed RTC. We also will adjust the time to
82 * at least the build time of systemd. */
83
84 fd = open(CLOCK_FILE, O_RDWR|O_CLOEXEC, 0644);
85 if (fd < 0) {
86 if (errno != ENOENT)
87 log_debug_errno(errno, "Unable to open timestamp file '" CLOCK_FILE "', ignoring: %m");
88
89 r = mkdir_safe_label(STATE_DIR, 0755, uid, gid,
90 MKDIR_FOLLOW_SYMLINK | MKDIR_WARN_MODE);
91 if (r < 0)
92 log_debug_errno(r, "Failed to create state directory, ignoring: %m");
93
94 /* create stamp file with the compiled-in date */
95 r = touch_file(CLOCK_FILE, /* parents= */ false, min, uid, gid, 0644);
96 if (r < 0)
97 log_debug_errno(r, "Failed to create %s, ignoring: %m", CLOCK_FILE);
98 } else {
99 struct stat st;
100 usec_t stamp;
101
102 /* check if the recorded time is later than the compiled-in one */
103 if (fstat(fd, &st) < 0)
104 return log_error_errno(errno, "Unable to stat timestamp file '" CLOCK_FILE "': %m");
105
106 stamp = timespec_load(&st.st_mtim);
107 if (stamp > min)
108 min = stamp;
109
110 /* Try to fix the access mode, so that we can still touch the file after dropping
111 * privileges */
112 r = fchmod_and_chown(fd, 0644, uid, gid);
113 if (r < 0)
114 log_full_errno(ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
115 "Failed to chmod or chown %s, ignoring: %m", CLOCK_FILE);
116
117 (void) advance_tstamp(fd, &st);
118 }
119
120 ct = now(CLOCK_REALTIME);
121 if (ct > min)
122 return 0;
123
124 /* Not that it matters much, but we actually restore the clock to n+1 here rather than n, simply
125 * because we read n as time previously already and we want to progress here, i.e. not report the
126 * same time again. */
127 if (clock_settime(CLOCK_REALTIME, TIMESPEC_STORE(min+1)) < 0) {
128 log_warning_errno(errno, "Failed to restore system clock, ignoring: %m");
129 return 0;
130 }
131
132 log_struct(LOG_INFO,
133 "MESSAGE_ID=" SD_MESSAGE_TIME_BUMP_STR,
134 "REALTIME_USEC=" USEC_FMT, min+1,
135 LOG_MESSAGE("System clock time unset or jumped backwards, restored from recorded timestamp: %s",
136 FORMAT_TIMESTAMP(min+1)));
137 return 0;
138 }
139
140 static int run(int argc, char *argv[]) {
141 _cleanup_(manager_freep) Manager *m = NULL;
142 _unused_ _cleanup_(notify_on_cleanup) const char *notify_message = NULL;
143 const char *user = "systemd-timesync";
144 uid_t uid, uid_current;
145 gid_t gid;
146 int r;
147
148 log_set_facility(LOG_CRON);
149 log_setup();
150
151 umask(0022);
152
153 if (argc != 1)
154 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments.");
155
156 uid = uid_current = geteuid();
157 gid = getegid();
158
159 if (uid_current == 0) {
160 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
161 if (r < 0)
162 return log_error_errno(r, "Cannot resolve user name %s: %m", user);
163 }
164
165 r = load_clock_timestamp(uid, gid);
166 if (r < 0)
167 return r;
168
169 /* Drop privileges, but only if we have been started as root. If we are not running as root we assume all
170 * privileges are already dropped. */
171 if (uid_current == 0) {
172 r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
173 if (r < 0)
174 return log_error_errno(r, "Failed to drop privileges: %m");
175 }
176
177 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGRTMIN+18) >= 0);
178
179 r = manager_new(&m);
180 if (r < 0)
181 return log_error_errno(r, "Failed to allocate manager: %m");
182
183 r = manager_connect_bus(m);
184 if (r < 0)
185 return log_error_errno(r, "Could not connect to bus: %m");
186
187 if (clock_is_localtime(NULL) > 0) {
188 log_info("The system is configured to read the RTC time in the local time zone. "
189 "This mode cannot be fully supported. All system time to RTC updates are disabled.");
190 m->rtc_local_time = true;
191 }
192
193 r = manager_parse_config_file(m);
194 if (r < 0)
195 log_warning_errno(r, "Failed to parse configuration file: %m");
196
197 r = manager_parse_fallback_string(m, NTP_SERVERS);
198 if (r < 0)
199 return log_error_errno(r, "Failed to parse fallback server strings: %m");
200
201 log_debug("systemd-timesyncd running as pid " PID_FMT, getpid_cached());
202
203 notify_message = notify_start("READY=1\n"
204 "STATUS=Daemon is running",
205 NOTIFY_STOPPING);
206
207 r = manager_setup_save_time_event(m);
208 if (r < 0)
209 return r;
210
211 if (network_is_online()) {
212 r = manager_connect(m);
213 if (r < 0)
214 return r;
215 }
216
217 r = sd_event_loop(m->event);
218 if (r < 0)
219 return log_error_errno(r, "Failed to run event loop: %m");
220
221 /* if we got an authoritative time, store it in the file system */
222 if (m->save_on_exit) {
223 r = touch(CLOCK_FILE);
224 if (r < 0)
225 log_debug_errno(r, "Failed to touch " CLOCK_FILE ", ignoring: %m");
226 }
227
228 return 0;
229 }
230
231 DEFINE_MAIN_FUNCTION(run);