1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Kay Sievers, Lennart Poettering
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.
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.
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/>.
26 #include <netinet/in.h>
27 #include <netinet/ip.h>
28 #include <sys/timerfd.h>
29 #include <sys/timex.h>
30 #include <sys/socket.h>
32 #include <sys/types.h>
36 #include "sparse-endian.h"
38 #include "socket-util.h"
40 #include "ratelimit.h"
42 #include "sd-daemon.h"
43 #include "network-util.h"
44 #include "timesyncd-conf.h"
45 #include "timesyncd-manager.h"
46 #include "time-util.h"
49 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
52 /* expected accuracy of time synchronization; used to adjust the poll interval */
53 #define NTP_ACCURACY_SEC 0.2
56 * "A client MUST NOT under any conditions use a poll interval less
59 #define NTP_POLL_INTERVAL_MIN_SEC 32
60 #define NTP_POLL_INTERVAL_MAX_SEC 2048
63 * Maximum delta in seconds which the system clock is gradually adjusted
64 * (slew) to approach the network time. Deltas larger that this are set by
65 * letting the system time jump. The kernel's limit for adjtime is 0.5s.
67 #define NTP_MAX_ADJUST 0.4
69 /* NTP protocol, packet header */
70 #define NTP_LEAP_PLUSSEC 1
71 #define NTP_LEAP_MINUSSEC 2
72 #define NTP_LEAP_NOTINSYNC 3
73 #define NTP_MODE_CLIENT 3
74 #define NTP_MODE_SERVER 4
75 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
76 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
77 #define NTP_FIELD_MODE(f) ((f) & 7)
78 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
80 /* Maximum acceptable root distance in seconds. */
81 #define NTP_MAX_ROOT_DISTANCE 5.0
83 /* Maximum number of missed replies before selecting another source. */
84 #define NTP_MAX_MISSED_REPLIES 2
87 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
88 * in seconds relative to 0h on 1 January 1900."
90 #define OFFSET_1900_1970 UINT64_C(2208988800)
92 #define RETRY_USEC (30*USEC_PER_SEC)
93 #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
94 #define RATELIMIT_BURST 10
96 #define TIMEOUT_USEC (10*USEC_PER_SEC)
103 struct ntp_ts_short {
113 struct ntp_ts_short root_delay;
114 struct ntp_ts_short root_dispersion;
116 struct ntp_ts reference_time;
117 struct ntp_ts origin_time;
118 struct ntp_ts recv_time;
119 struct ntp_ts trans_time;
122 static int manager_arm_timer(Manager *m, usec_t next);
123 static int manager_clock_watch_setup(Manager *m);
124 static int manager_listen_setup(Manager *m);
125 static void manager_listen_stop(Manager *m);
127 static double ntp_ts_short_to_d(const struct ntp_ts_short *ts) {
128 return be16toh(ts->sec) + (be16toh(ts->frac) / 65536.0);
131 static double ntp_ts_to_d(const struct ntp_ts *ts) {
132 return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
135 static double ts_to_d(const struct timespec *ts) {
136 return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
139 static int manager_timeout(sd_event_source *source, usec_t usec, void *userdata) {
140 _cleanup_free_ char *pretty = NULL;
141 Manager *m = userdata;
144 assert(m->current_server_name);
145 assert(m->current_server_address);
147 server_address_pretty(m->current_server_address, &pretty);
148 log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
150 return manager_connect(m);
153 static int manager_send_request(Manager *m) {
154 _cleanup_free_ char *pretty = NULL;
155 struct ntp_msg ntpmsg = {
157 * "The client initializes the NTP message header, sends the request
158 * to the server, and strips the time of day from the Transmit
159 * Timestamp field of the reply. For this purpose, all the NTP
160 * header fields are set to 0, except the Mode, VN, and optional
161 * Transmit Timestamp fields."
163 .field = NTP_FIELD(0, 4, NTP_MODE_CLIENT),
169 assert(m->current_server_name);
170 assert(m->current_server_address);
172 m->event_timeout = sd_event_source_unref(m->event_timeout);
174 r = manager_listen_setup(m);
176 return log_warning_errno(r, "Failed to setup connection socket: %m");
179 * Set transmit timestamp, remember it; the server will send that back
180 * as the origin timestamp and we have an indication that this is the
181 * matching answer to our request.
183 * The actual value does not matter, We do not care about the correct
184 * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
186 assert_se(clock_gettime(clock_boottime_or_monotonic(), &m->trans_time_mon) >= 0);
187 assert_se(clock_gettime(CLOCK_REALTIME, &m->trans_time) >= 0);
188 ntpmsg.trans_time.sec = htobe32(m->trans_time.tv_sec + OFFSET_1900_1970);
189 ntpmsg.trans_time.frac = htobe32(m->trans_time.tv_nsec);
191 server_address_pretty(m->current_server_address, &pretty);
193 len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
194 if (len == sizeof(ntpmsg)) {
196 log_debug("Sent NTP request to %s (%s).", strna(pretty), m->current_server_name->string);
198 log_debug_errno(errno, "Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
199 return manager_connect(m);
202 /* re-arm timer with increasing timeout, in case the packets never arrive back */
203 if (m->retry_interval > 0) {
204 if (m->retry_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
205 m->retry_interval *= 2;
207 m->retry_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
209 r = manager_arm_timer(m, m->retry_interval);
211 return log_error_errno(r, "Failed to rearm timer: %m");
214 if (m->missed_replies > NTP_MAX_MISSED_REPLIES) {
215 r = sd_event_add_time(
218 clock_boottime_or_monotonic(),
219 now(clock_boottime_or_monotonic()) + TIMEOUT_USEC, 0,
222 return log_error_errno(r, "Failed to arm timeout timer: %m");
228 static int manager_timer(sd_event_source *source, usec_t usec, void *userdata) {
229 Manager *m = userdata;
233 return manager_send_request(m);
236 static int manager_arm_timer(Manager *m, usec_t next) {
242 m->event_timer = sd_event_source_unref(m->event_timer);
246 if (m->event_timer) {
247 r = sd_event_source_set_time(m->event_timer, now(clock_boottime_or_monotonic()) + next);
251 return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
254 return sd_event_add_time(
257 clock_boottime_or_monotonic(),
258 now(clock_boottime_or_monotonic()) + next, 0,
262 static int manager_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
263 Manager *m = userdata;
268 manager_clock_watch_setup(m);
270 /* skip our own jumps */
277 log_debug("System time changed. Resyncing.");
278 m->poll_resync = true;
280 return manager_send_request(m);
283 /* wake up when the system time changes underneath us */
284 static int manager_clock_watch_setup(Manager *m) {
286 struct itimerspec its = {
287 .it_value.tv_sec = TIME_T_MAX
294 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
295 safe_close(m->clock_watch_fd);
297 m->clock_watch_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
298 if (m->clock_watch_fd < 0)
299 return log_error_errno(errno, "Failed to create timerfd: %m");
301 if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0)
302 return log_error_errno(errno, "Failed to set up timerfd: %m");
304 r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
306 return log_error_errno(r, "Failed to create clock watch event source: %m");
311 static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
312 struct timex tmx = {};
318 * For small deltas, tell the kernel to gradually adjust the system
319 * clock to the NTP time, larger deltas are just directly set.
321 if (fabs(offset) < NTP_MAX_ADJUST) {
322 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
323 tmx.status = STA_PLL;
324 tmx.offset = offset * NSEC_PER_SEC;
325 tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
328 log_debug(" adjust (slew): %+.3f sec", offset);
330 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_SETOFFSET;
332 /* ADJ_NANO uses nanoseconds in the microseconds field */
333 tmx.time.tv_sec = (long)offset;
334 tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
336 /* the kernel expects -0.3s as {-1, 7000.000.000} */
337 if (tmx.time.tv_usec < 0) {
338 tmx.time.tv_sec -= 1;
339 tmx.time.tv_usec += NSEC_PER_SEC;
343 log_debug(" adjust (jump): %+.3f sec", offset);
347 * An unset STA_UNSYNC will enable the kernel's 11-minute mode,
348 * which syncs the system time periodically to the RTC.
350 * In case the RTC runs in local time, never touch the RTC,
351 * we have no way to properly handle daylight saving changes and
352 * mobile devices moving between time zones.
354 if (m->rtc_local_time)
355 tmx.status |= STA_UNSYNC;
359 tmx.status |= STA_INS;
362 tmx.status |= STA_DEL;
366 r = clock_adjtime(CLOCK_REALTIME, &tmx);
370 touch("/var/lib/systemd/clock");
372 m->drift_ppm = tmx.freq / 65536;
374 log_debug(" status : %04i %s\n"
375 " time now : %li.%03llu\n"
377 " offset : %+.3f sec\n"
378 " freq offset : %+li (%i ppm)\n",
379 tmx.status, tmx.status & STA_UNSYNC ? "unsync" : "sync",
380 tmx.time.tv_sec, (unsigned long long) (tmx.time.tv_usec / NSEC_PER_MSEC),
382 (double)tmx.offset / NSEC_PER_SEC,
383 tmx.freq, m->drift_ppm);
388 static bool manager_sample_spike_detection(Manager *m, double offset, double delay) {
389 unsigned int i, idx_cur, idx_new, idx_min;
397 /* ignore initial sample */
398 if (m->packet_count == 1)
401 /* store the current data in our samples array */
402 idx_cur = m->samples_idx;
403 idx_new = (idx_cur + 1) % ELEMENTSOF(m->samples);
404 m->samples_idx = idx_new;
405 m->samples[idx_new].offset = offset;
406 m->samples[idx_new].delay = delay;
408 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
409 jitter = m->samples_jitter;
410 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(m->samples); i++)
411 if (m->samples[i].delay > 0 && m->samples[i].delay < m->samples[idx_min].delay)
415 for (i = 0; i < ELEMENTSOF(m->samples); i++)
416 j += pow(m->samples[i].offset - m->samples[idx_min].offset, 2);
417 m->samples_jitter = sqrt(j / (ELEMENTSOF(m->samples) - 1));
419 /* ignore samples when resyncing */
423 /* always accept offset if we are farther off than the round-trip delay */
424 if (fabs(offset) > delay)
427 /* we need a few samples before looking at them */
428 if (m->packet_count < 4)
431 /* do not accept anything worse than the maximum possible error of the best sample */
432 if (fabs(offset) > m->samples[idx_min].delay)
435 /* compare the difference between the current offset to the previous offset and jitter */
436 return fabs(offset - m->samples[idx_cur].offset) > 3 * jitter;
439 static void manager_adjust_poll(Manager *m, double offset, bool spike) {
442 if (m->poll_resync) {
443 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
444 m->poll_resync = false;
448 /* set to minimal poll interval */
449 if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
450 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
454 /* increase polling interval */
455 if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
456 if (m->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
457 m->poll_interval_usec *= 2;
461 /* decrease polling interval */
462 if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
463 if (m->poll_interval_usec > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
464 m->poll_interval_usec /= 2;
469 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
470 Manager *m = userdata;
471 struct ntp_msg ntpmsg;
475 .iov_len = sizeof(ntpmsg),
478 struct cmsghdr cmsghdr;
479 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
481 union sockaddr_union server_addr;
482 struct msghdr msghdr = {
485 .msg_control = &control,
486 .msg_controllen = sizeof(control),
487 .msg_name = &server_addr,
488 .msg_namelen = sizeof(server_addr),
490 struct cmsghdr *cmsg;
491 struct timespec *recv_time;
493 double origin, receive, trans, dest;
494 double delay, offset;
495 double root_distance;
503 if (revents & (EPOLLHUP|EPOLLERR)) {
504 log_warning("Server connection returned error.");
505 return manager_connect(m);
508 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
513 log_warning("Error receiving message. Disconnecting.");
514 return manager_connect(m);
517 /* Too short or too long packet? */
518 if (iov.iov_len < sizeof(struct ntp_msg) || (msghdr.msg_flags & MSG_TRUNC)) {
519 log_warning("Invalid response from server. Disconnecting.");
520 return manager_connect(m);
523 if (!m->current_server_name ||
524 !m->current_server_address ||
525 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
526 log_debug("Response from unknown server.");
531 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
532 if (cmsg->cmsg_level != SOL_SOCKET)
535 switch (cmsg->cmsg_type) {
536 case SCM_TIMESTAMPNS:
537 recv_time = (struct timespec *) CMSG_DATA(cmsg);
542 log_error("Invalid packet timestamp.");
547 log_debug("Unexpected reply. Ignoring.");
551 m->missed_replies = 0;
553 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
554 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
555 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
556 log_debug("Invalid reply; not our transmit time. Ignoring.");
560 m->event_timeout = sd_event_source_unref(m->event_timeout);
562 if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
563 be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
564 log_debug("Invalid reply, returned times before epoch. Ignoring.");
565 return manager_connect(m);
568 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC ||
569 ntpmsg.stratum == 0 || ntpmsg.stratum >= 16) {
570 log_debug("Server is not synchronized. Disconnecting.");
571 return manager_connect(m);
574 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
575 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
576 return manager_connect(m);
579 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
580 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
581 return manager_connect(m);
584 root_distance = ntp_ts_short_to_d(&ntpmsg.root_delay) / 2 + ntp_ts_short_to_d(&ntpmsg.root_dispersion);
585 if (root_distance > NTP_MAX_ROOT_DISTANCE) {
586 log_debug("Server has too large root distance. Disconnecting.");
587 return manager_connect(m);
592 m->retry_interval = 0;
595 manager_listen_stop(m);
597 /* announce leap seconds */
598 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
600 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
606 * "Timestamp Name ID When Generated
607 * ------------------------------------------------------------
608 * Originate Timestamp T1 time request sent by client
609 * Receive Timestamp T2 time request received by server
610 * Transmit Timestamp T3 time reply sent by server
611 * Destination Timestamp T4 time reply received by client
613 * The round-trip delay, d, and system clock offset, t, are defined as:
614 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
616 origin = ts_to_d(&m->trans_time) + OFFSET_1900_1970;
617 receive = ntp_ts_to_d(&ntpmsg.recv_time);
618 trans = ntp_ts_to_d(&ntpmsg.trans_time);
619 dest = ts_to_d(recv_time) + OFFSET_1900_1970;
621 offset = ((receive - origin) + (trans - dest)) / 2;
622 delay = (dest - origin) - (trans - receive);
624 spike = manager_sample_spike_detection(m, offset, delay);
626 manager_adjust_poll(m, offset, spike);
628 log_debug("NTP response:\n"
633 " precision : %.6f sec (%d)\n"
634 " root distance: %.6f sec\n"
635 " reference : %.4s\n"
640 " offset : %+.3f sec\n"
641 " delay : %+.3f sec\n"
642 " packet count : %"PRIu64"\n"
644 " poll interval: " USEC_FMT "\n",
645 NTP_FIELD_LEAP(ntpmsg.field),
646 NTP_FIELD_VERSION(ntpmsg.field),
647 NTP_FIELD_MODE(ntpmsg.field),
649 exp2(ntpmsg.precision), ntpmsg.precision,
651 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
652 origin - OFFSET_1900_1970,
653 receive - OFFSET_1900_1970,
654 trans - OFFSET_1900_1970,
655 dest - OFFSET_1900_1970,
658 m->samples_jitter, spike ? " spike" : "",
659 m->poll_interval_usec / USEC_PER_SEC);
663 r = manager_adjust_clock(m, offset, leap_sec);
665 log_error_errno(errno, "Failed to call clock_adjtime(): %m");
668 log_debug("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
669 m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
670 spike ? " (ignored)" : "");
672 r = manager_arm_timer(m, m->poll_interval_usec);
674 return log_error_errno(r, "Failed to rearm timer: %m");
679 static int manager_listen_setup(Manager *m) {
680 union sockaddr_union addr = {};
681 static const int tos = IPTOS_LOWDELAY;
682 static const int on = 1;
687 if (m->server_socket >= 0)
690 assert(!m->event_receive);
691 assert(m->current_server_address);
693 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
695 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
696 if (m->server_socket < 0)
699 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
703 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMPNS, &on, sizeof(on));
707 (void) setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
709 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
712 static void manager_listen_stop(Manager *m) {
715 m->event_receive = sd_event_source_unref(m->event_receive);
716 m->server_socket = safe_close(m->server_socket);
719 static int manager_begin(Manager *m) {
720 _cleanup_free_ char *pretty = NULL;
724 assert_return(m->current_server_name, -EHOSTUNREACH);
725 assert_return(m->current_server_address, -EHOSTUNREACH);
727 m->missed_replies = NTP_MAX_MISSED_REPLIES;
728 if (m->poll_interval_usec == 0)
729 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
731 server_address_pretty(m->current_server_address, &pretty);
732 log_debug("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
733 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
735 r = manager_clock_watch_setup(m);
739 return manager_send_request(m);
742 void manager_set_server_name(Manager *m, ServerName *n) {
745 if (m->current_server_name == n)
748 m->current_server_name = n;
749 m->current_server_address = NULL;
751 manager_disconnect(m);
754 log_debug("Selected server %s.", n->string);
757 void manager_set_server_address(Manager *m, ServerAddress *a) {
760 if (m->current_server_address == a)
763 m->current_server_address = a;
764 /* If a is NULL, we are just clearing the address, without
765 * changing the name. Keep the existing name in that case. */
767 m->current_server_name = a->name;
769 manager_disconnect(m);
772 _cleanup_free_ char *pretty = NULL;
773 server_address_pretty(a, &pretty);
774 log_debug("Selected address %s of server %s.", strna(pretty), a->name->string);
778 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
779 Manager *m = userdata;
784 assert(m->current_server_name);
786 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
789 log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
792 return manager_connect(m);
795 for (; ai; ai = ai->ai_next) {
796 _cleanup_free_ char *pretty = NULL;
800 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
802 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
803 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
807 r = server_address_new(m->current_server_name, &a, (const union sockaddr_union*) ai->ai_addr, ai->ai_addrlen);
809 return log_error_errno(r, "Failed to add server address: %m");
811 server_address_pretty(a, &pretty);
812 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
815 if (!m->current_server_name->addresses) {
816 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
819 return manager_connect(m);
822 manager_set_server_address(m, m->current_server_name->addresses);
824 return manager_begin(m);
827 static int manager_retry_connect(sd_event_source *source, usec_t usec, void *userdata) {
828 Manager *m = userdata;
832 return manager_connect(m);
835 int manager_connect(Manager *m) {
840 manager_disconnect(m);
842 m->event_retry = sd_event_source_unref(m->event_retry);
843 if (!ratelimit_test(&m->ratelimit)) {
844 log_debug("Slowing down attempts to contact servers.");
846 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);
848 return log_error_errno(r, "Failed to create retry timer: %m");
853 /* If we already are operating on some address, switch to the
855 if (m->current_server_address && m->current_server_address->addresses_next)
856 manager_set_server_address(m, m->current_server_address->addresses_next);
858 struct addrinfo hints = {
859 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
860 .ai_socktype = SOCK_DGRAM,
863 /* Hmm, we are through all addresses, let's look for the next host instead */
864 if (m->current_server_name && m->current_server_name->names_next)
865 manager_set_server_name(m, m->current_server_name->names_next);
870 /* Our current server name list is exhausted,
871 * let's find the next one to iterate. First
872 * we try the system list, then the link list.
873 * After having processed the link list we
874 * jump back to the system list. However, if
875 * both lists are empty, we change to the
877 if (!m->current_server_name || m->current_server_name->type == SERVER_LINK) {
878 f = m->system_servers;
884 f = m->system_servers;
890 f = m->fallback_servers;
893 manager_set_server_name(m, NULL);
894 log_debug("No server found.");
898 if (restart && !m->exhausted_servers && m->poll_interval_usec) {
899 log_debug("Waiting after exhausting servers.");
900 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);
902 return log_error_errno(r, "Failed to create retry timer: %m");
904 m->exhausted_servers = true;
906 /* Increase the polling interval */
907 if (m->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
908 m->poll_interval_usec *= 2;
913 m->exhausted_servers = false;
915 manager_set_server_name(m, f);
918 /* Tell the resolver to reread /etc/resolv.conf, in
919 * case it changed. */
922 /* Flush out any previously resolved addresses */
923 server_name_flush_addresses(m->current_server_name);
925 log_debug("Resolving %s...", m->current_server_name->string);
927 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
929 return log_error_errno(r, "Failed to create resolver: %m");
934 r = manager_begin(m);
941 void manager_disconnect(Manager *m) {
944 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
946 m->event_timer = sd_event_source_unref(m->event_timer);
948 manager_listen_stop(m);
950 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
951 m->clock_watch_fd = safe_close(m->clock_watch_fd);
953 m->event_timeout = sd_event_source_unref(m->event_timeout);
955 sd_notifyf(false, "STATUS=Idle.");
958 void manager_flush_server_names(Manager *m, ServerType t) {
961 if (t == SERVER_SYSTEM)
962 while (m->system_servers)
963 server_name_free(m->system_servers);
965 if (t == SERVER_LINK)
966 while (m->link_servers)
967 server_name_free(m->link_servers);
969 if (t == SERVER_FALLBACK)
970 while (m->fallback_servers)
971 server_name_free(m->fallback_servers);
974 void manager_free(Manager *m) {
978 manager_disconnect(m);
979 manager_flush_server_names(m, SERVER_SYSTEM);
980 manager_flush_server_names(m, SERVER_LINK);
981 manager_flush_server_names(m, SERVER_FALLBACK);
983 sd_event_source_unref(m->event_retry);
985 sd_event_source_unref(m->network_event_source);
986 sd_network_monitor_unref(m->network_monitor);
988 sd_resolve_unref(m->resolve);
989 sd_event_unref(m->event);
994 static int manager_network_read_link_servers(Manager *m) {
995 _cleanup_strv_free_ char **ntp = NULL;
1002 r = sd_network_get_ntp(&ntp);
1006 LIST_FOREACH(names, n, m->link_servers)
1009 STRV_FOREACH(i, ntp) {
1012 LIST_FOREACH(names, n, m->link_servers)
1013 if (streq(n->string, *i)) {
1020 r = server_name_new(m, NULL, SERVER_LINK, *i);
1026 LIST_FOREACH_SAFE(names, n, nx, m->link_servers)
1028 server_name_free(n);
1033 manager_flush_server_names(m, SERVER_LINK);
1037 static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1038 Manager *m = userdata;
1039 bool connected, online;
1044 sd_network_monitor_flush(m->network_monitor);
1046 manager_network_read_link_servers(m);
1048 /* check if the machine is online */
1049 online = network_is_online();
1051 /* check if the client is currently connected */
1052 connected = m->server_socket >= 0 || m->resolve_query || m->exhausted_servers;
1054 if (connected && !online) {
1055 log_info("No network connectivity, watching for changes.");
1056 manager_disconnect(m);
1058 } else if (!connected && online) {
1059 log_info("Network configuration changed, trying to establish connection.");
1061 if (m->current_server_address)
1062 r = manager_begin(m);
1064 r = manager_connect(m);
1072 static int manager_network_monitor_listen(Manager *m) {
1077 r = sd_network_monitor_new(&m->network_monitor, NULL);
1081 fd = sd_network_monitor_get_fd(m->network_monitor);
1085 events = sd_network_monitor_get_events(m->network_monitor);
1089 r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
1096 int manager_new(Manager **ret) {
1097 _cleanup_(manager_freep) Manager *m = NULL;
1102 m = new0(Manager, 1);
1106 m->server_socket = m->clock_watch_fd = -1;
1108 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1110 r = manager_parse_server_string(m, SERVER_FALLBACK, NTP_SERVERS);
1114 r = sd_event_default(&m->event);
1118 sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1119 sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1121 sd_event_set_watchdog(m->event, true);
1123 r = sd_resolve_default(&m->resolve);
1127 r = sd_resolve_attach_event(m->resolve, m->event, 0);
1131 r = manager_network_monitor_listen(m);
1135 manager_network_read_link_servers(m);