Line data Source code
1 : /* SPDX-License-Identifier: LGPL-2.1+ */
2 :
3 : #include <errno.h>
4 : #include <math.h>
5 : #include <netinet/in.h>
6 : #include <netinet/ip.h>
7 : #include <resolv.h>
8 : #include <stdlib.h>
9 : #include <sys/socket.h>
10 : #include <sys/timerfd.h>
11 : #include <sys/timex.h>
12 : #include <sys/types.h>
13 : #include <time.h>
14 :
15 : #include "sd-daemon.h"
16 :
17 : #include "alloc-util.h"
18 : #include "dns-domain.h"
19 : #include "fd-util.h"
20 : #include "format-util.h"
21 : #include "fs-util.h"
22 : #include "list.h"
23 : #include "log.h"
24 : #include "missing.h"
25 : #include "network-util.h"
26 : #include "ratelimit.h"
27 : #include "resolve-private.h"
28 : #include "socket-util.h"
29 : #include "string-util.h"
30 : #include "strv.h"
31 : #include "time-util.h"
32 : #include "timesyncd-conf.h"
33 : #include "timesyncd-manager.h"
34 : #include "util.h"
35 :
36 : #ifndef ADJ_SETOFFSET
37 : #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
38 : #endif
39 :
40 : /* expected accuracy of time synchronization; used to adjust the poll interval */
41 : #define NTP_ACCURACY_SEC 0.2
42 :
43 : /*
44 : * Maximum delta in seconds which the system clock is gradually adjusted
45 : * (slewed) to approach the network time. Deltas larger that this are set by
46 : * letting the system time jump. The kernel's limit for adjtime is 0.5s.
47 : */
48 : #define NTP_MAX_ADJUST 0.4
49 :
50 : /* Default of maximum acceptable root distance in microseconds. */
51 : #define NTP_MAX_ROOT_DISTANCE (5 * USEC_PER_SEC)
52 :
53 : /* Maximum number of missed replies before selecting another source. */
54 : #define NTP_MAX_MISSED_REPLIES 2
55 :
56 : #define RETRY_USEC (30*USEC_PER_SEC)
57 : #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
58 : #define RATELIMIT_BURST 10
59 :
60 : #define TIMEOUT_USEC (10*USEC_PER_SEC)
61 :
62 : static int manager_arm_timer(Manager *m, usec_t next);
63 : static int manager_clock_watch_setup(Manager *m);
64 : static int manager_listen_setup(Manager *m);
65 : static void manager_listen_stop(Manager *m);
66 :
67 0 : static double ntp_ts_short_to_d(const struct ntp_ts_short *ts) {
68 0 : return be16toh(ts->sec) + (be16toh(ts->frac) / 65536.0);
69 : }
70 :
71 0 : static double ntp_ts_to_d(const struct ntp_ts *ts) {
72 0 : return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
73 : }
74 :
75 0 : static double ts_to_d(const struct timespec *ts) {
76 0 : return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
77 : }
78 :
79 0 : static int manager_timeout(sd_event_source *source, usec_t usec, void *userdata) {
80 0 : _cleanup_free_ char *pretty = NULL;
81 0 : Manager *m = userdata;
82 :
83 0 : assert(m);
84 0 : assert(m->current_server_name);
85 0 : assert(m->current_server_address);
86 :
87 0 : server_address_pretty(m->current_server_address, &pretty);
88 0 : log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
89 :
90 0 : return manager_connect(m);
91 : }
92 :
93 0 : static int manager_send_request(Manager *m) {
94 0 : _cleanup_free_ char *pretty = NULL;
95 0 : struct ntp_msg ntpmsg = {
96 : /*
97 : * "The client initializes the NTP message header, sends the request
98 : * to the server, and strips the time of day from the Transmit
99 : * Timestamp field of the reply. For this purpose, all the NTP
100 : * header fields are set to 0, except the Mode, VN, and optional
101 : * Transmit Timestamp fields."
102 : */
103 : .field = NTP_FIELD(0, 4, NTP_MODE_CLIENT),
104 : };
105 : ssize_t len;
106 : int r;
107 :
108 0 : assert(m);
109 0 : assert(m->current_server_name);
110 0 : assert(m->current_server_address);
111 :
112 0 : m->event_timeout = sd_event_source_unref(m->event_timeout);
113 :
114 0 : r = manager_listen_setup(m);
115 0 : if (r < 0)
116 0 : return log_warning_errno(r, "Failed to setup connection socket: %m");
117 :
118 : /*
119 : * Set transmit timestamp, remember it; the server will send that back
120 : * as the origin timestamp and we have an indication that this is the
121 : * matching answer to our request.
122 : *
123 : * The actual value does not matter, We do not care about the correct
124 : * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
125 : */
126 0 : assert_se(clock_gettime(clock_boottime_or_monotonic(), &m->trans_time_mon) >= 0);
127 0 : assert_se(clock_gettime(CLOCK_REALTIME, &m->trans_time) >= 0);
128 0 : ntpmsg.trans_time.sec = htobe32(m->trans_time.tv_sec + OFFSET_1900_1970);
129 0 : ntpmsg.trans_time.frac = htobe32(m->trans_time.tv_nsec);
130 :
131 0 : server_address_pretty(m->current_server_address, &pretty);
132 :
133 0 : len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
134 0 : if (len == sizeof(ntpmsg)) {
135 0 : m->pending = true;
136 0 : log_debug("Sent NTP request to %s (%s).", strna(pretty), m->current_server_name->string);
137 : } else {
138 0 : log_debug_errno(errno, "Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
139 0 : return manager_connect(m);
140 : }
141 :
142 : /* re-arm timer with increasing timeout, in case the packets never arrive back */
143 0 : if (m->retry_interval > 0) {
144 0 : if (m->retry_interval < m->poll_interval_max_usec)
145 0 : m->retry_interval *= 2;
146 : } else
147 0 : m->retry_interval = m->poll_interval_min_usec;
148 :
149 0 : r = manager_arm_timer(m, m->retry_interval);
150 0 : if (r < 0)
151 0 : return log_error_errno(r, "Failed to rearm timer: %m");
152 :
153 0 : m->missed_replies++;
154 0 : if (m->missed_replies > NTP_MAX_MISSED_REPLIES) {
155 0 : r = sd_event_add_time(
156 : m->event,
157 : &m->event_timeout,
158 : clock_boottime_or_monotonic(),
159 0 : now(clock_boottime_or_monotonic()) + TIMEOUT_USEC, 0,
160 : manager_timeout, m);
161 0 : if (r < 0)
162 0 : return log_error_errno(r, "Failed to arm timeout timer: %m");
163 : }
164 :
165 0 : return 0;
166 : }
167 :
168 0 : static int manager_timer(sd_event_source *source, usec_t usec, void *userdata) {
169 0 : Manager *m = userdata;
170 :
171 0 : assert(m);
172 :
173 0 : return manager_send_request(m);
174 : }
175 :
176 0 : static int manager_arm_timer(Manager *m, usec_t next) {
177 : int r;
178 :
179 0 : assert(m);
180 :
181 0 : if (next == 0) {
182 0 : m->event_timer = sd_event_source_unref(m->event_timer);
183 0 : return 0;
184 : }
185 :
186 0 : if (m->event_timer) {
187 0 : r = sd_event_source_set_time(m->event_timer, now(clock_boottime_or_monotonic()) + next);
188 0 : if (r < 0)
189 0 : return r;
190 :
191 0 : return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
192 : }
193 :
194 0 : return sd_event_add_time(
195 : m->event,
196 : &m->event_timer,
197 : clock_boottime_or_monotonic(),
198 0 : now(clock_boottime_or_monotonic()) + next, 0,
199 : manager_timer, m);
200 : }
201 :
202 0 : static int manager_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
203 0 : Manager *m = userdata;
204 :
205 0 : assert(m);
206 :
207 : /* rearm timer */
208 0 : manager_clock_watch_setup(m);
209 :
210 : /* skip our own jumps */
211 0 : if (m->jumped) {
212 0 : m->jumped = false;
213 0 : return 0;
214 : }
215 :
216 : /* resync */
217 0 : log_debug("System time changed. Resyncing.");
218 0 : m->poll_resync = true;
219 :
220 0 : return manager_send_request(m);
221 : }
222 :
223 : /* wake up when the system time changes underneath us */
224 0 : static int manager_clock_watch_setup(Manager *m) {
225 : int r;
226 :
227 0 : assert(m);
228 :
229 0 : m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
230 0 : safe_close(m->clock_watch_fd);
231 :
232 0 : m->clock_watch_fd = time_change_fd();
233 0 : if (m->clock_watch_fd < 0)
234 0 : return log_error_errno(m->clock_watch_fd, "Failed to create timerfd: %m");
235 :
236 0 : r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
237 0 : if (r < 0)
238 0 : return log_error_errno(r, "Failed to create clock watch event source: %m");
239 :
240 0 : return 0;
241 : }
242 :
243 0 : static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
244 0 : struct timex tmx = {};
245 : int r;
246 :
247 0 : assert(m);
248 :
249 : /*
250 : * For small deltas, tell the kernel to gradually adjust the system
251 : * clock to the NTP time, larger deltas are just directly set.
252 : */
253 0 : if (fabs(offset) < NTP_MAX_ADJUST) {
254 0 : tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
255 0 : tmx.status = STA_PLL;
256 0 : tmx.offset = offset * NSEC_PER_SEC;
257 0 : tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
258 0 : tmx.maxerror = 0;
259 0 : tmx.esterror = 0;
260 0 : log_debug(" adjust (slew): %+.3f sec", offset);
261 : } else {
262 0 : tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_SETOFFSET | ADJ_MAXERROR | ADJ_ESTERROR;
263 :
264 : /* ADJ_NANO uses nanoseconds in the microseconds field */
265 0 : tmx.time.tv_sec = (long)offset;
266 0 : tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
267 0 : tmx.maxerror = 0;
268 0 : tmx.esterror = 0;
269 :
270 : /* the kernel expects -0.3s as {-1, 7000.000.000} */
271 0 : if (tmx.time.tv_usec < 0) {
272 0 : tmx.time.tv_sec -= 1;
273 0 : tmx.time.tv_usec += NSEC_PER_SEC;
274 : }
275 :
276 0 : m->jumped = true;
277 0 : log_debug(" adjust (jump): %+.3f sec", offset);
278 : }
279 :
280 : /*
281 : * An unset STA_UNSYNC will enable the kernel's 11-minute mode,
282 : * which syncs the system time periodically to the RTC.
283 : *
284 : * In case the RTC runs in local time, never touch the RTC,
285 : * we have no way to properly handle daylight saving changes and
286 : * mobile devices moving between time zones.
287 : */
288 0 : if (m->rtc_local_time)
289 0 : tmx.status |= STA_UNSYNC;
290 :
291 0 : switch (leap_sec) {
292 0 : case 1:
293 0 : tmx.status |= STA_INS;
294 0 : break;
295 0 : case -1:
296 0 : tmx.status |= STA_DEL;
297 0 : break;
298 : }
299 :
300 0 : r = clock_adjtime(CLOCK_REALTIME, &tmx);
301 0 : if (r < 0)
302 0 : return -errno;
303 :
304 : /* If touch fails, there isn't much we can do. Maybe it'll work next time. */
305 0 : (void) touch("/var/lib/systemd/timesync/clock");
306 0 : (void) touch("/run/systemd/timesync/synchronized");
307 :
308 0 : m->drift_freq = tmx.freq;
309 :
310 0 : log_debug(" status : %04i %s\n"
311 : " time now : %"PRI_TIME".%03"PRI_USEC"\n"
312 : " constant : %"PRI_TIMEX"\n"
313 : " offset : %+.3f sec\n"
314 : " freq offset : %+"PRI_TIMEX" (%+"PRI_TIMEX" ppm)\n",
315 : tmx.status, tmx.status & STA_UNSYNC ? "unsync" : "sync",
316 : tmx.time.tv_sec, tmx.time.tv_usec / NSEC_PER_MSEC,
317 : tmx.constant,
318 : (double)tmx.offset / NSEC_PER_SEC,
319 : tmx.freq, tmx.freq / 65536);
320 :
321 0 : return 0;
322 : }
323 :
324 0 : static bool manager_sample_spike_detection(Manager *m, double offset, double delay) {
325 : unsigned i, idx_cur, idx_new, idx_min;
326 : double jitter;
327 : double j;
328 :
329 0 : assert(m);
330 :
331 0 : m->packet_count++;
332 :
333 : /* ignore initial sample */
334 0 : if (m->packet_count == 1)
335 0 : return false;
336 :
337 : /* store the current data in our samples array */
338 0 : idx_cur = m->samples_idx;
339 0 : idx_new = (idx_cur + 1) % ELEMENTSOF(m->samples);
340 0 : m->samples_idx = idx_new;
341 0 : m->samples[idx_new].offset = offset;
342 0 : m->samples[idx_new].delay = delay;
343 :
344 : /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
345 0 : jitter = m->samples_jitter;
346 0 : for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(m->samples); i++)
347 0 : if (m->samples[i].delay > 0 && m->samples[i].delay < m->samples[idx_min].delay)
348 0 : idx_min = i;
349 :
350 0 : j = 0;
351 0 : for (i = 0; i < ELEMENTSOF(m->samples); i++)
352 0 : j += pow(m->samples[i].offset - m->samples[idx_min].offset, 2);
353 0 : m->samples_jitter = sqrt(j / (ELEMENTSOF(m->samples) - 1));
354 :
355 : /* ignore samples when resyncing */
356 0 : if (m->poll_resync)
357 0 : return false;
358 :
359 : /* always accept offset if we are farther off than the round-trip delay */
360 0 : if (fabs(offset) > delay)
361 0 : return false;
362 :
363 : /* we need a few samples before looking at them */
364 0 : if (m->packet_count < 4)
365 0 : return false;
366 :
367 : /* do not accept anything worse than the maximum possible error of the best sample */
368 0 : if (fabs(offset) > m->samples[idx_min].delay)
369 0 : return true;
370 :
371 : /* compare the difference between the current offset to the previous offset and jitter */
372 0 : return fabs(offset - m->samples[idx_cur].offset) > 3 * jitter;
373 : }
374 :
375 0 : static void manager_adjust_poll(Manager *m, double offset, bool spike) {
376 0 : assert(m);
377 :
378 0 : if (m->poll_resync) {
379 0 : m->poll_interval_usec = m->poll_interval_min_usec;
380 0 : m->poll_resync = false;
381 0 : return;
382 : }
383 :
384 : /* set to minimal poll interval */
385 0 : if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
386 0 : m->poll_interval_usec = m->poll_interval_min_usec;
387 0 : return;
388 : }
389 :
390 : /* increase polling interval */
391 0 : if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
392 0 : if (m->poll_interval_usec < m->poll_interval_max_usec)
393 0 : m->poll_interval_usec *= 2;
394 0 : return;
395 : }
396 :
397 : /* decrease polling interval */
398 0 : if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
399 0 : if (m->poll_interval_usec > m->poll_interval_min_usec)
400 0 : m->poll_interval_usec /= 2;
401 0 : return;
402 : }
403 : }
404 :
405 0 : static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
406 0 : Manager *m = userdata;
407 : struct ntp_msg ntpmsg;
408 :
409 0 : struct iovec iov = {
410 : .iov_base = &ntpmsg,
411 : .iov_len = sizeof(ntpmsg),
412 : };
413 : union {
414 : struct cmsghdr cmsghdr;
415 : uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
416 : } control;
417 : union sockaddr_union server_addr;
418 0 : struct msghdr msghdr = {
419 : .msg_iov = &iov,
420 : .msg_iovlen = 1,
421 : .msg_control = &control,
422 : .msg_controllen = sizeof(control),
423 : .msg_name = &server_addr,
424 : .msg_namelen = sizeof(server_addr),
425 : };
426 : struct cmsghdr *cmsg;
427 0 : struct timespec *recv_time = NULL;
428 : ssize_t len;
429 : double origin, receive, trans, dest;
430 : double delay, offset;
431 : double root_distance;
432 : bool spike;
433 : int leap_sec;
434 : int r;
435 :
436 0 : assert(source);
437 0 : assert(m);
438 :
439 0 : if (revents & (EPOLLHUP|EPOLLERR)) {
440 0 : log_warning("Server connection returned error.");
441 0 : return manager_connect(m);
442 : }
443 :
444 0 : len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
445 0 : if (len < 0) {
446 0 : if (errno == EAGAIN)
447 0 : return 0;
448 :
449 0 : log_warning("Error receiving message. Disconnecting.");
450 0 : return manager_connect(m);
451 : }
452 :
453 : /* Too short or too long packet? */
454 0 : if (iov.iov_len < sizeof(struct ntp_msg) || (msghdr.msg_flags & MSG_TRUNC)) {
455 0 : log_warning("Invalid response from server. Disconnecting.");
456 0 : return manager_connect(m);
457 : }
458 :
459 0 : if (!m->current_server_name ||
460 0 : !m->current_server_address ||
461 0 : !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
462 0 : log_debug("Response from unknown server.");
463 0 : return 0;
464 : }
465 :
466 0 : CMSG_FOREACH(cmsg, &msghdr) {
467 0 : if (cmsg->cmsg_level != SOL_SOCKET)
468 0 : continue;
469 :
470 0 : switch (cmsg->cmsg_type) {
471 0 : case SCM_TIMESTAMPNS:
472 0 : recv_time = (struct timespec *) CMSG_DATA(cmsg);
473 0 : break;
474 : }
475 0 : }
476 0 : if (!recv_time)
477 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
478 : "Invalid packet timestamp.");
479 :
480 0 : if (!m->pending) {
481 0 : log_debug("Unexpected reply. Ignoring.");
482 0 : return 0;
483 : }
484 :
485 0 : m->missed_replies = 0;
486 :
487 : /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
488 0 : if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
489 0 : be32toh(ntpmsg.origin_time.frac) != (unsigned long) m->trans_time.tv_nsec) {
490 0 : log_debug("Invalid reply; not our transmit time. Ignoring.");
491 0 : return 0;
492 : }
493 :
494 0 : m->event_timeout = sd_event_source_unref(m->event_timeout);
495 :
496 0 : if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
497 0 : be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
498 0 : log_debug("Invalid reply, returned times before epoch. Ignoring.");
499 0 : return manager_connect(m);
500 : }
501 :
502 0 : if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC ||
503 0 : ntpmsg.stratum == 0 || ntpmsg.stratum >= 16) {
504 0 : log_debug("Server is not synchronized. Disconnecting.");
505 0 : return manager_connect(m);
506 : }
507 :
508 0 : if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
509 0 : log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
510 0 : return manager_connect(m);
511 : }
512 :
513 0 : if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
514 0 : log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
515 0 : return manager_connect(m);
516 : }
517 :
518 0 : root_distance = ntp_ts_short_to_d(&ntpmsg.root_delay) / 2 + ntp_ts_short_to_d(&ntpmsg.root_dispersion);
519 0 : if (root_distance > (double) m->max_root_distance_usec / (double) USEC_PER_SEC) {
520 0 : log_debug("Server has too large root distance. Disconnecting.");
521 0 : return manager_connect(m);
522 : }
523 :
524 : /* valid packet */
525 0 : m->pending = false;
526 0 : m->retry_interval = 0;
527 :
528 : /* Stop listening */
529 0 : manager_listen_stop(m);
530 :
531 : /* announce leap seconds */
532 0 : if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
533 0 : leap_sec = 1;
534 0 : else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
535 0 : leap_sec = -1;
536 : else
537 0 : leap_sec = 0;
538 :
539 : /*
540 : * "Timestamp Name ID When Generated
541 : * ------------------------------------------------------------
542 : * Originate Timestamp T1 time request sent by client
543 : * Receive Timestamp T2 time request received by server
544 : * Transmit Timestamp T3 time reply sent by server
545 : * Destination Timestamp T4 time reply received by client
546 : *
547 : * The round-trip delay, d, and system clock offset, t, are defined as:
548 : * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
549 : */
550 0 : origin = ts_to_d(&m->trans_time) + OFFSET_1900_1970;
551 0 : receive = ntp_ts_to_d(&ntpmsg.recv_time);
552 0 : trans = ntp_ts_to_d(&ntpmsg.trans_time);
553 0 : dest = ts_to_d(recv_time) + OFFSET_1900_1970;
554 :
555 0 : offset = ((receive - origin) + (trans - dest)) / 2;
556 0 : delay = (dest - origin) - (trans - receive);
557 :
558 0 : spike = manager_sample_spike_detection(m, offset, delay);
559 :
560 0 : manager_adjust_poll(m, offset, spike);
561 :
562 0 : log_debug("NTP response:\n"
563 : " leap : %u\n"
564 : " version : %u\n"
565 : " mode : %u\n"
566 : " stratum : %u\n"
567 : " precision : %.6f sec (%d)\n"
568 : " root distance: %.6f sec\n"
569 : " reference : %.4s\n"
570 : " origin : %.3f\n"
571 : " receive : %.3f\n"
572 : " transmit : %.3f\n"
573 : " dest : %.3f\n"
574 : " offset : %+.3f sec\n"
575 : " delay : %+.3f sec\n"
576 : " packet count : %"PRIu64"\n"
577 : " jitter : %.3f%s\n"
578 : " poll interval: " USEC_FMT "\n",
579 : NTP_FIELD_LEAP(ntpmsg.field),
580 : NTP_FIELD_VERSION(ntpmsg.field),
581 : NTP_FIELD_MODE(ntpmsg.field),
582 : ntpmsg.stratum,
583 : exp2(ntpmsg.precision), ntpmsg.precision,
584 : root_distance,
585 : ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
586 : origin - OFFSET_1900_1970,
587 : receive - OFFSET_1900_1970,
588 : trans - OFFSET_1900_1970,
589 : dest - OFFSET_1900_1970,
590 : offset, delay,
591 : m->packet_count,
592 : m->samples_jitter, spike ? " spike" : "",
593 : m->poll_interval_usec / USEC_PER_SEC);
594 :
595 0 : if (!spike) {
596 0 : m->sync = true;
597 0 : r = manager_adjust_clock(m, offset, leap_sec);
598 0 : if (r < 0)
599 0 : log_error_errno(r, "Failed to call clock_adjtime(): %m");
600 : }
601 :
602 : /* Save NTP response */
603 0 : m->ntpmsg = ntpmsg;
604 0 : m->origin_time = m->trans_time;
605 0 : m->dest_time = *recv_time;
606 0 : m->spike = spike;
607 :
608 0 : log_debug("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+"PRIi64"ppm%s",
609 : m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_freq / 65536,
610 : spike ? " (ignored)" : "");
611 :
612 0 : (void) sd_bus_emit_properties_changed(m->bus, "/org/freedesktop/timesync1", "org.freedesktop.timesync1.Manager", "NTPMessage", NULL);
613 :
614 0 : if (!m->good) {
615 0 : _cleanup_free_ char *pretty = NULL;
616 :
617 0 : m->good = true;
618 :
619 0 : server_address_pretty(m->current_server_address, &pretty);
620 : /* "for the first time", as further successful syncs will not be logged. */
621 0 : log_info("Synchronized to time server for the first time %s (%s).", strna(pretty), m->current_server_name->string);
622 0 : sd_notifyf(false, "STATUS=Synchronized to time server for the first time %s (%s).", strna(pretty), m->current_server_name->string);
623 : }
624 :
625 0 : r = manager_arm_timer(m, m->poll_interval_usec);
626 0 : if (r < 0)
627 0 : return log_error_errno(r, "Failed to rearm timer: %m");
628 :
629 0 : return 0;
630 : }
631 :
632 0 : static int manager_listen_setup(Manager *m) {
633 0 : union sockaddr_union addr = {};
634 : int r;
635 :
636 0 : assert(m);
637 :
638 0 : if (m->server_socket >= 0)
639 0 : return 0;
640 :
641 0 : assert(!m->event_receive);
642 0 : assert(m->current_server_address);
643 :
644 0 : addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
645 :
646 0 : m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
647 0 : if (m->server_socket < 0)
648 0 : return -errno;
649 :
650 0 : r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
651 0 : if (r < 0)
652 0 : return -errno;
653 :
654 0 : r = setsockopt_int(m->server_socket, SOL_SOCKET, SO_TIMESTAMPNS, true);
655 0 : if (r < 0)
656 0 : return r;
657 :
658 0 : (void) setsockopt_int(m->server_socket, IPPROTO_IP, IP_TOS, IPTOS_LOWDELAY);
659 :
660 0 : return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
661 : }
662 :
663 1 : static void manager_listen_stop(Manager *m) {
664 1 : assert(m);
665 :
666 1 : m->event_receive = sd_event_source_unref(m->event_receive);
667 1 : m->server_socket = safe_close(m->server_socket);
668 1 : }
669 :
670 0 : static int manager_begin(Manager *m) {
671 0 : _cleanup_free_ char *pretty = NULL;
672 : int r;
673 :
674 0 : assert(m);
675 0 : assert_return(m->current_server_name, -EHOSTUNREACH);
676 0 : assert_return(m->current_server_address, -EHOSTUNREACH);
677 :
678 0 : m->good = false;
679 0 : m->missed_replies = NTP_MAX_MISSED_REPLIES;
680 0 : if (m->poll_interval_usec == 0)
681 0 : m->poll_interval_usec = m->poll_interval_min_usec;
682 :
683 0 : server_address_pretty(m->current_server_address, &pretty);
684 0 : log_debug("Connecting to time server %s (%s).", strna(pretty), m->current_server_name->string);
685 0 : sd_notifyf(false, "STATUS=Connecting to time server %s (%s).", strna(pretty), m->current_server_name->string);
686 :
687 0 : r = manager_clock_watch_setup(m);
688 0 : if (r < 0)
689 0 : return r;
690 :
691 0 : return manager_send_request(m);
692 : }
693 :
694 0 : void manager_set_server_name(Manager *m, ServerName *n) {
695 0 : assert(m);
696 :
697 0 : if (m->current_server_name == n)
698 0 : return;
699 :
700 0 : m->current_server_name = n;
701 0 : m->current_server_address = NULL;
702 :
703 0 : manager_disconnect(m);
704 :
705 0 : if (n)
706 0 : log_debug("Selected server %s.", n->string);
707 : }
708 :
709 0 : void manager_set_server_address(Manager *m, ServerAddress *a) {
710 0 : assert(m);
711 :
712 0 : if (m->current_server_address == a)
713 0 : return;
714 :
715 0 : m->current_server_address = a;
716 : /* If a is NULL, we are just clearing the address, without
717 : * changing the name. Keep the existing name in that case. */
718 0 : if (a)
719 0 : m->current_server_name = a->name;
720 :
721 0 : manager_disconnect(m);
722 :
723 0 : if (a) {
724 0 : _cleanup_free_ char *pretty = NULL;
725 0 : server_address_pretty(a, &pretty);
726 0 : log_debug("Selected address %s of server %s.", strna(pretty), a->name->string);
727 : }
728 : }
729 :
730 0 : static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, Manager *m) {
731 : int r;
732 :
733 0 : assert(q);
734 0 : assert(m);
735 0 : assert(m->current_server_name);
736 :
737 0 : m->resolve_query = sd_resolve_query_unref(m->resolve_query);
738 :
739 0 : if (ret != 0) {
740 0 : log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
741 :
742 : /* Try next host */
743 0 : return manager_connect(m);
744 : }
745 :
746 0 : for (; ai; ai = ai->ai_next) {
747 0 : _cleanup_free_ char *pretty = NULL;
748 : ServerAddress *a;
749 :
750 0 : assert(ai->ai_addr);
751 0 : assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
752 :
753 0 : if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
754 0 : log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
755 0 : continue;
756 : }
757 :
758 0 : r = server_address_new(m->current_server_name, &a, (const union sockaddr_union*) ai->ai_addr, ai->ai_addrlen);
759 0 : if (r < 0)
760 0 : return log_error_errno(r, "Failed to add server address: %m");
761 :
762 0 : server_address_pretty(a, &pretty);
763 0 : log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
764 : }
765 :
766 0 : if (!m->current_server_name->addresses) {
767 0 : log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
768 :
769 : /* Try next host */
770 0 : return manager_connect(m);
771 : }
772 :
773 0 : manager_set_server_address(m, m->current_server_name->addresses);
774 :
775 0 : return manager_begin(m);
776 : }
777 :
778 0 : static int manager_retry_connect(sd_event_source *source, usec_t usec, void *userdata) {
779 0 : Manager *m = userdata;
780 :
781 0 : assert(m);
782 :
783 0 : return manager_connect(m);
784 : }
785 :
786 0 : int manager_connect(Manager *m) {
787 : int r;
788 :
789 0 : assert(m);
790 :
791 0 : manager_disconnect(m);
792 :
793 0 : m->event_retry = sd_event_source_unref(m->event_retry);
794 0 : if (!ratelimit_below(&m->ratelimit)) {
795 0 : log_debug("Delaying attempts to contact servers.");
796 :
797 0 : r = sd_event_add_time(m->event, &m->event_retry, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + RETRY_USEC, 0, manager_retry_connect, m);
798 0 : if (r < 0)
799 0 : return log_error_errno(r, "Failed to create retry timer: %m");
800 :
801 0 : return 0;
802 : }
803 :
804 : /* If we already are operating on some address, switch to the
805 : * next one. */
806 0 : if (m->current_server_address && m->current_server_address->addresses_next)
807 0 : manager_set_server_address(m, m->current_server_address->addresses_next);
808 : else {
809 0 : struct addrinfo hints = {
810 : .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
811 : .ai_socktype = SOCK_DGRAM,
812 : };
813 :
814 : /* Hmm, we are through all addresses, let's look for the next host instead */
815 0 : if (m->current_server_name && m->current_server_name->names_next)
816 0 : manager_set_server_name(m, m->current_server_name->names_next);
817 : else {
818 : ServerName *f;
819 0 : bool restart = true;
820 :
821 : /* Our current server name list is exhausted,
822 : * let's find the next one to iterate. First
823 : * we try the system list, then the link list.
824 : * After having processed the link list we
825 : * jump back to the system list. However, if
826 : * both lists are empty, we change to the
827 : * fallback list. */
828 0 : if (!m->current_server_name || m->current_server_name->type == SERVER_LINK) {
829 0 : f = m->system_servers;
830 0 : if (!f)
831 0 : f = m->link_servers;
832 : } else {
833 0 : f = m->link_servers;
834 0 : if (!f)
835 0 : f = m->system_servers;
836 : else
837 0 : restart = false;
838 : }
839 :
840 0 : if (!f)
841 0 : f = m->fallback_servers;
842 :
843 0 : if (!f) {
844 0 : manager_set_server_name(m, NULL);
845 0 : log_debug("No server found.");
846 0 : return 0;
847 : }
848 :
849 0 : if (restart && !m->exhausted_servers && m->poll_interval_usec) {
850 0 : log_debug("Waiting after exhausting servers.");
851 0 : r = sd_event_add_time(m->event, &m->event_retry, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + m->poll_interval_usec, 0, manager_retry_connect, m);
852 0 : if (r < 0)
853 0 : return log_error_errno(r, "Failed to create retry timer: %m");
854 :
855 0 : m->exhausted_servers = true;
856 :
857 : /* Increase the polling interval */
858 0 : if (m->poll_interval_usec < m->poll_interval_max_usec)
859 0 : m->poll_interval_usec *= 2;
860 :
861 0 : return 0;
862 : }
863 :
864 0 : m->exhausted_servers = false;
865 :
866 0 : manager_set_server_name(m, f);
867 : }
868 :
869 : /* Tell the resolver to reread /etc/resolv.conf, in
870 : * case it changed. */
871 0 : res_init();
872 :
873 : /* Flush out any previously resolved addresses */
874 0 : server_name_flush_addresses(m->current_server_name);
875 :
876 0 : log_debug("Resolving %s...", m->current_server_name->string);
877 :
878 0 : r = resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, NULL, m);
879 0 : if (r < 0)
880 0 : return log_error_errno(r, "Failed to create resolver: %m");
881 :
882 0 : return 1;
883 : }
884 :
885 0 : r = manager_begin(m);
886 0 : if (r < 0)
887 0 : return r;
888 :
889 0 : return 1;
890 : }
891 :
892 1 : void manager_disconnect(Manager *m) {
893 1 : assert(m);
894 :
895 1 : m->resolve_query = sd_resolve_query_unref(m->resolve_query);
896 :
897 1 : m->event_timer = sd_event_source_unref(m->event_timer);
898 :
899 1 : manager_listen_stop(m);
900 :
901 1 : m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
902 1 : m->clock_watch_fd = safe_close(m->clock_watch_fd);
903 :
904 1 : m->event_timeout = sd_event_source_unref(m->event_timeout);
905 :
906 1 : sd_notifyf(false, "STATUS=Idle.");
907 1 : }
908 :
909 4 : void manager_flush_server_names(Manager *m, ServerType t) {
910 4 : assert(m);
911 :
912 4 : if (t == SERVER_SYSTEM)
913 3 : while (m->system_servers)
914 2 : server_name_free(m->system_servers);
915 :
916 4 : if (t == SERVER_LINK)
917 2 : while (m->link_servers)
918 0 : server_name_free(m->link_servers);
919 :
920 4 : if (t == SERVER_FALLBACK)
921 7 : while (m->fallback_servers)
922 6 : server_name_free(m->fallback_servers);
923 4 : }
924 :
925 1 : void manager_free(Manager *m) {
926 1 : if (!m)
927 0 : return;
928 :
929 1 : manager_disconnect(m);
930 1 : manager_flush_server_names(m, SERVER_SYSTEM);
931 1 : manager_flush_server_names(m, SERVER_LINK);
932 1 : manager_flush_server_names(m, SERVER_FALLBACK);
933 :
934 1 : sd_event_source_unref(m->event_retry);
935 :
936 1 : sd_event_source_unref(m->network_event_source);
937 1 : sd_network_monitor_unref(m->network_monitor);
938 :
939 1 : sd_resolve_unref(m->resolve);
940 1 : sd_event_unref(m->event);
941 :
942 1 : sd_bus_flush_close_unref(m->bus);
943 :
944 1 : free(m);
945 : }
946 :
947 1 : static int manager_network_read_link_servers(Manager *m) {
948 1 : _cleanup_strv_free_ char **ntp = NULL;
949 : ServerName *n, *nx;
950 : char **i;
951 1 : bool changed = false;
952 : int r;
953 :
954 1 : assert(m);
955 :
956 1 : r = sd_network_get_ntp(&ntp);
957 1 : if (r < 0) {
958 1 : if (r == -ENOMEM)
959 0 : log_oom();
960 : else
961 1 : log_debug_errno(r, "Failed to get link NTP servers: %m");
962 1 : goto clear;
963 : }
964 :
965 0 : LIST_FOREACH(names, n, m->link_servers)
966 0 : n->marked = true;
967 :
968 0 : STRV_FOREACH(i, ntp) {
969 0 : bool found = false;
970 :
971 0 : r = dns_name_is_valid_or_address(*i);
972 0 : if (r < 0) {
973 0 : log_error_errno(r, "Failed to check validity of NTP server name or address '%s': %m", *i);
974 0 : goto clear;
975 0 : } else if (r == 0) {
976 0 : log_error("Invalid NTP server name or address, ignoring: %s", *i);
977 0 : continue;
978 : }
979 :
980 0 : LIST_FOREACH(names, n, m->link_servers)
981 0 : if (streq(n->string, *i)) {
982 0 : n->marked = false;
983 0 : found = true;
984 0 : break;
985 : }
986 :
987 0 : if (!found) {
988 0 : r = server_name_new(m, NULL, SERVER_LINK, *i);
989 0 : if (r < 0) {
990 0 : log_oom();
991 0 : goto clear;
992 : }
993 :
994 0 : changed = true;
995 : }
996 : }
997 :
998 0 : LIST_FOREACH_SAFE(names, n, nx, m->link_servers)
999 0 : if (n->marked) {
1000 0 : server_name_free(n);
1001 0 : changed = true;
1002 : }
1003 :
1004 0 : return changed;
1005 :
1006 1 : clear:
1007 1 : manager_flush_server_names(m, SERVER_LINK);
1008 1 : return r;
1009 : }
1010 :
1011 0 : static bool manager_is_connected(Manager *m) {
1012 : /* Return true when the manager is sending a request, resolving a server name, or
1013 : * in a poll interval. */
1014 0 : return m->server_socket >= 0 || m->resolve_query || m->event_timer;
1015 : }
1016 :
1017 0 : static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1018 0 : Manager *m = userdata;
1019 : bool changed, connected, online;
1020 : int r;
1021 :
1022 0 : assert(m);
1023 :
1024 0 : sd_network_monitor_flush(m->network_monitor);
1025 :
1026 : /* When manager_network_read_link_servers() failed, we assume that the servers are changed. */
1027 0 : changed = manager_network_read_link_servers(m);
1028 :
1029 : /* check if the machine is online */
1030 0 : online = network_is_online();
1031 :
1032 : /* check if the client is currently connected */
1033 0 : connected = manager_is_connected(m);
1034 :
1035 0 : if (connected && !online) {
1036 0 : log_info("No network connectivity, watching for changes.");
1037 0 : manager_disconnect(m);
1038 :
1039 0 : } else if ((!connected || changed) && online) {
1040 0 : log_info("Network configuration changed, trying to establish connection.");
1041 :
1042 0 : if (m->current_server_address)
1043 0 : r = manager_begin(m);
1044 : else
1045 0 : r = manager_connect(m);
1046 0 : if (r < 0)
1047 0 : return r;
1048 : }
1049 :
1050 0 : return 0;
1051 : }
1052 :
1053 1 : static int manager_network_monitor_listen(Manager *m) {
1054 : int r, fd, events;
1055 :
1056 1 : assert(m);
1057 :
1058 1 : r = sd_network_monitor_new(&m->network_monitor, NULL);
1059 1 : if (r == -ENOENT) {
1060 0 : log_info("systemd does not appear to be running, not listening for systemd-networkd events.");
1061 0 : return 0;
1062 : }
1063 1 : if (r < 0)
1064 0 : return r;
1065 :
1066 1 : fd = sd_network_monitor_get_fd(m->network_monitor);
1067 1 : if (fd < 0)
1068 0 : return fd;
1069 :
1070 1 : events = sd_network_monitor_get_events(m->network_monitor);
1071 1 : if (events < 0)
1072 0 : return events;
1073 :
1074 1 : r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
1075 1 : if (r < 0)
1076 0 : return r;
1077 :
1078 1 : return 0;
1079 : }
1080 :
1081 1 : int manager_new(Manager **ret) {
1082 1 : _cleanup_(manager_freep) Manager *m = NULL;
1083 : int r;
1084 :
1085 1 : assert(ret);
1086 :
1087 1 : m = new0(Manager, 1);
1088 1 : if (!m)
1089 0 : return -ENOMEM;
1090 :
1091 1 : m->max_root_distance_usec = NTP_MAX_ROOT_DISTANCE;
1092 1 : m->poll_interval_min_usec = NTP_POLL_INTERVAL_MIN_USEC;
1093 1 : m->poll_interval_max_usec = NTP_POLL_INTERVAL_MAX_USEC;
1094 :
1095 1 : m->server_socket = m->clock_watch_fd = -1;
1096 :
1097 1 : RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1098 :
1099 1 : r = sd_event_default(&m->event);
1100 1 : if (r < 0)
1101 0 : return r;
1102 :
1103 1 : (void) sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1104 1 : (void) sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1105 :
1106 1 : (void) sd_event_set_watchdog(m->event, true);
1107 :
1108 1 : r = sd_resolve_default(&m->resolve);
1109 1 : if (r < 0)
1110 0 : return r;
1111 :
1112 1 : r = sd_resolve_attach_event(m->resolve, m->event, 0);
1113 1 : if (r < 0)
1114 0 : return r;
1115 :
1116 1 : r = manager_network_monitor_listen(m);
1117 1 : if (r < 0)
1118 0 : return r;
1119 :
1120 1 : (void) manager_network_read_link_servers(m);
1121 :
1122 1 : *ret = TAKE_PTR(m);
1123 :
1124 1 : return 0;
1125 : }
|