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/>.
29 #include <arpa/inet.h>
30 #include <netinet/in.h>
31 #include <netinet/ip.h>
32 #include <sys/timerfd.h>
33 #include <sys/timex.h>
34 #include <sys/socket.h>
36 #include <sys/prctl.h>
37 #include <sys/types.h>
42 #include "sparse-endian.h"
44 #include "socket-util.h"
46 #include "ratelimit.h"
48 #include "conf-parser.h"
49 #include "sd-daemon.h"
50 #include "event-util.h"
51 #include "network-util.h"
52 #include "clock-util.h"
53 #include "capability.h"
55 #include "timesyncd-conf.h"
56 #include "timesyncd-manager.h"
58 #define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
61 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
64 /* expected accuracy of time synchronization; used to adjust the poll interval */
65 #define NTP_ACCURACY_SEC 0.2
68 * "A client MUST NOT under any conditions use a poll interval less
71 #define NTP_POLL_INTERVAL_MIN_SEC 32
72 #define NTP_POLL_INTERVAL_MAX_SEC 2048
75 * Maximum delta in seconds which the system clock is gradually adjusted
76 * (slew) to approach the network time. Deltas larger that this are set by
77 * letting the system time jump. The kernel's limit for adjtime is 0.5s.
79 #define NTP_MAX_ADJUST 0.4
81 /* NTP protocol, packet header */
82 #define NTP_LEAP_PLUSSEC 1
83 #define NTP_LEAP_MINUSSEC 2
84 #define NTP_LEAP_NOTINSYNC 3
85 #define NTP_MODE_CLIENT 3
86 #define NTP_MODE_SERVER 4
87 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
88 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
89 #define NTP_FIELD_MODE(f) ((f) & 7)
90 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
93 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
94 * in seconds relative to 0h on 1 January 1900."
96 #define OFFSET_1900_1970 2208988800UL
98 #define RETRY_USEC (30*USEC_PER_SEC)
99 #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
100 #define RATELIMIT_BURST 10
102 #define TIMEOUT_USEC (10*USEC_PER_SEC)
109 struct ntp_ts_short {
119 struct ntp_ts_short root_delay;
120 struct ntp_ts_short root_dispersion;
122 struct ntp_ts reference_time;
123 struct ntp_ts origin_time;
124 struct ntp_ts recv_time;
125 struct ntp_ts trans_time;
128 static int manager_arm_timer(Manager *m, usec_t next);
129 static int manager_clock_watch_setup(Manager *m);
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 double tv_to_d(const struct timeval *tv) {
140 return tv->tv_sec + (1.0e-6 * tv->tv_usec);
143 static double square(double d) {
147 static int manager_timeout(sd_event_source *source, usec_t usec, void *userdata) {
148 _cleanup_free_ char *pretty = NULL;
149 Manager *m = userdata;
152 assert(m->current_server_name);
153 assert(m->current_server_address);
155 server_address_pretty(m->current_server_address, &pretty);
156 log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
158 return manager_connect(m);
161 static int manager_send_request(Manager *m) {
162 _cleanup_free_ char *pretty = NULL;
163 struct ntp_msg ntpmsg = {
165 * "The client initializes the NTP message header, sends the request
166 * to the server, and strips the time of day from the Transmit
167 * Timestamp field of the reply. For this purpose, all the NTP
168 * header fields are set to 0, except the Mode, VN, and optional
169 * Transmit Timestamp fields."
171 .field = NTP_FIELD(0, 4, NTP_MODE_CLIENT),
177 assert(m->current_server_name);
178 assert(m->current_server_address);
180 m->event_timeout = sd_event_source_unref(m->event_timeout);
183 * Set transmit timestamp, remember it; the server will send that back
184 * as the origin timestamp and we have an indication that this is the
185 * matching answer to our request.
187 * The actual value does not matter, We do not care about the correct
188 * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
190 assert_se(clock_gettime(clock_boottime_or_monotonic(), &m->trans_time_mon) >= 0);
191 assert_se(clock_gettime(CLOCK_REALTIME, &m->trans_time) >= 0);
192 ntpmsg.trans_time.sec = htobe32(m->trans_time.tv_sec + OFFSET_1900_1970);
193 ntpmsg.trans_time.frac = htobe32(m->trans_time.tv_nsec);
195 server_address_pretty(m->current_server_address, &pretty);
197 len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
198 if (len == sizeof(ntpmsg)) {
200 log_debug("Sent NTP request to %s (%s).", strna(pretty), m->current_server_name->string);
202 log_debug("Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
203 return manager_connect(m);
206 /* re-arm timer with increasing timeout, in case the packets never arrive back */
207 if (m->retry_interval > 0) {
208 if (m->retry_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
209 m->retry_interval *= 2;
211 m->retry_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
213 r = manager_arm_timer(m, m->retry_interval);
215 log_error("Failed to rearm timer: %s", strerror(-r));
219 r = sd_event_add_time(
222 clock_boottime_or_monotonic(),
223 now(clock_boottime_or_monotonic()) + TIMEOUT_USEC, 0,
226 log_error("Failed to arm timeout timer: %s", strerror(-r));
233 static int manager_timer(sd_event_source *source, usec_t usec, void *userdata) {
234 Manager *m = userdata;
238 return manager_send_request(m);
241 static int manager_arm_timer(Manager *m, usec_t next) {
245 assert(m->event_receive);
248 m->event_timer = sd_event_source_unref(m->event_timer);
252 if (m->event_timer) {
253 r = sd_event_source_set_time(m->event_timer, now(clock_boottime_or_monotonic()) + next);
257 return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
260 return sd_event_add_time(
263 clock_boottime_or_monotonic(),
264 now(clock_boottime_or_monotonic()) + next, 0,
268 static int manager_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
269 Manager *m = userdata;
274 manager_clock_watch_setup(m);
276 /* skip our own jumps */
283 log_info("System time changed. Resyncing.");
284 m->poll_resync = true;
286 return manager_send_request(m);
289 /* wake up when the system time changes underneath us */
290 static int manager_clock_watch_setup(Manager *m) {
292 struct itimerspec its = {
293 .it_value.tv_sec = TIME_T_MAX
300 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
301 safe_close(m->clock_watch_fd);
303 m->clock_watch_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
304 if (m->clock_watch_fd < 0) {
305 log_error("Failed to create timerfd: %m");
309 if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
310 log_error("Failed to set up timerfd: %m");
314 r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
316 log_error("Failed to create clock watch event source: %s", strerror(-r));
323 static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
324 struct timex tmx = {};
330 * For small deltas, tell the kernel to gradually adjust the system
331 * clock to the NTP time, larger deltas are just directly set.
333 if (fabs(offset) < NTP_MAX_ADJUST) {
334 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
335 tmx.status = STA_PLL;
336 tmx.offset = offset * NSEC_PER_SEC;
337 tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
340 log_debug(" adjust (slew): %+.3f sec\n", offset);
342 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_SETOFFSET;
344 /* ADJ_NANO uses nanoseconds in the microseconds field */
345 tmx.time.tv_sec = (long)offset;
346 tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
348 /* the kernel expects -0.3s as {-1, 7000.000.000} */
349 if (tmx.time.tv_usec < 0) {
350 tmx.time.tv_sec -= 1;
351 tmx.time.tv_usec += NSEC_PER_SEC;
355 log_debug(" adjust (jump): %+.3f sec\n", offset);
359 * An unset STA_UNSYNC will enable the kernel's 11-minute mode,
360 * which syncs the system time periodically to the RTC.
362 * In case the RTC runs in local time, never touch the RTC,
363 * we have no way to properly handle daylight saving changes and
364 * mobile devices moving between time zones.
366 if (m->rtc_local_time)
367 tmx.status |= STA_UNSYNC;
371 tmx.status |= STA_INS;
374 tmx.status |= STA_DEL;
378 r = clock_adjtime(CLOCK_REALTIME, &tmx);
382 touch("/var/lib/systemd/clock");
384 m->drift_ppm = tmx.freq / 65536;
386 log_debug(" status : %04i %s\n"
387 " time now : %li.%03llu\n"
389 " offset : %+.3f sec\n"
390 " freq offset : %+li (%i ppm)\n",
391 tmx.status, tmx.status & STA_UNSYNC ? "unsync" : "sync",
392 tmx.time.tv_sec, (unsigned long long) (tmx.time.tv_usec / NSEC_PER_MSEC),
394 (double)tmx.offset / NSEC_PER_SEC,
395 tmx.freq, m->drift_ppm);
400 static bool manager_sample_spike_detection(Manager *m, double offset, double delay) {
401 unsigned int i, idx_cur, idx_new, idx_min;
409 /* ignore initial sample */
410 if (m->packet_count == 1)
413 /* store the current data in our samples array */
414 idx_cur = m->samples_idx;
415 idx_new = (idx_cur + 1) % ELEMENTSOF(m->samples);
416 m->samples_idx = idx_new;
417 m->samples[idx_new].offset = offset;
418 m->samples[idx_new].delay = delay;
420 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
421 jitter = m->samples_jitter;
422 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(m->samples); i++)
423 if (m->samples[i].delay > 0 && m->samples[i].delay < m->samples[idx_min].delay)
427 for (i = 0; i < ELEMENTSOF(m->samples); i++)
428 j += square(m->samples[i].offset - m->samples[idx_min].offset);
429 m->samples_jitter = sqrt(j / (ELEMENTSOF(m->samples) - 1));
431 /* ignore samples when resyncing */
435 /* always accept offset if we are farther off than the round-trip delay */
436 if (fabs(offset) > delay)
439 /* we need a few samples before looking at them */
440 if (m->packet_count < 4)
443 /* do not accept anything worse than the maximum possible error of the best sample */
444 if (fabs(offset) > m->samples[idx_min].delay)
447 /* compare the difference between the current offset to the previous offset and jitter */
448 return fabs(offset - m->samples[idx_cur].offset) > 3 * jitter;
451 static void manager_adjust_poll(Manager *m, double offset, bool spike) {
454 if (m->poll_resync) {
455 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
456 m->poll_resync = false;
460 /* set to minimal poll interval */
461 if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
462 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
466 /* increase polling interval */
467 if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
468 if (m->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
469 m->poll_interval_usec *= 2;
473 /* decrease polling interval */
474 if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
475 if (m->poll_interval_usec > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
476 m->poll_interval_usec /= 2;
481 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
482 Manager *m = userdata;
483 struct ntp_msg ntpmsg;
487 .iov_len = sizeof(ntpmsg),
490 struct cmsghdr cmsghdr;
491 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
493 union sockaddr_union server_addr;
494 struct msghdr msghdr = {
497 .msg_control = &control,
498 .msg_controllen = sizeof(control),
499 .msg_name = &server_addr,
500 .msg_namelen = sizeof(server_addr),
502 struct cmsghdr *cmsg;
503 struct timespec now_ts;
504 struct timeval *recv_time;
506 double origin, receive, trans, dest;
507 double delay, offset;
515 if (revents & (EPOLLHUP|EPOLLERR)) {
516 log_warning("Server connection returned error.");
517 return manager_connect(m);
520 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
525 log_warning("Error receiving message. Disconnecting.");
526 return manager_connect(m);
529 if (iov.iov_len < sizeof(struct ntp_msg)) {
530 log_warning("Invalid response from server. Disconnecting.");
531 return manager_connect(m);
534 if (!m->current_server_name ||
535 !m->current_server_address ||
536 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
537 log_debug("Response from unknown server.");
542 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
543 if (cmsg->cmsg_level != SOL_SOCKET)
546 switch (cmsg->cmsg_type) {
548 recv_time = (struct timeval *) CMSG_DATA(cmsg);
553 log_error("Invalid packet timestamp.");
558 log_debug("Unexpected reply. Ignoring.");
562 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
563 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
564 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
565 log_debug("Invalid reply; not our transmit time. Ignoring.");
569 m->event_timeout = sd_event_source_unref(m->event_timeout);
571 if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
572 be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
573 log_debug("Invalid reply, returned times before epoch. Ignoring.");
574 return manager_connect(m);
577 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC) {
578 log_debug("Server is not synchronized. Disconnecting.");
579 return manager_connect(m);
582 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
583 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
584 return manager_connect(m);
587 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
588 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
589 return manager_connect(m);
594 m->retry_interval = 0;
596 /* announce leap seconds */
597 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
599 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
605 * "Timestamp Name ID When Generated
606 * ------------------------------------------------------------
607 * Originate Timestamp T1 time request sent by client
608 * Receive Timestamp T2 time request received by server
609 * Transmit Timestamp T3 time reply sent by server
610 * Destination Timestamp T4 time reply received by client
612 * The round-trip delay, d, and system clock offset, t, are defined as:
613 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
615 assert_se(clock_gettime(clock_boottime_or_monotonic(), &now_ts) >= 0);
616 origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&m->trans_time_mon)) + OFFSET_1900_1970;
617 receive = ntp_ts_to_d(&ntpmsg.recv_time);
618 trans = ntp_ts_to_d(&ntpmsg.trans_time);
619 dest = tv_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 " reference : %.4s\n"
639 " offset : %+.3f sec\n"
640 " delay : %+.3f sec\n"
641 " packet count : %"PRIu64"\n"
643 " poll interval: " USEC_FMT "\n",
644 NTP_FIELD_LEAP(ntpmsg.field),
645 NTP_FIELD_VERSION(ntpmsg.field),
646 NTP_FIELD_MODE(ntpmsg.field),
648 exp2(ntpmsg.precision), ntpmsg.precision,
649 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
650 origin - OFFSET_1900_1970,
651 receive - OFFSET_1900_1970,
652 trans - OFFSET_1900_1970,
653 dest - OFFSET_1900_1970,
656 m->samples_jitter, spike ? " spike" : "",
657 m->poll_interval_usec / USEC_PER_SEC);
661 r = manager_adjust_clock(m, offset, leap_sec);
663 log_error("Failed to call clock_adjtime(): %m");
666 log_info("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
667 m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
668 spike ? " (ignored)" : "");
670 r = manager_arm_timer(m, m->poll_interval_usec);
672 log_error("Failed to rearm timer: %s", strerror(-r));
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 assert(m->server_socket < 0);
688 assert(!m->event_receive);
689 assert(m->current_server_address);
691 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
693 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
694 if (m->server_socket < 0)
697 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
701 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
705 setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
707 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
710 static int manager_begin(Manager *m) {
711 _cleanup_free_ char *pretty = NULL;
715 assert_return(m->current_server_name, -EHOSTUNREACH);
716 assert_return(m->current_server_address, -EHOSTUNREACH);
718 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
720 server_address_pretty(m->current_server_address, &pretty);
721 log_info("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
722 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
724 r = manager_listen_setup(m);
726 log_warning("Failed to setup connection socket: %s", strerror(-r));
730 r = manager_clock_watch_setup(m);
734 return manager_send_request(m);
737 void manager_set_server_name(Manager *m, ServerName *n) {
740 if (m->current_server_name == n)
743 m->current_server_name = n;
744 m->current_server_address = NULL;
746 manager_disconnect(m);
749 log_debug("Selected server %s.", n->string);
752 void manager_set_server_address(Manager *m, ServerAddress *a) {
755 if (m->current_server_address == a)
758 m->current_server_name = a ? a->name : NULL;
759 m->current_server_address = a;
761 manager_disconnect(m);
764 _cleanup_free_ char *pretty = NULL;
765 server_address_pretty(a, &pretty);
766 log_debug("Selected address %s of server %s.", strna(pretty), a->name->string);
770 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
771 Manager *m = userdata;
776 assert(m->current_server_name);
778 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
781 log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
784 return manager_connect(m);
787 for (; ai; ai = ai->ai_next) {
788 _cleanup_free_ char *pretty = NULL;
792 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
794 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
795 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
799 r = server_address_new(m->current_server_name, &a, (const union sockaddr_union*) ai->ai_addr, ai->ai_addrlen);
801 log_error("Failed to add server address: %s", strerror(-r));
805 server_address_pretty(a, &pretty);
806 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
809 if (!m->current_server_name->addresses) {
810 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
813 return manager_connect(m);
816 manager_set_server_address(m, m->current_server_name->addresses);
818 return manager_begin(m);
821 static int manager_retry_connect(sd_event_source *source, usec_t usec, void *userdata) {
822 Manager *m = userdata;
826 return manager_connect(m);
829 int manager_connect(Manager *m) {
834 manager_disconnect(m);
836 m->event_retry = sd_event_source_unref(m->event_retry);
837 if (!ratelimit_test(&m->ratelimit)) {
838 log_debug("Slowing down attempts to contact servers.");
840 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);
842 log_error("Failed to create retry timer: %s", strerror(-r));
849 /* If we already are operating on some address, switch to the
851 if (m->current_server_address && m->current_server_address->addresses_next)
852 manager_set_server_address(m, m->current_server_address->addresses_next);
854 struct addrinfo hints = {
855 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
856 .ai_socktype = SOCK_DGRAM,
859 /* Hmm, we are through all addresses, let's look for the next host instead */
860 if (m->current_server_name && m->current_server_name->names_next)
861 manager_set_server_name(m, m->current_server_name->names_next);
865 /* Our current server name list is exhausted,
866 * let's find the next one to iterate. First
867 * we try the system list, then the link list.
868 * After having processed the link list we
869 * jump back to the system list. However, if
870 * both lists are empty, we change to the
872 if (!m->current_server_name || m->current_server_name->type == SERVER_LINK) {
873 f = m->system_servers;
879 f = m->system_servers;
883 f = m->fallback_servers;
886 manager_set_server_name(m, NULL);
887 log_debug("No server found.");
891 manager_set_server_name(m, f);
894 /* Tell the resolver to reread /etc/resolv.conf, in
895 * case it changed. */
898 /* Flush out any previously resolved addresses */
899 server_name_flush_addresses(m->current_server_name);
901 log_debug("Resolving %s...", m->current_server_name->string);
903 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
905 log_error("Failed to create resolver: %s", strerror(-r));
912 r = manager_begin(m);
919 void manager_disconnect(Manager *m) {
922 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
924 m->event_timer = sd_event_source_unref(m->event_timer);
926 m->event_receive = sd_event_source_unref(m->event_receive);
927 m->server_socket = safe_close(m->server_socket);
929 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
930 m->clock_watch_fd = safe_close(m->clock_watch_fd);
932 m->event_timeout = sd_event_source_unref(m->event_timeout);
934 sd_notifyf(false, "STATUS=Idle.");
937 void manager_flush_server_names(Manager *m, ServerType t) {
940 if (t == SERVER_SYSTEM)
941 while (m->system_servers)
942 server_name_free(m->system_servers);
944 if (t == SERVER_LINK)
945 while (m->link_servers)
946 server_name_free(m->link_servers);
948 if (t == SERVER_FALLBACK)
949 while (m->fallback_servers)
950 server_name_free(m->fallback_servers);
953 void manager_free(Manager *m) {
957 manager_disconnect(m);
958 manager_flush_server_names(m, SERVER_SYSTEM);
959 manager_flush_server_names(m, SERVER_LINK);
960 manager_flush_server_names(m, SERVER_FALLBACK);
962 sd_event_source_unref(m->event_retry);
964 sd_event_source_unref(m->network_event_source);
965 sd_network_monitor_unref(m->network_monitor);
967 sd_resolve_unref(m->resolve);
968 sd_event_unref(m->event);
973 static int manager_network_read_link_servers(Manager *m) {
974 _cleanup_strv_free_ char **ntp = NULL;
981 r = sd_network_get_ntp(&ntp);
985 LIST_FOREACH(names, n, m->link_servers)
988 STRV_FOREACH(i, ntp) {
991 LIST_FOREACH(names, n, m->link_servers)
992 if (streq(n->string, *i)) {
999 r = server_name_new(m, NULL, SERVER_LINK, *i);
1005 LIST_FOREACH_SAFE(names, n, nx, m->link_servers)
1007 server_name_free(n);
1012 manager_flush_server_names(m, SERVER_LINK);
1016 static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1017 Manager *m = userdata;
1018 bool connected, online;
1023 sd_network_monitor_flush(m->network_monitor);
1025 manager_network_read_link_servers(m);
1027 /* check if the machine is online */
1028 online = network_is_online();
1030 /* check if the client is currently connected */
1031 connected = m->server_socket >= 0 || m->resolve_query;
1033 if (connected && !online) {
1034 log_info("No network connectivity, watching for changes.");
1035 manager_disconnect(m);
1037 } else if (!connected && online) {
1038 log_info("Network configuration changed, trying to establish connection.");
1040 if (m->current_server_address)
1041 r = manager_begin(m);
1043 r = manager_connect(m);
1051 static int manager_network_monitor_listen(Manager *m) {
1056 r = sd_network_monitor_new(&m->network_monitor, NULL);
1060 fd = sd_network_monitor_get_fd(m->network_monitor);
1064 events = sd_network_monitor_get_events(m->network_monitor);
1068 r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
1075 int manager_new(Manager **ret) {
1076 _cleanup_(manager_freep) Manager *m = NULL;
1081 m = new0(Manager, 1);
1085 m->server_socket = m->clock_watch_fd = -1;
1087 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1089 r = manager_parse_server_string(m, SERVER_FALLBACK, NTP_SERVERS);
1093 r = sd_event_default(&m->event);
1097 sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1098 sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1100 sd_event_set_watchdog(m->event, true);
1102 r = sd_resolve_default(&m->resolve);
1106 r = sd_resolve_attach_event(m->resolve, m->event, 0);
1110 r = manager_network_monitor_listen(m);
1114 manager_network_read_link_servers(m);