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"
50 #include "sd-resolve.h"
51 #include "sd-daemon.h"
52 #include "sd-network.h"
53 #include "event-util.h"
54 #include "network-util.h"
55 #include "clock-util.h"
56 #include "capability.h"
58 #include "timesyncd.h"
60 #define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
63 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
66 /* expected accuracy of time synchronization; used to adjust the poll interval */
67 #define NTP_ACCURACY_SEC 0.2
70 * "A client MUST NOT under any conditions use a poll interval less
73 #define NTP_POLL_INTERVAL_MIN_SEC 32
74 #define NTP_POLL_INTERVAL_MAX_SEC 2048
77 * Maximum delta in seconds which the system clock is gradually adjusted
78 * (slew) to approach the network time. Deltas larger that this are set by
79 * letting the system time jump. The kernel's limit for adjtime is 0.5s.
81 #define NTP_MAX_ADJUST 0.4
83 /* NTP protocol, packet header */
84 #define NTP_LEAP_PLUSSEC 1
85 #define NTP_LEAP_MINUSSEC 2
86 #define NTP_LEAP_NOTINSYNC 3
87 #define NTP_MODE_CLIENT 3
88 #define NTP_MODE_SERVER 4
89 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
90 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
91 #define NTP_FIELD_MODE(f) ((f) & 7)
92 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
95 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
96 * in seconds relative to 0h on 1 January 1900."
98 #define OFFSET_1900_1970 2208988800UL
100 #define RETRY_USEC (30*USEC_PER_SEC)
101 #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
102 #define RATELIMIT_BURST 10
104 #define TIMEOUT_USEC (10*USEC_PER_SEC)
111 struct ntp_ts_short {
121 struct ntp_ts_short root_delay;
122 struct ntp_ts_short root_dispersion;
124 struct ntp_ts reference_time;
125 struct ntp_ts origin_time;
126 struct ntp_ts recv_time;
127 struct ntp_ts trans_time;
130 static void manager_free(Manager *m);
131 DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free);
132 #define _cleanup_manager_free_ _cleanup_(manager_freep)
134 static int manager_arm_timer(Manager *m, usec_t next);
135 static int manager_clock_watch_setup(Manager *m);
136 static int manager_connect(Manager *m);
137 static void manager_disconnect(Manager *m);
139 static double ntp_ts_to_d(const struct ntp_ts *ts) {
140 return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
143 static double ts_to_d(const struct timespec *ts) {
144 return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
147 static double tv_to_d(const struct timeval *tv) {
148 return tv->tv_sec + (1.0e-6 * tv->tv_usec);
151 static double square(double d) {
155 static int load_clock_timestamp(uid_t uid, gid_t gid) {
156 _cleanup_close_ int fd = -1;
157 usec_t min = TIME_EPOCH * USEC_PER_SEC;
161 /* Let's try to make sure that the clock is always
162 * monotonically increasing, by saving the clock whenever we
163 * have a new NTP time, or when we shut down, and restoring it
164 * when we start again. This is particularly helpful on
165 * systems lacking a battery backed RTC. We also will adjust
166 * the time to at least the build time of systemd. */
168 fd = open("/var/lib/systemd/clock", O_RDWR|O_CLOEXEC, 0644);
173 /* check if the recorded time is later than the compiled-in one */
176 stamp = timespec_load(&st.st_mtim);
181 /* Try to fix the access mode, so that we can still
182 touch the file after dropping priviliges */
184 fchown(fd, uid, gid);
187 /* create stamp file with the compiled-in date */
188 touch_file("/var/lib/systemd/clock", true, min, uid, gid, 0644);
190 ct = now(CLOCK_REALTIME);
193 char date[FORMAT_TIMESTAMP_MAX];
195 log_info("System clock time unset or jumped backwards, restoring from recorded timestamp: %s",
196 format_timestamp(date, sizeof(date), min));
198 if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, min)) < 0)
199 log_error("Failed to restore system clock: %m");
205 static int manager_timeout(sd_event_source *source, usec_t usec, void *userdata) {
206 _cleanup_free_ char *pretty = NULL;
207 Manager *m = userdata;
210 assert(m->current_server_name);
211 assert(m->current_server_address);
213 server_address_pretty(m->current_server_address, &pretty);
214 log_info("Timed out waiting for reply from %s (%s).", strna(pretty), m->current_server_name->string);
216 return manager_connect(m);
219 static int manager_send_request(Manager *m) {
220 _cleanup_free_ char *pretty = NULL;
221 struct ntp_msg ntpmsg = {
223 * "The client initializes the NTP message header, sends the request
224 * to the server, and strips the time of day from the Transmit
225 * Timestamp field of the reply. For this purpose, all the NTP
226 * header fields are set to 0, except the Mode, VN, and optional
227 * Transmit Timestamp fields."
229 .field = NTP_FIELD(0, 4, NTP_MODE_CLIENT),
235 assert(m->current_server_name);
236 assert(m->current_server_address);
238 m->event_timeout = sd_event_source_unref(m->event_timeout);
241 * Set transmit timestamp, remember it; the server will send that back
242 * as the origin timestamp and we have an indication that this is the
243 * matching answer to our request.
245 * The actual value does not matter, We do not care about the correct
246 * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
248 assert_se(clock_gettime(clock_boottime_or_monotonic(), &m->trans_time_mon) >= 0);
249 assert_se(clock_gettime(CLOCK_REALTIME, &m->trans_time) >= 0);
250 ntpmsg.trans_time.sec = htobe32(m->trans_time.tv_sec + OFFSET_1900_1970);
251 ntpmsg.trans_time.frac = htobe32(m->trans_time.tv_nsec);
253 server_address_pretty(m->current_server_address, &pretty);
255 len = sendto(m->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &m->current_server_address->sockaddr.sa, m->current_server_address->socklen);
256 if (len == sizeof(ntpmsg)) {
258 log_debug("Sent NTP request to %s (%s).", strna(pretty), m->current_server_name->string);
260 log_debug("Sending NTP request to %s (%s) failed: %m", strna(pretty), m->current_server_name->string);
261 return manager_connect(m);
264 /* re-arm timer with increasing timeout, in case the packets never arrive back */
265 if (m->retry_interval > 0) {
266 if (m->retry_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
267 m->retry_interval *= 2;
269 m->retry_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
271 r = manager_arm_timer(m, m->retry_interval);
273 log_error("Failed to rearm timer: %s", strerror(-r));
277 r = sd_event_add_time(
280 clock_boottime_or_monotonic(),
281 now(clock_boottime_or_monotonic()) + TIMEOUT_USEC, 0,
284 log_error("Failed to arm timeout timer: %s", strerror(-r));
291 static int manager_timer(sd_event_source *source, usec_t usec, void *userdata) {
292 Manager *m = userdata;
296 return manager_send_request(m);
299 static int manager_arm_timer(Manager *m, usec_t next) {
303 assert(m->event_receive);
306 m->event_timer = sd_event_source_unref(m->event_timer);
310 if (m->event_timer) {
311 r = sd_event_source_set_time(m->event_timer, now(clock_boottime_or_monotonic()) + next);
315 return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
318 return sd_event_add_time(
321 clock_boottime_or_monotonic(),
322 now(clock_boottime_or_monotonic()) + next, 0,
326 static int manager_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
327 Manager *m = userdata;
332 manager_clock_watch_setup(m);
334 /* skip our own jumps */
341 log_info("System time changed. Resyncing.");
342 m->poll_resync = true;
344 return manager_send_request(m);
347 /* wake up when the system time changes underneath us */
348 static int manager_clock_watch_setup(Manager *m) {
350 struct itimerspec its = {
351 .it_value.tv_sec = TIME_T_MAX
358 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
359 safe_close(m->clock_watch_fd);
361 m->clock_watch_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
362 if (m->clock_watch_fd < 0) {
363 log_error("Failed to create timerfd: %m");
367 if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
368 log_error("Failed to set up timerfd: %m");
372 r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
374 log_error("Failed to create clock watch event source: %s", strerror(-r));
381 static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
382 struct timex tmx = {};
388 * For small deltas, tell the kernel to gradually adjust the system
389 * clock to the NTP time, larger deltas are just directly set.
391 if (fabs(offset) < NTP_MAX_ADJUST) {
392 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
393 tmx.status = STA_PLL;
394 tmx.offset = offset * NSEC_PER_SEC;
395 tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
398 log_debug(" adjust (slew): %+.3f sec\n", offset);
400 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_SETOFFSET;
402 /* ADJ_NANO uses nanoseconds in the microseconds field */
403 tmx.time.tv_sec = (long)offset;
404 tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
406 /* the kernel expects -0.3s as {-1, 7000.000.000} */
407 if (tmx.time.tv_usec < 0) {
408 tmx.time.tv_sec -= 1;
409 tmx.time.tv_usec += NSEC_PER_SEC;
413 log_debug(" adjust (jump): %+.3f sec\n", offset);
417 * An unset STA_UNSYNC will enable the kernel's 11-minute mode,
418 * which syncs the system time periodically to the RTC.
420 * In case the RTC runs in local time, never touch the RTC,
421 * we have no way to properly handle daylight saving changes and
422 * mobile devices moving between time zones.
424 if (m->rtc_local_time)
425 tmx.status |= STA_UNSYNC;
429 tmx.status |= STA_INS;
432 tmx.status |= STA_DEL;
436 r = clock_adjtime(CLOCK_REALTIME, &tmx);
440 touch("/var/lib/systemd/clock");
442 m->drift_ppm = tmx.freq / 65536;
444 log_debug(" status : %04i %s\n"
445 " time now : %li.%03llu\n"
447 " offset : %+.3f sec\n"
448 " freq offset : %+li (%i ppm)\n",
449 tmx.status, tmx.status & STA_UNSYNC ? "unsync" : "sync",
450 tmx.time.tv_sec, (unsigned long long) (tmx.time.tv_usec / NSEC_PER_MSEC),
452 (double)tmx.offset / NSEC_PER_SEC,
453 tmx.freq, m->drift_ppm);
458 static bool manager_sample_spike_detection(Manager *m, double offset, double delay) {
459 unsigned int i, idx_cur, idx_new, idx_min;
467 /* ignore initial sample */
468 if (m->packet_count == 1)
471 /* store the current data in our samples array */
472 idx_cur = m->samples_idx;
473 idx_new = (idx_cur + 1) % ELEMENTSOF(m->samples);
474 m->samples_idx = idx_new;
475 m->samples[idx_new].offset = offset;
476 m->samples[idx_new].delay = delay;
478 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
479 jitter = m->samples_jitter;
480 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(m->samples); i++)
481 if (m->samples[i].delay > 0 && m->samples[i].delay < m->samples[idx_min].delay)
485 for (i = 0; i < ELEMENTSOF(m->samples); i++)
486 j += square(m->samples[i].offset - m->samples[idx_min].offset);
487 m->samples_jitter = sqrt(j / (ELEMENTSOF(m->samples) - 1));
489 /* ignore samples when resyncing */
493 /* always accept offset if we are farther off than the round-trip delay */
494 if (fabs(offset) > delay)
497 /* we need a few samples before looking at them */
498 if (m->packet_count < 4)
501 /* do not accept anything worse than the maximum possible error of the best sample */
502 if (fabs(offset) > m->samples[idx_min].delay)
505 /* compare the difference between the current offset to the previous offset and jitter */
506 return fabs(offset - m->samples[idx_cur].offset) > 3 * jitter;
509 static void manager_adjust_poll(Manager *m, double offset, bool spike) {
512 if (m->poll_resync) {
513 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
514 m->poll_resync = false;
518 /* set to minimal poll interval */
519 if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
520 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
524 /* increase polling interval */
525 if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
526 if (m->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
527 m->poll_interval_usec *= 2;
531 /* decrease polling interval */
532 if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
533 if (m->poll_interval_usec > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
534 m->poll_interval_usec /= 2;
539 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
540 Manager *m = userdata;
541 struct ntp_msg ntpmsg;
545 .iov_len = sizeof(ntpmsg),
548 struct cmsghdr cmsghdr;
549 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
551 union sockaddr_union server_addr;
552 struct msghdr msghdr = {
555 .msg_control = &control,
556 .msg_controllen = sizeof(control),
557 .msg_name = &server_addr,
558 .msg_namelen = sizeof(server_addr),
560 struct cmsghdr *cmsg;
561 struct timespec now_ts;
562 struct timeval *recv_time;
564 double origin, receive, trans, dest;
565 double delay, offset;
573 if (revents & (EPOLLHUP|EPOLLERR)) {
574 log_warning("Server connection returned error.");
575 return manager_connect(m);
578 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
583 log_warning("Error receiving message. Disconnecting.");
584 return manager_connect(m);
587 if (iov.iov_len < sizeof(struct ntp_msg)) {
588 log_warning("Invalid response from server. Disconnecting.");
589 return manager_connect(m);
592 if (!m->current_server_name ||
593 !m->current_server_address ||
594 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
595 log_debug("Response from unknown server.");
600 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
601 if (cmsg->cmsg_level != SOL_SOCKET)
604 switch (cmsg->cmsg_type) {
606 recv_time = (struct timeval *) CMSG_DATA(cmsg);
611 log_error("Invalid packet timestamp.");
616 log_debug("Unexpected reply. Ignoring.");
620 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
621 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
622 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
623 log_debug("Invalid reply; not our transmit time. Ignoring.");
627 m->event_timeout = sd_event_source_unref(m->event_timeout);
629 if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
630 be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
631 log_debug("Invalid reply, returned times before epoch. Ignoring.");
632 return manager_connect(m);
635 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC) {
636 log_debug("Server is not synchronized. Disconnecting.");
637 return manager_connect(m);
640 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
641 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
642 return manager_connect(m);
645 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
646 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
647 return manager_connect(m);
652 m->retry_interval = 0;
654 /* announce leap seconds */
655 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
657 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
663 * "Timestamp Name ID When Generated
664 * ------------------------------------------------------------
665 * Originate Timestamp T1 time request sent by client
666 * Receive Timestamp T2 time request received by server
667 * Transmit Timestamp T3 time reply sent by server
668 * Destination Timestamp T4 time reply received by client
670 * The round-trip delay, d, and system clock offset, t, are defined as:
671 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
673 assert_se(clock_gettime(clock_boottime_or_monotonic(), &now_ts) >= 0);
674 origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&m->trans_time_mon)) + OFFSET_1900_1970;
675 receive = ntp_ts_to_d(&ntpmsg.recv_time);
676 trans = ntp_ts_to_d(&ntpmsg.trans_time);
677 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
679 offset = ((receive - origin) + (trans - dest)) / 2;
680 delay = (dest - origin) - (trans - receive);
682 spike = manager_sample_spike_detection(m, offset, delay);
684 manager_adjust_poll(m, offset, spike);
686 log_debug("NTP response:\n"
691 " precision : %.6f sec (%d)\n"
692 " reference : %.4s\n"
697 " offset : %+.3f sec\n"
698 " delay : %+.3f sec\n"
699 " packet count : %"PRIu64"\n"
701 " poll interval: " USEC_FMT "\n",
702 NTP_FIELD_LEAP(ntpmsg.field),
703 NTP_FIELD_VERSION(ntpmsg.field),
704 NTP_FIELD_MODE(ntpmsg.field),
706 exp2(ntpmsg.precision), ntpmsg.precision,
707 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
708 origin - OFFSET_1900_1970,
709 receive - OFFSET_1900_1970,
710 trans - OFFSET_1900_1970,
711 dest - OFFSET_1900_1970,
714 m->samples_jitter, spike ? " spike" : "",
715 m->poll_interval_usec / USEC_PER_SEC);
719 r = manager_adjust_clock(m, offset, leap_sec);
721 log_error("Failed to call clock_adjtime(): %m");
724 log_info("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
725 m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
726 spike ? " (ignored)" : "");
728 r = manager_arm_timer(m, m->poll_interval_usec);
730 log_error("Failed to rearm timer: %s", strerror(-r));
737 static int manager_listen_setup(Manager *m) {
738 union sockaddr_union addr = {};
739 static const int tos = IPTOS_LOWDELAY;
740 static const int on = 1;
745 assert(m->server_socket < 0);
746 assert(!m->event_receive);
747 assert(m->current_server_address);
749 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
751 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
752 if (m->server_socket < 0)
755 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
759 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
763 setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
765 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
768 static int manager_begin(Manager *m) {
769 _cleanup_free_ char *pretty = NULL;
773 assert_return(m->current_server_name, -EHOSTUNREACH);
774 assert_return(m->current_server_address, -EHOSTUNREACH);
776 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
778 server_address_pretty(m->current_server_address, &pretty);
779 log_info("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
780 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
782 r = manager_listen_setup(m);
784 log_warning("Failed to setup connection socket: %s", strerror(-r));
788 r = manager_clock_watch_setup(m);
792 return manager_send_request(m);
795 static void server_name_flush_addresses(ServerName *n) {
800 while ((a = n->addresses)) {
801 LIST_REMOVE(addresses, n->addresses, a);
806 static void manager_flush_names(Manager *m) {
811 while ((n = m->servers)) {
812 LIST_REMOVE(names, m->servers, n);
814 server_name_flush_addresses(n);
819 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
820 Manager *m = userdata;
821 ServerAddress *a, *last = NULL;
825 assert(m->current_server_name);
827 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
830 log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
833 return manager_connect(m);
836 server_name_flush_addresses(m->current_server_name);
838 for (; ai; ai = ai->ai_next) {
839 _cleanup_free_ char *pretty = NULL;
842 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
843 assert(ai->ai_addrlen <= sizeof(union sockaddr_union));
845 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
846 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
850 a = new0(ServerAddress, 1);
854 memcpy(&a->sockaddr, ai->ai_addr, ai->ai_addrlen);
855 a->socklen = ai->ai_addrlen;
857 LIST_INSERT_AFTER(addresses, m->current_server_name->addresses, last, a);
860 sockaddr_pretty(&a->sockaddr.sa, a->socklen, true, &pretty);
861 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
864 if (!m->current_server_name->addresses) {
865 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
868 return manager_connect(m);
871 m->current_server_address = m->current_server_name->addresses;
873 return manager_begin(m);
876 static int manager_retry(sd_event_source *source, usec_t usec, void *userdata) {
877 Manager *m = userdata;
881 return manager_connect(m);
884 static int manager_connect(Manager *m) {
886 struct addrinfo hints = {
887 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
888 .ai_socktype = SOCK_DGRAM,
894 manager_disconnect(m);
896 m->event_retry = sd_event_source_unref(m->event_retry);
897 if (!ratelimit_test(&m->ratelimit)) {
898 log_debug("Slowing down attempts to contact servers.");
900 r = sd_event_add_time(m->event, &m->event_retry, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + RETRY_USEC, 0, manager_retry, m);
902 log_error("Failed to create retry timer: %s", strerror(-r));
909 /* If we already are operating on some address, switch to the
911 if (m->current_server_address && m->current_server_address->addresses_next)
912 m->current_server_address = m->current_server_address->addresses_next;
914 /* Hmm, we are through all addresses, let's look for the next host instead */
915 m->current_server_address = NULL;
917 if (m->current_server_name && m->current_server_name->names_next)
918 m->current_server_name = m->current_server_name->names_next;
921 m->current_server_name = NULL;
922 log_debug("No server found.");
926 m->current_server_name = m->servers;
929 /* Tell the resolver to reread /etc/resolv.conf, in
930 * case it changed. */
933 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
935 log_error("Failed to create resolver: %s", strerror(-r));
942 r = manager_begin(m);
949 static int manager_add_server(Manager *m, const char *server) {
950 ServerName *n, *tail;
955 n = new0(ServerName, 1);
959 n->string = strdup(server);
965 LIST_FIND_TAIL(names, m->servers, tail);
966 LIST_INSERT_AFTER(names, m->servers, tail, n);
971 static int manager_add_server_string(Manager *m, const char *string) {
972 const char *word, *state;
979 FOREACH_WORD_QUOTED(word, l, string, state) {
985 r = manager_add_server(m, t);
987 log_error("Failed to add server %s to configuration, ignoring: %s", t, strerror(-r));
990 log_warning("Trailing garbage at the end of server list, ignoring.");
995 static void manager_disconnect(Manager *m) {
998 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
1000 m->event_timer = sd_event_source_unref(m->event_timer);
1002 m->event_receive = sd_event_source_unref(m->event_receive);
1003 m->server_socket = safe_close(m->server_socket);
1005 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
1006 m->clock_watch_fd = safe_close(m->clock_watch_fd);
1008 m->event_timeout = sd_event_source_unref(m->event_timeout);
1010 sd_notifyf(false, "STATUS=Idle.");
1013 static int manager_new(Manager **ret) {
1014 _cleanup_manager_free_ Manager *m = NULL;
1019 m = new0(Manager, 1);
1023 m->server_socket = m->clock_watch_fd = -1;
1025 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1027 r = sd_event_default(&m->event);
1031 sd_event_set_watchdog(m->event, true);
1033 sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1034 sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1036 r = sd_resolve_default(&m->resolve);
1040 r = sd_resolve_attach_event(m->resolve, m->event, 0);
1050 static void manager_free(Manager *m) {
1054 manager_disconnect(m);
1055 manager_flush_names(m);
1057 sd_event_source_unref(m->event_retry);
1059 sd_event_source_unref(m->network_event_source);
1060 sd_network_monitor_unref(m->network_monitor);
1062 sd_resolve_unref(m->resolve);
1063 sd_event_unref(m->event);
1068 int config_parse_servers(
1070 const char *filename,
1072 const char *section,
1073 unsigned section_line,
1080 Manager *m = userdata;
1086 manager_flush_names(m);
1087 manager_add_server_string(m, rvalue);
1092 static int manager_parse_config_file(Manager *m) {
1095 return config_parse(NULL, "/etc/systemd/timesyncd.conf", NULL,
1097 config_item_perf_lookup, timesyncd_gperf_lookup,
1098 false, false, true, m);
1101 static bool network_is_online(void) {
1102 _cleanup_free_ char *state = NULL;
1105 r = sd_network_get_operational_state(&state);
1106 if (r < 0) /* if we don't know anything, we consider the system online */
1109 if (STR_IN_SET(state, "routable", "degraded"))
1115 static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1116 Manager *m = userdata;
1117 bool connected, online;
1122 sd_network_monitor_flush(m->network_monitor);
1124 /* check if the machine is online */
1125 online = network_is_online();
1127 /* check if the client is currently connected */
1128 connected = m->server_socket >= 0;
1130 if (connected && !online) {
1131 log_info("No network connectivity, watching for changes.");
1132 manager_disconnect(m);
1134 } else if (!connected && online) {
1135 log_info("Network configuration changed, trying to establish connection.");
1137 if (m->current_server_address)
1138 r = manager_begin(m);
1140 r = manager_connect(m);
1148 static int manager_network_monitor_listen(Manager *m) {
1153 r = sd_network_monitor_new(&m->network_monitor, NULL);
1157 fd = sd_network_monitor_get_fd(m->network_monitor);
1161 events = sd_network_monitor_get_events(m->network_monitor);
1165 r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
1172 int main(int argc, char *argv[]) {
1173 _cleanup_manager_free_ Manager *m = NULL;
1174 const char *user = "systemd-timesync";
1180 log_error("This program does not take arguments.");
1181 return EXIT_FAILURE;
1184 log_set_target(LOG_TARGET_AUTO);
1185 log_set_facility(LOG_CRON);
1186 log_parse_environment();
1191 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1193 log_error("Cannot resolve user name %s: %s", user, strerror(-r));
1197 r = load_clock_timestamp(uid, gid);
1201 r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
1205 assert_se(sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1) == 0);
1207 r = manager_new(&m);
1209 log_error("Failed to allocate manager: %s", strerror(-r));
1213 if (clock_is_localtime() > 0) {
1214 log_info("The system is configured to read the RTC time in the local time zone. "
1215 "This mode can not be fully supported. All system time to RTC updates are disabled.");
1216 m->rtc_local_time = true;
1219 manager_add_server_string(m, NTP_SERVERS);
1220 manager_parse_config_file(m);
1222 r = manager_network_monitor_listen(m);
1224 log_error("Failed to listen to networkd events: %s", strerror(-r));
1228 log_debug("systemd-timesyncd running as pid %lu", (unsigned long) getpid());
1229 sd_notify(false, "READY=1");
1231 if (network_is_online()) {
1232 r = manager_connect(m);
1237 r = sd_event_loop(m->event);
1239 log_error("Failed to run event loop: %s", strerror(-r));
1243 sd_event_get_exit_code(m->event, &r);
1245 /* if we got an authoritative time, store it in the file system */
1247 touch("/var/lib/systemd/clock");
1250 sd_notify(false, "STATUS=Shutting down...");
1252 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;