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