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 bool sockaddr_equal(union sockaddr_union *a, union sockaddr_union *b) {
543 if (a->sa.sa_family != b->sa.sa_family)
546 if (a->sa.sa_family == AF_INET)
547 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
549 if (a->sa.sa_family == AF_INET6)
550 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
555 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
556 Manager *m = userdata;
557 struct ntp_msg ntpmsg;
561 .iov_len = sizeof(ntpmsg),
564 struct cmsghdr cmsghdr;
565 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
567 union sockaddr_union server_addr;
568 struct msghdr msghdr = {
571 .msg_control = &control,
572 .msg_controllen = sizeof(control),
573 .msg_name = &server_addr,
574 .msg_namelen = sizeof(server_addr),
576 struct cmsghdr *cmsg;
577 struct timespec now_ts;
578 struct timeval *recv_time;
580 double origin, receive, trans, dest;
581 double delay, offset;
589 if (revents & (EPOLLHUP|EPOLLERR)) {
590 log_warning("Server connection returned error.");
591 return manager_connect(m);
594 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
599 log_warning("Error receiving message. Disconnecting.");
600 return manager_connect(m);
603 if (iov.iov_len < sizeof(struct ntp_msg)) {
604 log_warning("Invalid response from server. Disconnecting.");
605 return manager_connect(m);
608 if (!m->current_server_name ||
609 !m->current_server_address ||
610 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
611 log_debug("Response from unknown server.");
616 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
617 if (cmsg->cmsg_level != SOL_SOCKET)
620 switch (cmsg->cmsg_type) {
622 recv_time = (struct timeval *) CMSG_DATA(cmsg);
627 log_error("Invalid packet timestamp.");
632 log_debug("Unexpected reply. Ignoring.");
636 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
637 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
638 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
639 log_debug("Invalid reply; not our transmit time. Ignoring.");
643 m->event_timeout = sd_event_source_unref(m->event_timeout);
645 if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
646 be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
647 log_debug("Invalid reply, returned times before epoch. Ignoring.");
648 return manager_connect(m);
651 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC) {
652 log_debug("Server is not synchronized. Disconnecting.");
653 return manager_connect(m);
656 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
657 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
658 return manager_connect(m);
661 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
662 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
663 return manager_connect(m);
668 m->retry_interval = 0;
670 /* announce leap seconds */
671 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
673 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
679 * "Timestamp Name ID When Generated
680 * ------------------------------------------------------------
681 * Originate Timestamp T1 time request sent by client
682 * Receive Timestamp T2 time request received by server
683 * Transmit Timestamp T3 time reply sent by server
684 * Destination Timestamp T4 time reply received by client
686 * The round-trip delay, d, and system clock offset, t, are defined as:
687 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
689 assert_se(clock_gettime(clock_boottime_or_monotonic(), &now_ts) >= 0);
690 origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&m->trans_time_mon)) + OFFSET_1900_1970;
691 receive = ntp_ts_to_d(&ntpmsg.recv_time);
692 trans = ntp_ts_to_d(&ntpmsg.trans_time);
693 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
695 offset = ((receive - origin) + (trans - dest)) / 2;
696 delay = (dest - origin) - (trans - receive);
698 spike = manager_sample_spike_detection(m, offset, delay);
700 manager_adjust_poll(m, offset, spike);
702 log_debug("NTP response:\n"
707 " precision : %.6f sec (%d)\n"
708 " reference : %.4s\n"
713 " offset : %+.3f sec\n"
714 " delay : %+.3f sec\n"
715 " packet count : %"PRIu64"\n"
717 " poll interval: " USEC_FMT "\n",
718 NTP_FIELD_LEAP(ntpmsg.field),
719 NTP_FIELD_VERSION(ntpmsg.field),
720 NTP_FIELD_MODE(ntpmsg.field),
722 exp2(ntpmsg.precision), ntpmsg.precision,
723 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
724 origin - OFFSET_1900_1970,
725 receive - OFFSET_1900_1970,
726 trans - OFFSET_1900_1970,
727 dest - OFFSET_1900_1970,
730 m->samples_jitter, spike ? " spike" : "",
731 m->poll_interval_usec / USEC_PER_SEC);
735 r = manager_adjust_clock(m, offset, leap_sec);
737 log_error("Failed to call clock_adjtime(): %m");
740 log_info("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
741 m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
742 spike ? " (ignored)" : "");
744 r = manager_arm_timer(m, m->poll_interval_usec);
746 log_error("Failed to rearm timer: %s", strerror(-r));
753 static int manager_listen_setup(Manager *m) {
754 union sockaddr_union addr = {};
755 static const int tos = IPTOS_LOWDELAY;
756 static const int on = 1;
761 assert(m->server_socket < 0);
762 assert(!m->event_receive);
763 assert(m->current_server_address);
765 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
767 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
768 if (m->server_socket < 0)
771 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
775 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
779 setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
781 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
784 static int manager_begin(Manager *m) {
785 _cleanup_free_ char *pretty = NULL;
789 assert_return(m->current_server_name, -EHOSTUNREACH);
790 assert_return(m->current_server_address, -EHOSTUNREACH);
792 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
794 server_address_pretty(m->current_server_address, &pretty);
795 log_info("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
796 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
798 r = manager_listen_setup(m);
800 log_warning("Failed to setup connection socket: %s", strerror(-r));
804 r = manager_clock_watch_setup(m);
808 return manager_send_request(m);
811 static void server_name_flush_addresses(ServerName *n) {
816 while ((a = n->addresses)) {
817 LIST_REMOVE(addresses, n->addresses, a);
822 static void manager_flush_names(Manager *m) {
827 while ((n = m->servers)) {
828 LIST_REMOVE(names, m->servers, n);
830 server_name_flush_addresses(n);
835 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
836 Manager *m = userdata;
837 ServerAddress *a, *last = NULL;
841 assert(m->current_server_name);
843 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
846 log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
849 return manager_connect(m);
852 server_name_flush_addresses(m->current_server_name);
854 for (; ai; ai = ai->ai_next) {
855 _cleanup_free_ char *pretty = NULL;
858 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
859 assert(ai->ai_addrlen <= sizeof(union sockaddr_union));
861 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
862 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
866 a = new0(ServerAddress, 1);
870 memcpy(&a->sockaddr, ai->ai_addr, ai->ai_addrlen);
871 a->socklen = ai->ai_addrlen;
873 LIST_INSERT_AFTER(addresses, m->current_server_name->addresses, last, a);
876 sockaddr_pretty(&a->sockaddr.sa, a->socklen, true, &pretty);
877 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
880 if (!m->current_server_name->addresses) {
881 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
884 return manager_connect(m);
887 m->current_server_address = m->current_server_name->addresses;
889 return manager_begin(m);
892 static int manager_retry(sd_event_source *source, usec_t usec, void *userdata) {
893 Manager *m = userdata;
897 return manager_connect(m);
900 static int manager_connect(Manager *m) {
902 struct addrinfo hints = {
903 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
904 .ai_socktype = SOCK_DGRAM,
910 manager_disconnect(m);
912 m->event_retry = sd_event_source_unref(m->event_retry);
913 if (!ratelimit_test(&m->ratelimit)) {
914 log_debug("Slowing down attempts to contact servers.");
916 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);
918 log_error("Failed to create retry timer: %s", strerror(-r));
925 /* If we already are operating on some address, switch to the
927 if (m->current_server_address && m->current_server_address->addresses_next)
928 m->current_server_address = m->current_server_address->addresses_next;
930 /* Hmm, we are through all addresses, let's look for the next host instead */
931 m->current_server_address = NULL;
933 if (m->current_server_name && m->current_server_name->names_next)
934 m->current_server_name = m->current_server_name->names_next;
937 m->current_server_name = NULL;
938 log_debug("No server found.");
942 m->current_server_name = m->servers;
945 /* Tell the resolver to reread /etc/resolv.conf, in
946 * case it changed. */
949 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
951 log_error("Failed to create resolver: %s", strerror(-r));
958 r = manager_begin(m);
965 static int manager_add_server(Manager *m, const char *server) {
966 ServerName *n, *tail;
971 n = new0(ServerName, 1);
975 n->string = strdup(server);
981 LIST_FIND_TAIL(names, m->servers, tail);
982 LIST_INSERT_AFTER(names, m->servers, tail, n);
987 static int manager_add_server_string(Manager *m, const char *string) {
988 const char *word, *state;
995 FOREACH_WORD_QUOTED(word, l, string, state) {
1001 r = manager_add_server(m, t);
1003 log_error("Failed to add server %s to configuration, ignoring: %s", t, strerror(-r));
1005 if (!isempty(state))
1006 log_warning("Trailing garbage at the end of server list, ignoring.");
1011 static void manager_disconnect(Manager *m) {
1014 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
1016 m->event_timer = sd_event_source_unref(m->event_timer);
1018 m->event_receive = sd_event_source_unref(m->event_receive);
1019 m->server_socket = safe_close(m->server_socket);
1021 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
1022 m->clock_watch_fd = safe_close(m->clock_watch_fd);
1024 m->event_timeout = sd_event_source_unref(m->event_timeout);
1026 sd_notifyf(false, "STATUS=Idle.");
1029 static int manager_new(Manager **ret) {
1030 _cleanup_manager_free_ Manager *m = NULL;
1035 m = new0(Manager, 1);
1039 m->server_socket = m->clock_watch_fd = -1;
1041 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1043 r = sd_event_default(&m->event);
1047 sd_event_set_watchdog(m->event, true);
1049 sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1050 sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1052 r = sd_resolve_default(&m->resolve);
1056 r = sd_resolve_attach_event(m->resolve, m->event, 0);
1066 static void manager_free(Manager *m) {
1070 manager_disconnect(m);
1071 manager_flush_names(m);
1073 sd_event_source_unref(m->event_retry);
1075 sd_event_source_unref(m->network_event_source);
1076 sd_network_monitor_unref(m->network_monitor);
1078 sd_resolve_unref(m->resolve);
1079 sd_event_unref(m->event);
1084 int config_parse_servers(
1086 const char *filename,
1088 const char *section,
1089 unsigned section_line,
1096 Manager *m = userdata;
1102 manager_flush_names(m);
1103 manager_add_server_string(m, rvalue);
1108 static int manager_parse_config_file(Manager *m) {
1111 return config_parse(NULL, "/etc/systemd/timesyncd.conf", NULL,
1113 config_item_perf_lookup, timesyncd_gperf_lookup,
1114 false, false, true, m);
1117 static bool network_is_online(void) {
1118 _cleanup_free_ char *state = NULL;
1121 r = sd_network_get_operational_state(&state);
1122 if (r < 0) /* if we don't know anything, we consider the system online */
1125 if (STR_IN_SET(state, "routable", "degraded"))
1131 static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) {
1132 Manager *m = userdata;
1133 bool connected, online;
1138 sd_network_monitor_flush(m->network_monitor);
1140 /* check if the machine is online */
1141 online = network_is_online();
1143 /* check if the client is currently connected */
1144 connected = m->server_socket >= 0;
1146 if (connected && !online) {
1147 log_info("No network connectivity, watching for changes.");
1148 manager_disconnect(m);
1150 } else if (!connected && online) {
1151 log_info("Network configuration changed, trying to establish connection.");
1153 if (m->current_server_address)
1154 r = manager_begin(m);
1156 r = manager_connect(m);
1164 static int manager_network_monitor_listen(Manager *m) {
1169 r = sd_network_monitor_new(&m->network_monitor, NULL);
1173 fd = sd_network_monitor_get_fd(m->network_monitor);
1177 events = sd_network_monitor_get_events(m->network_monitor);
1181 r = sd_event_add_io(m->event, &m->network_event_source, fd, events, manager_network_event_handler, m);
1188 int main(int argc, char *argv[]) {
1189 _cleanup_manager_free_ Manager *m = NULL;
1190 const char *user = "systemd-timesync";
1196 log_error("This program does not take arguments.");
1197 return EXIT_FAILURE;
1200 log_set_target(LOG_TARGET_AUTO);
1201 log_set_facility(LOG_CRON);
1202 log_parse_environment();
1207 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1209 log_error("Cannot resolve user name %s: %s", user, strerror(-r));
1213 r = load_clock_timestamp(uid, gid);
1217 r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
1221 assert_se(sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1) == 0);
1223 r = manager_new(&m);
1225 log_error("Failed to allocate manager: %s", strerror(-r));
1229 if (clock_is_localtime() > 0) {
1230 log_info("The system is configured to read the RTC time in the local time zone. "
1231 "This mode can not be fully supported. All system time to RTC updates are disabled.");
1232 m->rtc_local_time = true;
1235 manager_add_server_string(m, NTP_SERVERS);
1236 manager_parse_config_file(m);
1238 r = manager_network_monitor_listen(m);
1240 log_error("Failed to listen to networkd events: %s", strerror(-r));
1244 log_debug("systemd-timesyncd running as pid %lu", (unsigned long) getpid());
1245 sd_notify(false, "READY=1");
1247 if (network_is_online()) {
1248 r = manager_connect(m);
1253 r = sd_event_loop(m->event);
1255 log_error("Failed to run event loop: %s", strerror(-r));
1259 sd_event_get_exit_code(m->event, &r);
1261 /* if we got an authoritative time, store it in the file system */
1263 touch("/var/lib/systemd/clock");
1266 sd_notify(false, "STATUS=Shutting down...");
1268 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;