]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/timesync/timesyncd.c
Merge pull request #31000 from flatcar-hub/krnowak/mutable-overlays
[thirdparty/systemd.git] / src / timesync / timesyncd.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
bcdbbd7e 2
ca78ad1d
ZJS
3#include <sys/stat.h>
4#include <sys/types.h>
5
687ed123 6#include "sd-daemon.h"
3ffd4af2 7#include "sd-event.h"
29920c5b 8#include "sd-messages.h"
3ffd4af2 9
430f0182 10#include "capability-util.h"
84e51726 11#include "clock-util.h"
82310c79 12#include "daemon-util.h"
3ffd4af2 13#include "fd-util.h"
f4f15635 14#include "fs-util.h"
82310c79 15#include "main-func.h"
35cd0ba5 16#include "mkdir-label.h"
84e51726 17#include "network-util.h"
df0ff127 18#include "process-util.h"
24882e06 19#include "signal-util.h"
e7dd3947 20#include "timesyncd-bus.h"
84e51726 21#include "timesyncd-conf.h"
3ffd4af2 22#include "timesyncd-manager.h"
b1d4f8e1 23#include "user-util.h"
d636d376 24
1acb4f61
LP
25static 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
e503019b
LP
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,
1acb4f61
LP
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
e503019b 43 for (usec_t a = 1; a <= 10 * USEC_PER_SEC; a *= 10) { /* 1μs, 10μs, 100μs, 1ms, … 10s */
1acb4f61
LP
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
d636d376 74static int load_clock_timestamp(uid_t uid, gid_t gid) {
5ba674cc 75 usec_t min = TIME_EPOCH * USEC_PER_SEC, ct;
254d1313 76 _cleanup_close_ int fd = -EBADF;
d636d376 77 int r;
ece6e766 78
84447fe7
LP
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. */
ece6e766 83
86aaccb0 84 fd = open(CLOCK_FILE, O_RDWR|O_CLOEXEC, 0644);
84447fe7
LP
85 if (fd < 0) {
86 if (errno != ENOENT)
87 log_debug_errno(errno, "Unable to open timestamp file '" CLOCK_FILE "', ignoring: %m");
ece6e766 88
86aaccb0 89 r = mkdir_safe_label(STATE_DIR, 0755, uid, gid,
37c1d5e9 90 MKDIR_FOLLOW_SYMLINK | MKDIR_WARN_MODE);
84447fe7 91 if (r < 0)
86aaccb0 92 log_debug_errno(r, "Failed to create state directory, ignoring: %m");
d636d376 93
d636d376 94 /* create stamp file with the compiled-in date */
0fd08026 95 r = touch_file(CLOCK_FILE, /* parents= */ false, min, uid, gid, 0644);
86aaccb0
YW
96 if (r < 0)
97 log_debug_errno(r, "Failed to create %s, ignoring: %m", CLOCK_FILE);
84447fe7
LP
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);
1acb4f61
LP
116
117 (void) advance_tstamp(fd, &st);
53d133ea 118 }
ece6e766
LP
119
120 ct = now(CLOCK_REALTIME);
29920c5b
LP
121 if (ct > min)
122 return 0;
ece6e766 123
29920c5b
LP
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;
ece6e766
LP
130 }
131
29920c5b
LP
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)));
ece6e766
LP
137 return 0;
138}
139
82310c79 140static int run(int argc, char *argv[]) {
84e51726 141 _cleanup_(manager_freep) Manager *m = NULL;
d7ac0952 142 _unused_ _cleanup_(notify_on_cleanup) const char *notify_message = NULL;
cedc8c44 143 const char *user = "systemd-timesync";
444c1915 144 uid_t uid, uid_current;
ece6e766 145 gid_t gid;
687ed123
KS
146 int r;
147
e8af6973 148 log_set_facility(LOG_CRON);
d2acb93d 149 log_setup();
687ed123 150
e8af6973
LP
151 umask(0022);
152
82310c79
YW
153 if (argc != 1)
154 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments.");
84e51726 155
444c1915
YW
156 uid = uid_current = geteuid();
157 gid = getegid();
158
159 if (uid_current == 0) {
fafff8f1 160 r = get_user_creds(&user, &uid, &gid, NULL, NULL, 0);
82310c79
YW
161 if (r < 0)
162 return log_error_errno(r, "Cannot resolve user name %s: %m", user);
ece6e766
LP
163 }
164
d636d376 165 r = load_clock_timestamp(uid, gid);
ece6e766 166 if (r < 0)
82310c79 167 return r;
ece6e766 168
87a85e25
YW
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. */
444c1915 171 if (uid_current == 0) {
87a85e25
YW
172 r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
173 if (r < 0)
82310c79 174 return log_error_errno(r, "Failed to drop privileges: %m");
87a85e25 175 }
a349eb10 176
db7136ec 177 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGRTMIN+18) >= 0);
856a5a7d 178
687ed123 179 r = manager_new(&m);
82310c79
YW
180 if (r < 0)
181 return log_error_errno(r, "Failed to allocate manager: %m");
687ed123 182
e7dd3947 183 r = manager_connect_bus(m);
82310c79
YW
184 if (r < 0)
185 return log_error_errno(r, "Could not connect to bus: %m");
e7dd3947 186
6369641d 187 if (clock_is_localtime(NULL) > 0) {
c264aeab 188 log_info("The system is configured to read the RTC time in the local time zone. "
87ac8d99 189 "This mode cannot be fully supported. All system time to RTC updates are disabled.");
c264aeab
KS
190 m->rtc_local_time = true;
191 }
192
84e51726
LP
193 r = manager_parse_config_file(m);
194 if (r < 0)
da927ba9 195 log_warning_errno(r, "Failed to parse configuration file: %m");
e0e5ce23 196
c4c06912 197 r = manager_parse_fallback_string(m, NTP_SERVERS);
82310c79
YW
198 if (r < 0)
199 return log_error_errno(r, "Failed to parse fallback server strings: %m");
3745770a 200
df0ff127 201 log_debug("systemd-timesyncd running as pid " PID_FMT, getpid_cached());
82310c79
YW
202
203 notify_message = notify_start("READY=1\n"
204 "STATUS=Daemon is running",
205 NOTIFY_STOPPING);
39594d49 206
33e82f3e
DI
207 r = manager_setup_save_time_event(m);
208 if (r < 0)
209 return r;
210
e0e5ce23
TG
211 if (network_is_online()) {
212 r = manager_connect(m);
213 if (r < 0)
82310c79 214 return r;
e0e5ce23 215 }
678522cf 216
687ed123 217 r = sd_event_loop(m->event);
82310c79
YW
218 if (r < 0)
219 return log_error_errno(r, "Failed to run event loop: %m");
856a5a7d 220
d636d376 221 /* if we got an authoritative time, store it in the file system */
33e82f3e 222 if (m->save_on_exit) {
86aaccb0
YW
223 r = touch(CLOCK_FILE);
224 if (r < 0)
33e82f3e 225 log_debug_errno(r, "Failed to touch " CLOCK_FILE ", ignoring: %m");
86aaccb0 226 }
687ed123 227
690f02f4 228 return 0;
bcdbbd7e 229}
82310c79
YW
230
231DEFINE_MAIN_FUNCTION(run);