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