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>
39 #include "sparse-endian.h"
41 #include "socket-util.h"
43 #include "ratelimit.h"
45 #include "conf-parser.h"
47 #include "sd-resolve.h"
48 #include "sd-daemon.h"
49 #include "timesyncd.h"
51 #define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
54 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
57 /* expected accuracy of time synchronization; used to adjust the poll interval */
58 #define NTP_ACCURACY_SEC 0.2
61 * "A client MUST NOT under any conditions use a poll interval less
64 #define NTP_POLL_INTERVAL_MIN_SEC 32
65 #define NTP_POLL_INTERVAL_MAX_SEC 2048
68 * Maximum delta in seconds which the system clock is gradually adjusted
69 * (slew) to approach the network time. Deltas larger that this are set by
70 * letting the system time jump. The kernel's limit for adjtime is 0.5s.
72 #define NTP_MAX_ADJUST 0.4
74 /* NTP protocol, packet header */
75 #define NTP_LEAP_PLUSSEC 1
76 #define NTP_LEAP_MINUSSEC 2
77 #define NTP_LEAP_NOTINSYNC 3
78 #define NTP_MODE_CLIENT 3
79 #define NTP_MODE_SERVER 4
80 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
81 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
82 #define NTP_FIELD_MODE(f) ((f) & 7)
83 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
86 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
87 * in seconds relative to 0h on 1 January 1900."
89 #define OFFSET_1900_1970 2208988800UL
91 #define RETRY_USEC (30*USEC_PER_SEC)
92 #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
93 #define RATELIMIT_BURST 10
95 #define TIMEOUT_USEC (10*USEC_PER_SEC)
102 struct ntp_ts_short {
112 struct ntp_ts_short root_delay;
113 struct ntp_ts_short root_dispersion;
115 struct ntp_ts reference_time;
116 struct ntp_ts origin_time;
117 struct ntp_ts recv_time;
118 struct ntp_ts trans_time;
121 static void manager_free(Manager *m);
122 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
123 #define _cleanup_manager_free_ _cleanup_(manager_freep)
125 static int manager_arm_timer(Manager *m, usec_t next);
126 static int manager_clock_watch_setup(Manager *m);
127 static int manager_connect(Manager *m);
128 static void manager_disconnect(Manager *m);
130 static double ntp_ts_to_d(const struct ntp_ts *ts) {
131 return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
134 static double ts_to_d(const struct timespec *ts) {
135 return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
138 static double tv_to_d(const struct timeval *tv) {
139 return tv->tv_sec + (1.0e-6 * tv->tv_usec);
142 static double square(double d) {
146 static int manager_timeout(sd_event_source *source, usec_t usec, void *userdata) {
147 _cleanup_free_ char *pretty = NULL;
148 Manager *m = userdata;
151 assert(m->current_server_name);
152 assert(m->current_server_address);
154 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
155 log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
157 return manager_connect(m);
160 static int manager_send_request(Manager *m) {
161 _cleanup_free_ char *pretty = NULL;
162 struct ntp_msg ntpmsg = {
164 * "The client initializes the NTP message header, sends the request
165 * to the server, and strips the time of day from the Transmit
166 * Timestamp field of the reply. For this purpose, all the NTP
167 * header fields are set to 0, except the Mode, VN, and optional
168 * Transmit Timestamp fields."
170 .field = NTP_FIELD(0, 4, NTP_MODE_CLIENT),
176 assert(m->current_server_name);
177 assert(m->current_server_address);
179 m->event_timeout = sd_event_source_unref(m->event_timeout);
182 * Set transmit timestamp, remember it; the server will send that back
183 * as the origin timestamp and we have an indication that this is the
184 * matching answer to our request.
186 * The actual value does not matter, We do not care about the correct
187 * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
189 assert_se(clock_gettime(CLOCK_MONOTONIC, &m->trans_time_mon) >= 0);
190 assert_se(clock_gettime(CLOCK_REALTIME, &m->trans_time) >= 0);
191 ntpmsg.trans_time.sec = htobe32(m->trans_time.tv_sec + OFFSET_1900_1970);
192 ntpmsg.trans_time.frac = htobe32(m->trans_time.tv_nsec);
194 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
196 len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
197 if (len == sizeof(ntpmsg)) {
199 log_debug("Sent NTP request to %s (%s).", strna(pretty), m->current_server_name->string);
201 log_debug("Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
202 return manager_connect(m);
205 /* re-arm timer with incresing timeout, in case the packets never arrive back */
206 if (m->retry_interval > 0) {
207 if (m->retry_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
208 m->retry_interval *= 2;
210 m->retry_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
212 r = manager_arm_timer(m, m->retry_interval);
214 log_error("Failed to rearm timer: %s", strerror(-r));
218 r = sd_event_add_time(
222 now(CLOCK_MONOTONIC) + TIMEOUT_USEC, 0,
225 log_error("Failed to arm timeout timer: %s", strerror(-r));
232 static int manager_timer(sd_event_source *source, usec_t usec, void *userdata) {
233 Manager *m = userdata;
237 return manager_send_request(m);
240 static int manager_arm_timer(Manager *m, usec_t next) {
244 assert(m->event_receive);
247 m->event_timer = sd_event_source_unref(m->event_timer);
251 if (m->event_timer) {
252 r = sd_event_source_set_time(m->event_timer, now(CLOCK_MONOTONIC) + next);
256 return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
259 return sd_event_add_time(
263 now(CLOCK_MONOTONIC) + next, 0,
267 static int manager_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
268 Manager *m = userdata;
273 manager_clock_watch_setup(m);
275 /* skip our own jumps */
282 log_info("System time changed. Resyncing.");
283 m->poll_resync = true;
284 return manager_send_request(m);
287 /* wake up when the system time changes underneath us */
288 static int manager_clock_watch_setup(Manager *m) {
290 struct itimerspec its = {
291 .it_value.tv_sec = TIME_T_MAX
298 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
299 safe_close(m->clock_watch_fd);
301 m->clock_watch_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
302 if (m->clock_watch_fd < 0) {
303 log_error("Failed to create timerfd: %m");
307 if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
308 log_error("Failed to set up timerfd: %m");
312 r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
314 log_error("Failed to create clock watch event source: %s", strerror(-r));
321 static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
322 struct timex tmx = {};
328 * For small deltas, tell the kernel to gradually adjust the system
329 * clock to the NTP time, larger deltas are just directly set.
331 * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
332 * syncs the system time periodically to the hardware clock.
334 if (fabs(offset) < NTP_MAX_ADJUST) {
335 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
336 tmx.status = STA_PLL;
337 tmx.offset = offset * NSEC_PER_SEC;
338 tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
341 log_debug(" adjust (slew): %+.3f sec\n", offset);
343 tmx.modes = ADJ_SETOFFSET | ADJ_NANO;
345 /* ADJ_NANO uses nanoseconds in the microseconds field */
346 tmx.time.tv_sec = (long)offset;
347 tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
349 /* the kernel expects -0.3s as {-1, 7000.000.000} */
350 if (tmx.time.tv_usec < 0) {
351 tmx.time.tv_sec -= 1;
352 tmx.time.tv_usec += NSEC_PER_SEC;
356 log_debug(" adjust (jump): %+.3f sec\n", offset);
361 tmx.status |= STA_INS;
364 tmx.status |= STA_DEL;
368 r = clock_adjtime(CLOCK_REALTIME, &tmx);
372 m->drift_ppm = tmx.freq / 65536;
374 log_debug(" status : %04i %s\n"
375 " time now : %li.%03lli\n"
377 " offset : %+.3f sec\n"
378 " freq offset : %+li (%i ppm)\n",
379 tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
380 tmx.time.tv_sec, 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 += square(m->samples[i].offset - m->samples[idx_min].offset);
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 bool sockaddr_equal(union sockaddr_union *a, union sockaddr_union *b) {
473 if (a->sa.sa_family != b->sa.sa_family)
476 if (a->sa.sa_family == AF_INET)
477 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
479 if (a->sa.sa_family == AF_INET6)
480 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
485 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
486 _cleanup_free_ char *pretty = NULL;
487 Manager *m = userdata;
488 struct ntp_msg ntpmsg;
492 .iov_len = sizeof(ntpmsg),
495 struct cmsghdr cmsghdr;
496 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
498 union sockaddr_union server_addr;
499 struct msghdr msghdr = {
502 .msg_control = &control,
503 .msg_controllen = sizeof(control),
504 .msg_name = &server_addr,
505 .msg_namelen = sizeof(server_addr),
507 struct cmsghdr *cmsg;
508 struct timespec now_ts;
509 struct timeval *recv_time;
511 double origin, receive, trans, dest;
512 double delay, offset;
520 if (revents & (EPOLLHUP|EPOLLERR)) {
521 log_warning("Server connection returned error.");
522 return manager_connect(m);
525 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
530 log_warning("Error receiving message. Disconnecting.");
531 return manager_connect(m);
534 if (iov.iov_len < sizeof(struct ntp_msg)) {
535 log_warning("Invalid response from server. Disconnecting.");
536 return manager_connect(m);
539 if (!m->current_server_name ||
540 !m->current_server_address ||
541 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
542 log_debug("Response from unknown server.");
547 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
548 if (cmsg->cmsg_level != SOL_SOCKET)
551 switch (cmsg->cmsg_type) {
553 recv_time = (struct timeval *) CMSG_DATA(cmsg);
558 log_error("Invalid packet timestamp.");
563 log_debug("Unexpected reply. Ignoring.");
567 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
568 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
569 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
570 log_debug("Invalid reply; not our transmit time. Ignoring.");
574 m->event_timeout = sd_event_source_unref(m->event_timeout);
576 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC) {
577 log_debug("Server is not synchronized. Disconnecting.");
578 return manager_connect(m);
581 if (NTP_FIELD_VERSION(ntpmsg.field) != 4 && NTP_FIELD_VERSION(ntpmsg.field) != 3) {
582 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
583 return manager_connect(m);
586 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
587 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
588 return manager_connect(m);
593 m->retry_interval = 0;
595 /* announce leap seconds */
596 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
598 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
604 * "Timestamp Name ID When Generated
605 * ------------------------------------------------------------
606 * Originate Timestamp T1 time request sent by client
607 * Receive Timestamp T2 time request received by server
608 * Transmit Timestamp T3 time reply sent by server
609 * Destination Timestamp T4 time reply received by client
611 * The round-trip delay, d, and system clock offset, t, are defined as:
612 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
614 assert_se(clock_gettime(CLOCK_MONOTONIC, &now_ts) >= 0);
615 origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&m->trans_time_mon)) + OFFSET_1900_1970;
616 receive = ntp_ts_to_d(&ntpmsg.recv_time);
617 trans = ntp_ts_to_d(&ntpmsg.trans_time);
618 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
620 offset = ((receive - origin) + (trans - dest)) / 2;
621 delay = (dest - origin) - (trans - receive);
623 spike = manager_sample_spike_detection(m, offset, delay);
625 manager_adjust_poll(m, offset, spike);
627 log_debug("NTP response:\n"
632 " precision : %.6f sec (%d)\n"
633 " reference : %.4s\n"
638 " offset : %+.3f sec\n"
639 " delay : %+.3f sec\n"
640 " packet count : %"PRIu64"\n"
642 " poll interval: %llu\n",
643 NTP_FIELD_LEAP(ntpmsg.field),
644 NTP_FIELD_VERSION(ntpmsg.field),
645 NTP_FIELD_MODE(ntpmsg.field),
647 exp2(ntpmsg.precision), ntpmsg.precision,
648 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
649 origin - OFFSET_1900_1970,
650 receive - OFFSET_1900_1970,
651 trans - OFFSET_1900_1970,
652 dest - OFFSET_1900_1970,
655 m->samples_jitter, spike ? " spike" : "",
656 m->poll_interval_usec / USEC_PER_SEC);
659 r = manager_adjust_clock(m, offset, leap_sec);
661 log_error("Failed to call clock_adjtime(): %m");
664 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
665 log_info("%s (%s): interval/delta/delay/jitter/drift %llus/%+.3fs/%.3fs/%.3fs/%+ippm%s",
666 strna(pretty), m->current_server_name->string, m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
667 spike ? " (ignored)" : "");
669 r = manager_arm_timer(m, m->poll_interval_usec);
671 log_error("Failed to rearm timer: %s", strerror(-r));
678 static int manager_listen_setup(Manager *m) {
679 union sockaddr_union addr = {};
680 static const int tos = IPTOS_LOWDELAY;
681 static const int on = 1;
686 assert(m->server_socket < 0);
687 assert(!m->event_receive);
688 assert(m->current_server_address);
690 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
692 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
693 if (m->server_socket < 0)
696 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
700 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
704 setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
706 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
709 static int manager_begin(Manager *m) {
710 _cleanup_free_ char *pretty = NULL;
714 assert_return(m->current_server_name, -EHOSTUNREACH);
715 assert_return(m->current_server_address, -EHOSTUNREACH);
717 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
719 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
720 log_info("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
721 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
723 r = manager_listen_setup(m);
725 log_warning("Failed to setup connection socket: %s", strerror(-r));
729 r = manager_clock_watch_setup(m);
733 return manager_send_request(m);
736 static void server_name_flush_addresses(ServerName *n) {
741 while ((a = n->addresses)) {
742 LIST_REMOVE(addresses, n->addresses, a);
747 static void manager_flush_names(Manager *m) {
752 while ((n = m->servers)) {
753 LIST_REMOVE(names, m->servers, n);
755 server_name_flush_addresses(n);
760 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
761 Manager *m = userdata;
762 ServerAddress *a, *last = NULL;
766 assert(m->current_server_name);
768 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
771 log_error("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
774 return manager_connect(m);
777 server_name_flush_addresses(m->current_server_name);
779 for (; ai; ai = ai->ai_next) {
780 _cleanup_free_ char *pretty = NULL;
783 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
784 assert(ai->ai_addrlen <= sizeof(union sockaddr_union));
786 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
787 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
791 a = new0(ServerAddress, 1);
795 memcpy(&a->sockaddr, ai->ai_addr, ai->ai_addrlen);
796 a->socklen = ai->ai_addrlen;
798 LIST_INSERT_AFTER(addresses, m->current_server_name->addresses, last, a);
801 sockaddr_pretty(&a->sockaddr.sa, a->socklen, true, &pretty);
802 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
805 if (!m->current_server_name->addresses) {
806 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
809 return manager_connect(m);
812 m->current_server_address = m->current_server_name->addresses;
814 return manager_begin(m);
817 static int manager_retry(sd_event_source *source, usec_t usec, void *userdata) {
818 Manager *m = userdata;
822 return manager_connect(m);
825 static int manager_connect(Manager *m) {
827 struct addrinfo hints = {
828 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
829 .ai_socktype = SOCK_DGRAM,
835 manager_disconnect(m);
837 m->event_retry = sd_event_source_unref(m->event_retry);
838 if (!ratelimit_test(&m->ratelimit)) {
839 log_debug("Slowing down attempts to contact servers.");
841 r = sd_event_add_time(m->event, &m->event_retry, CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + RETRY_USEC, 0, manager_retry, m);
843 log_error("Failed to create retry timer: %s", strerror(-r));
850 /* If we already are operating on some address, switch to the
852 if (m->current_server_address && m->current_server_address->addresses_next)
853 m->current_server_address = m->current_server_address->addresses_next;
855 /* Hmm, we are through all addresses, let's look for the next host instead */
856 m->current_server_address = NULL;
858 if (m->current_server_name && m->current_server_name->names_next)
859 m->current_server_name = m->current_server_name->names_next;
862 m->current_server_name = NULL;
863 log_debug("No server found.");
867 m->current_server_name = m->servers;
870 /* Tell the resolver to reread /etc/resolv.conf, in
871 * case it changed. */
874 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
876 log_error("Failed to create resolver: %s", strerror(-r));
883 r = manager_begin(m);
890 static int manager_add_server(Manager *m, const char *server) {
891 ServerName *n, *tail;
896 n = new0(ServerName, 1);
900 n->string = strdup(server);
906 LIST_FIND_TAIL(names, m->servers, tail);
907 LIST_INSERT_AFTER(names, m->servers, tail, n);
912 static int manager_add_server_string(Manager *m, const char *string) {
920 FOREACH_WORD_QUOTED(w, l, string, state) {
926 r = manager_add_server(m, t);
928 log_error("Failed to add server %s to configuration, ignoring: %s", t, strerror(-r));
934 static void manager_disconnect(Manager *m) {
937 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
939 m->event_timer = sd_event_source_unref(m->event_timer);
941 m->event_receive = sd_event_source_unref(m->event_receive);
942 m->server_socket = safe_close(m->server_socket);
944 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
945 m->clock_watch_fd = safe_close(m->clock_watch_fd);
947 m->event_timeout = sd_event_source_unref(m->event_timeout);
949 sd_notifyf(false, "STATUS=Idle.");
952 static int manager_new(Manager **ret) {
953 _cleanup_manager_free_ Manager *m = NULL;
956 m = new0(Manager, 1);
960 m->server_socket = m->clock_watch_fd = -1;
962 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
964 r = sd_event_default(&m->event);
968 sd_event_add_signal(m->event, &m->sigterm, SIGTERM, NULL, NULL);
969 sd_event_add_signal(m->event, &m->sigint, SIGINT, NULL, NULL);
971 r = sd_resolve_default(&m->resolve);
975 r = sd_resolve_attach_event(m->resolve, m->event, 0);
979 r = manager_clock_watch_setup(m);
989 static void manager_free(Manager *m) {
993 manager_disconnect(m);
994 manager_flush_names(m);
996 sd_event_source_unref(m->sigint);
997 sd_event_source_unref(m->sigterm);
999 sd_event_source_unref(m->event_retry);
1001 sd_resolve_unref(m->resolve);
1002 sd_event_unref(m->event);
1007 int config_parse_servers(
1009 const char *filename,
1011 const char *section,
1012 unsigned section_line,
1019 Manager *m = userdata;
1025 manager_flush_names(m);
1026 manager_add_server_string(m, rvalue);
1031 static int manager_parse_config_file(Manager *m) {
1032 static const char fn[] = "/etc/systemd/timesyncd.conf";
1033 _cleanup_fclose_ FILE *f = NULL;
1038 f = fopen(fn, "re");
1040 if (errno == ENOENT)
1043 log_warning("Failed to open configuration file %s: %m", fn);
1047 r = config_parse(NULL, fn, f, "Time\0", config_item_perf_lookup,
1048 (void*) timesyncd_gperf_lookup, false, false, m);
1050 log_warning("Failed to parse configuration file: %s", strerror(-r));
1055 int main(int argc, char *argv[]) {
1056 _cleanup_manager_free_ Manager *m = NULL;
1060 log_error("This program does not take arguments.");
1061 return EXIT_FAILURE;
1064 log_set_target(LOG_TARGET_AUTO);
1065 log_set_facility(LOG_CRON);
1066 log_parse_environment();
1071 assert_se(sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1) == 0);
1073 r = manager_new(&m);
1075 log_error("Failed to allocate manager: %s", strerror(-r));
1079 manager_add_server_string(m, NTP_SERVERS);
1080 manager_parse_config_file(m);
1082 log_debug("systemd-timesyncd running as pid %lu", (unsigned long) getpid());
1083 sd_notify(false, "READY=1");
1085 r = manager_connect(m);
1089 r = sd_event_loop(m->event);
1091 log_error("Failed to run event loop: %s", strerror(-r));
1095 sd_event_get_exit_code(m->event, &r);
1098 sd_notify(false, "STATUS=Shutting down...");
1100 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;