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 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &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_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 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &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(
281 now(CLOCK_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_MONOTONIC) + next);
315 return sd_event_source_set_enabled(m->event_timer, SD_EVENT_ONESHOT);
318 return sd_event_add_time(
322 now(CLOCK_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 if (!m->current_server_address)
337 /* skip our own jumps */
344 log_info("System time changed. Resyncing.");
345 m->poll_resync = true;
346 return manager_send_request(m);
349 /* wake up when the system time changes underneath us */
350 static int manager_clock_watch_setup(Manager *m) {
352 struct itimerspec its = {
353 .it_value.tv_sec = TIME_T_MAX
360 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
361 safe_close(m->clock_watch_fd);
363 m->clock_watch_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
364 if (m->clock_watch_fd < 0) {
365 log_error("Failed to create timerfd: %m");
369 if (timerfd_settime(m->clock_watch_fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
370 log_error("Failed to set up timerfd: %m");
374 r = sd_event_add_io(m->event, &m->event_clock_watch, m->clock_watch_fd, EPOLLIN, manager_clock_watch, m);
376 log_error("Failed to create clock watch event source: %s", strerror(-r));
383 static int manager_adjust_clock(Manager *m, double offset, int leap_sec) {
384 struct timex tmx = {};
390 * For small deltas, tell the kernel to gradually adjust the system
391 * clock to the NTP time, larger deltas are just directly set.
393 * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
394 * syncs the system time periodically to the hardware clock.
396 if (fabs(offset) < NTP_MAX_ADJUST) {
397 tmx.modes = ADJ_STATUS | ADJ_NANO | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
398 tmx.status = STA_PLL;
399 tmx.offset = offset * NSEC_PER_SEC;
400 tmx.constant = log2i(m->poll_interval_usec / USEC_PER_SEC) - 4;
403 log_debug(" adjust (slew): %+.3f sec\n", offset);
405 tmx.modes = ADJ_SETOFFSET | ADJ_NANO;
407 /* ADJ_NANO uses nanoseconds in the microseconds field */
408 tmx.time.tv_sec = (long)offset;
409 tmx.time.tv_usec = (offset - tmx.time.tv_sec) * NSEC_PER_SEC;
411 /* the kernel expects -0.3s as {-1, 7000.000.000} */
412 if (tmx.time.tv_usec < 0) {
413 tmx.time.tv_sec -= 1;
414 tmx.time.tv_usec += NSEC_PER_SEC;
418 log_debug(" adjust (jump): %+.3f sec\n", offset);
423 tmx.status |= STA_INS;
426 tmx.status |= STA_DEL;
430 r = clock_adjtime(CLOCK_REALTIME, &tmx);
434 touch("/var/lib/systemd/clock");
436 m->drift_ppm = tmx.freq / 65536;
438 log_debug(" status : %04i %s\n"
439 " time now : %li.%03llu\n"
441 " offset : %+.3f sec\n"
442 " freq offset : %+li (%i ppm)\n",
443 tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
444 tmx.time.tv_sec, (unsigned long long) (tmx.time.tv_usec / NSEC_PER_MSEC),
446 (double)tmx.offset / NSEC_PER_SEC,
447 tmx.freq, m->drift_ppm);
452 static bool manager_sample_spike_detection(Manager *m, double offset, double delay) {
453 unsigned int i, idx_cur, idx_new, idx_min;
461 /* ignore initial sample */
462 if (m->packet_count == 1)
465 /* store the current data in our samples array */
466 idx_cur = m->samples_idx;
467 idx_new = (idx_cur + 1) % ELEMENTSOF(m->samples);
468 m->samples_idx = idx_new;
469 m->samples[idx_new].offset = offset;
470 m->samples[idx_new].delay = delay;
472 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
473 jitter = m->samples_jitter;
474 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(m->samples); i++)
475 if (m->samples[i].delay > 0 && m->samples[i].delay < m->samples[idx_min].delay)
479 for (i = 0; i < ELEMENTSOF(m->samples); i++)
480 j += square(m->samples[i].offset - m->samples[idx_min].offset);
481 m->samples_jitter = sqrt(j / (ELEMENTSOF(m->samples) - 1));
483 /* ignore samples when resyncing */
487 /* always accept offset if we are farther off than the round-trip delay */
488 if (fabs(offset) > delay)
491 /* we need a few samples before looking at them */
492 if (m->packet_count < 4)
495 /* do not accept anything worse than the maximum possible error of the best sample */
496 if (fabs(offset) > m->samples[idx_min].delay)
499 /* compare the difference between the current offset to the previous offset and jitter */
500 return fabs(offset - m->samples[idx_cur].offset) > 3 * jitter;
503 static void manager_adjust_poll(Manager *m, double offset, bool spike) {
506 if (m->poll_resync) {
507 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
508 m->poll_resync = false;
512 /* set to minimal poll interval */
513 if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
514 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
518 /* increase polling interval */
519 if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
520 if (m->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
521 m->poll_interval_usec *= 2;
525 /* decrease polling interval */
526 if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
527 if (m->poll_interval_usec > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
528 m->poll_interval_usec /= 2;
533 static bool sockaddr_equal(union sockaddr_union *a, union sockaddr_union *b) {
537 if (a->sa.sa_family != b->sa.sa_family)
540 if (a->sa.sa_family == AF_INET)
541 return a->in.sin_addr.s_addr == b->in.sin_addr.s_addr;
543 if (a->sa.sa_family == AF_INET6)
544 return memcmp(&a->in6.sin6_addr, &b->in6.sin6_addr, sizeof(a->in6.sin6_addr)) == 0;
549 static int manager_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
550 Manager *m = userdata;
551 struct ntp_msg ntpmsg;
555 .iov_len = sizeof(ntpmsg),
558 struct cmsghdr cmsghdr;
559 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
561 union sockaddr_union server_addr;
562 struct msghdr msghdr = {
565 .msg_control = &control,
566 .msg_controllen = sizeof(control),
567 .msg_name = &server_addr,
568 .msg_namelen = sizeof(server_addr),
570 struct cmsghdr *cmsg;
571 struct timespec now_ts;
572 struct timeval *recv_time;
574 double origin, receive, trans, dest;
575 double delay, offset;
583 if (revents & (EPOLLHUP|EPOLLERR)) {
584 log_warning("Server connection returned error.");
585 return manager_connect(m);
588 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
593 log_warning("Error receiving message. Disconnecting.");
594 return manager_connect(m);
597 if (iov.iov_len < sizeof(struct ntp_msg)) {
598 log_warning("Invalid response from server. Disconnecting.");
599 return manager_connect(m);
602 if (!m->current_server_name ||
603 !m->current_server_address ||
604 !sockaddr_equal(&server_addr, &m->current_server_address->sockaddr)) {
605 log_debug("Response from unknown server.");
610 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
611 if (cmsg->cmsg_level != SOL_SOCKET)
614 switch (cmsg->cmsg_type) {
616 recv_time = (struct timeval *) CMSG_DATA(cmsg);
621 log_error("Invalid packet timestamp.");
626 log_debug("Unexpected reply. Ignoring.");
630 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
631 if (be32toh(ntpmsg.origin_time.sec) != m->trans_time.tv_sec + OFFSET_1900_1970 ||
632 be32toh(ntpmsg.origin_time.frac) != m->trans_time.tv_nsec) {
633 log_debug("Invalid reply; not our transmit time. Ignoring.");
637 m->event_timeout = sd_event_source_unref(m->event_timeout);
639 if (be32toh(ntpmsg.recv_time.sec) < TIME_EPOCH + OFFSET_1900_1970 ||
640 be32toh(ntpmsg.trans_time.sec) < TIME_EPOCH + OFFSET_1900_1970) {
641 log_debug("Invalid reply, returned times before epoch. Ignoring.");
642 return manager_connect(m);
645 if (NTP_FIELD_LEAP(ntpmsg.field) == NTP_LEAP_NOTINSYNC) {
646 log_debug("Server is not synchronized. Disconnecting.");
647 return manager_connect(m);
650 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg.field), 3, 4)) {
651 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg.field));
652 return manager_connect(m);
655 if (NTP_FIELD_MODE(ntpmsg.field) != NTP_MODE_SERVER) {
656 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg.field));
657 return manager_connect(m);
662 m->retry_interval = 0;
664 /* announce leap seconds */
665 if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_PLUSSEC)
667 else if (NTP_FIELD_LEAP(ntpmsg.field) & NTP_LEAP_MINUSSEC)
673 * "Timestamp Name ID When Generated
674 * ------------------------------------------------------------
675 * Originate Timestamp T1 time request sent by client
676 * Receive Timestamp T2 time request received by server
677 * Transmit Timestamp T3 time reply sent by server
678 * Destination Timestamp T4 time reply received by client
680 * The round-trip delay, d, and system clock offset, t, are defined as:
681 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
683 assert_se(clock_gettime(CLOCK_MONOTONIC, &now_ts) >= 0);
684 origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&m->trans_time_mon)) + OFFSET_1900_1970;
685 receive = ntp_ts_to_d(&ntpmsg.recv_time);
686 trans = ntp_ts_to_d(&ntpmsg.trans_time);
687 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
689 offset = ((receive - origin) + (trans - dest)) / 2;
690 delay = (dest - origin) - (trans - receive);
692 spike = manager_sample_spike_detection(m, offset, delay);
694 manager_adjust_poll(m, offset, spike);
696 log_debug("NTP response:\n"
701 " precision : %.6f sec (%d)\n"
702 " reference : %.4s\n"
707 " offset : %+.3f sec\n"
708 " delay : %+.3f sec\n"
709 " packet count : %"PRIu64"\n"
711 " poll interval: " USEC_FMT "\n",
712 NTP_FIELD_LEAP(ntpmsg.field),
713 NTP_FIELD_VERSION(ntpmsg.field),
714 NTP_FIELD_MODE(ntpmsg.field),
716 exp2(ntpmsg.precision), ntpmsg.precision,
717 ntpmsg.stratum == 1 ? ntpmsg.refid : "n/a",
718 origin - OFFSET_1900_1970,
719 receive - OFFSET_1900_1970,
720 trans - OFFSET_1900_1970,
721 dest - OFFSET_1900_1970,
724 m->samples_jitter, spike ? " spike" : "",
725 m->poll_interval_usec / USEC_PER_SEC);
729 r = manager_adjust_clock(m, offset, leap_sec);
731 log_error("Failed to call clock_adjtime(): %m");
734 log_info("interval/delta/delay/jitter/drift " USEC_FMT "s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
735 m->poll_interval_usec / USEC_PER_SEC, offset, delay, m->samples_jitter, m->drift_ppm,
736 spike ? " (ignored)" : "");
738 r = manager_arm_timer(m, m->poll_interval_usec);
740 log_error("Failed to rearm timer: %s", strerror(-r));
747 static int manager_listen_setup(Manager *m) {
748 union sockaddr_union addr = {};
749 static const int tos = IPTOS_LOWDELAY;
750 static const int on = 1;
755 assert(m->server_socket < 0);
756 assert(!m->event_receive);
757 assert(m->current_server_address);
759 addr.sa.sa_family = m->current_server_address->sockaddr.sa.sa_family;
761 m->server_socket = socket(addr.sa.sa_family, SOCK_DGRAM | SOCK_CLOEXEC, 0);
762 if (m->server_socket < 0)
765 r = bind(m->server_socket, &addr.sa, m->current_server_address->socklen);
769 r = setsockopt(m->server_socket, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
773 setsockopt(m->server_socket, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
775 return sd_event_add_io(m->event, &m->event_receive, m->server_socket, EPOLLIN, manager_receive_response, m);
778 static int manager_begin(Manager *m) {
779 _cleanup_free_ char *pretty = NULL;
783 assert_return(m->current_server_name, -EHOSTUNREACH);
784 assert_return(m->current_server_address, -EHOSTUNREACH);
786 m->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
788 sockaddr_pretty(&m->current_server_address->sockaddr.sa, m->current_server_address->socklen, true, &pretty);
789 log_info("Using NTP server %s (%s).", strna(pretty), m->current_server_name->string);
790 sd_notifyf(false, "STATUS=Using Time Server %s (%s).", strna(pretty), m->current_server_name->string);
792 r = manager_listen_setup(m);
794 log_warning("Failed to setup connection socket: %s", strerror(-r));
798 r = manager_clock_watch_setup(m);
802 return manager_send_request(m);
805 static void server_name_flush_addresses(ServerName *n) {
810 while ((a = n->addresses)) {
811 LIST_REMOVE(addresses, n->addresses, a);
816 static void manager_flush_names(Manager *m) {
821 while ((n = m->servers)) {
822 LIST_REMOVE(names, m->servers, n);
824 server_name_flush_addresses(n);
829 static int manager_resolve_handler(sd_resolve_query *q, int ret, const struct addrinfo *ai, void *userdata) {
830 Manager *m = userdata;
831 ServerAddress *a, *last = NULL;
835 assert(m->current_server_name);
837 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
840 log_debug("Failed to resolve %s: %s", m->current_server_name->string, gai_strerror(ret));
843 return manager_connect(m);
846 server_name_flush_addresses(m->current_server_name);
848 for (; ai; ai = ai->ai_next) {
849 _cleanup_free_ char *pretty = NULL;
852 assert(ai->ai_addrlen >= offsetof(struct sockaddr, sa_data));
853 assert(ai->ai_addrlen <= sizeof(union sockaddr_union));
855 if (!IN_SET(ai->ai_addr->sa_family, AF_INET, AF_INET6)) {
856 log_warning("Unsuitable address protocol for %s", m->current_server_name->string);
860 a = new0(ServerAddress, 1);
864 memcpy(&a->sockaddr, ai->ai_addr, ai->ai_addrlen);
865 a->socklen = ai->ai_addrlen;
867 LIST_INSERT_AFTER(addresses, m->current_server_name->addresses, last, a);
870 sockaddr_pretty(&a->sockaddr.sa, a->socklen, true, &pretty);
871 log_debug("Resolved address %s for %s.", pretty, m->current_server_name->string);
874 if (!m->current_server_name->addresses) {
875 log_error("Failed to find suitable address for host %s.", m->current_server_name->string);
878 return manager_connect(m);
881 m->current_server_address = m->current_server_name->addresses;
883 return manager_begin(m);
886 static int manager_retry(sd_event_source *source, usec_t usec, void *userdata) {
887 Manager *m = userdata;
891 return manager_connect(m);
894 static int manager_connect(Manager *m) {
896 struct addrinfo hints = {
897 .ai_flags = AI_NUMERICSERV|AI_ADDRCONFIG,
898 .ai_socktype = SOCK_DGRAM,
904 manager_disconnect(m);
906 m->event_retry = sd_event_source_unref(m->event_retry);
907 if (!ratelimit_test(&m->ratelimit)) {
908 log_debug("Slowing down attempts to contact servers.");
910 r = sd_event_add_time(m->event, &m->event_retry, CLOCK_MONOTONIC, now(CLOCK_MONOTONIC) + RETRY_USEC, 0, manager_retry, m);
912 log_error("Failed to create retry timer: %s", strerror(-r));
919 /* If we already are operating on some address, switch to the
921 if (m->current_server_address && m->current_server_address->addresses_next)
922 m->current_server_address = m->current_server_address->addresses_next;
924 /* Hmm, we are through all addresses, let's look for the next host instead */
925 m->current_server_address = NULL;
927 if (m->current_server_name && m->current_server_name->names_next)
928 m->current_server_name = m->current_server_name->names_next;
931 m->current_server_name = NULL;
932 log_debug("No server found.");
936 m->current_server_name = m->servers;
939 /* Tell the resolver to reread /etc/resolv.conf, in
940 * case it changed. */
943 r = sd_resolve_getaddrinfo(m->resolve, &m->resolve_query, m->current_server_name->string, "123", &hints, manager_resolve_handler, m);
945 log_error("Failed to create resolver: %s", strerror(-r));
952 r = manager_begin(m);
959 static int manager_add_server(Manager *m, const char *server) {
960 ServerName *n, *tail;
965 n = new0(ServerName, 1);
969 n->string = strdup(server);
975 LIST_FIND_TAIL(names, m->servers, tail);
976 LIST_INSERT_AFTER(names, m->servers, tail, n);
981 static int manager_add_server_string(Manager *m, const char *string) {
989 FOREACH_WORD_QUOTED(w, l, string, state) {
995 r = manager_add_server(m, t);
997 log_error("Failed to add server %s to configuration, ignoring: %s", t, strerror(-r));
1003 static void manager_disconnect(Manager *m) {
1006 m->resolve_query = sd_resolve_query_unref(m->resolve_query);
1008 m->event_timer = sd_event_source_unref(m->event_timer);
1010 m->event_receive = sd_event_source_unref(m->event_receive);
1011 m->server_socket = safe_close(m->server_socket);
1013 m->event_clock_watch = sd_event_source_unref(m->event_clock_watch);
1014 m->clock_watch_fd = safe_close(m->clock_watch_fd);
1016 m->event_timeout = sd_event_source_unref(m->event_timeout);
1018 sd_notifyf(false, "STATUS=Idle.");
1021 static int manager_new(Manager **ret) {
1022 _cleanup_manager_free_ Manager *m = NULL;
1027 m = new0(Manager, 1);
1031 m->server_socket = m->clock_watch_fd = -1;
1033 RATELIMIT_INIT(m->ratelimit, RATELIMIT_INTERVAL_USEC, RATELIMIT_BURST);
1035 r = sd_event_default(&m->event);
1039 sd_event_set_watchdog(m->event, true);
1041 sd_event_add_signal(m->event, NULL, SIGTERM, NULL, NULL);
1042 sd_event_add_signal(m->event, NULL, SIGINT, NULL, NULL);
1044 r = sd_resolve_default(&m->resolve);
1048 r = sd_resolve_attach_event(m->resolve, m->event, 0);
1052 r = manager_clock_watch_setup(m);
1062 static void manager_free(Manager *m) {
1066 manager_disconnect(m);
1067 manager_flush_names(m);
1069 sd_event_source_unref(m->event_retry);
1071 sd_event_source_unref(m->network_event_source);
1072 sd_network_monitor_unref(m->network_monitor);
1074 sd_resolve_unref(m->resolve);
1075 sd_event_unref(m->event);
1080 int config_parse_servers(
1082 const char *filename,
1084 const char *section,
1085 unsigned section_line,
1092 Manager *m = userdata;
1098 manager_flush_names(m);
1099 manager_add_server_string(m, rvalue);
1104 static int manager_parse_config_file(Manager *m) {
1105 static const char fn[] = "/etc/systemd/timesyncd.conf";
1106 _cleanup_fclose_ FILE *f = NULL;
1111 f = fopen(fn, "re");
1113 if (errno == ENOENT)
1116 log_warning("Failed to open configuration file %s: %m", fn);
1120 r = config_parse(NULL, fn, f, "Time\0", config_item_perf_lookup,
1121 (void*) timesyncd_gperf_lookup, false, false, m);
1123 log_warning("Failed to parse configuration file: %s", strerror(-r));
1128 static bool network_is_online(void) {
1129 _cleanup_free_ char *state = NULL;
1132 r = sd_network_get_operational_state(&state);
1133 if (r >= 0 && STR_IN_SET(state, "routable", "degraded"))
1139 static int manager_network_event_handler(sd_event_source *s, int fd, uint32_t revents,
1141 Manager *m = userdata;
1142 bool connected, online;
1147 /* check if the machine is online */
1148 online = network_is_online();
1150 /* check if the client is currently connected */
1151 connected = (m->server_socket != -1);
1153 if (connected && !online) {
1154 log_info("No network connectivity, watching for changes.");
1155 manager_disconnect(m);
1156 } else if (!connected && online) {
1157 log_info("Network configuration changed, trying to establish connection.");
1158 if (m->current_server_address) {
1159 r = manager_begin(m);
1163 r = manager_connect(m);
1169 sd_network_monitor_flush(m->network_monitor);
1174 static int manager_network_monitor_listen(Manager *m) {
1175 _cleanup_event_source_unref_ sd_event_source *event_source = NULL;
1176 _cleanup_network_monitor_unref_ sd_network_monitor *monitor = NULL;
1179 r = sd_network_monitor_new(NULL, &monitor);
1183 fd = sd_network_monitor_get_fd(monitor);
1187 events = sd_network_monitor_get_events(monitor);
1191 r = sd_event_add_io(m->event, &event_source, fd, events,
1192 &manager_network_event_handler, m);
1196 m->network_monitor = monitor;
1197 m->network_event_source = event_source;
1199 event_source = NULL;
1204 int main(int argc, char *argv[]) {
1205 const char *user = "systemd-timesync";
1206 _cleanup_manager_free_ Manager *m = NULL;
1212 log_error("This program does not take arguments.");
1213 return EXIT_FAILURE;
1216 log_set_target(LOG_TARGET_AUTO);
1217 log_set_facility(LOG_CRON);
1218 log_parse_environment();
1223 r = get_user_creds(&user, &uid, &gid, NULL, NULL);
1225 log_error("Cannot resolve user name %s: %s", user, strerror(-r));
1229 r = load_clock_timestamp(uid, gid);
1233 r = drop_privileges(uid, gid, (1ULL << CAP_SYS_TIME));
1237 assert_se(sigprocmask_many(SIG_BLOCK, SIGTERM, SIGINT, -1) == 0);
1239 r = manager_new(&m);
1241 log_error("Failed to allocate manager: %s", strerror(-r));
1245 manager_add_server_string(m, NTP_SERVERS);
1246 manager_parse_config_file(m);
1248 r = manager_network_monitor_listen(m);
1250 log_error("Failed to listen to networkd events: %s", strerror(-r));
1254 log_debug("systemd-timesyncd running as pid %lu", (unsigned long) getpid());
1255 sd_notify(false, "READY=1");
1257 if (network_is_online()) {
1258 r = manager_connect(m);
1263 r = sd_event_loop(m->event);
1265 log_error("Failed to run event loop: %s", strerror(-r));
1269 sd_event_get_exit_code(m->event, &r);
1271 /* if we got an authoritative time, store it in the file system */
1273 touch("/var/lib/systemd/clock");
1276 sd_notify(false, "STATUS=Shutting down...");
1278 return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS;