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/>.
24 #include <netinet/in.h>
25 #include <netinet/ip.h>
28 #include <sys/socket.h>
29 #include <sys/timerfd.h>
30 #include <sys/timex.h>
31 #include <sys/types.h>
34 #include "sd-daemon.h"
36 #include "alloc-util.h"
42 #include "network-util.h"
43 #include "ratelimit.h"
44 #include "socket-util.h"
45 #include "sparse-endian.h"
46 #include "string-util.h"
48 #include "time-util.h"
49 #include "timesyncd-conf.h"
50 #include "timesyncd-manager.h"
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))
85 /* Maximum acceptable root distance in seconds. */
86 #define NTP_MAX_ROOT_DISTANCE 5.0
88 /* Maximum number of missed replies before selecting another source. */
89 #define NTP_MAX_MISSED_REPLIES 2
92 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
93 * in seconds relative to 0h on 1 January 1900."
95 #define OFFSET_1900_1970 UINT64_C(2208988800)
97 #define RETRY_USEC (30*USEC_PER_SEC)
98 #define RATELIMIT_INTERVAL_USEC (10*USEC_PER_SEC)
99 #define RATELIMIT_BURST 10
101 #define TIMEOUT_USEC (10*USEC_PER_SEC)
108 struct ntp_ts_short
{
118 struct ntp_ts_short root_delay
;
119 struct ntp_ts_short root_dispersion
;
121 struct ntp_ts reference_time
;
122 struct ntp_ts origin_time
;
123 struct ntp_ts recv_time
;
124 struct ntp_ts trans_time
;
127 static int manager_arm_timer(Manager
*m
, usec_t next
);
128 static int manager_clock_watch_setup(Manager
*m
);
129 static int manager_listen_setup(Manager
*m
);
130 static void manager_listen_stop(Manager
*m
);
132 static double ntp_ts_short_to_d(const struct ntp_ts_short
*ts
) {
133 return be16toh(ts
->sec
) + (be16toh(ts
->frac
) / 65536.0);
136 static double ntp_ts_to_d(const struct ntp_ts
*ts
) {
137 return be32toh(ts
->sec
) + ((double)be32toh(ts
->frac
) / UINT_MAX
);
140 static double ts_to_d(const struct timespec
*ts
) {
141 return ts
->tv_sec
+ (1.0e-9 * ts
->tv_nsec
);
144 static int manager_timeout(sd_event_source
*source
, usec_t usec
, void *userdata
) {
145 _cleanup_free_
char *pretty
= NULL
;
146 Manager
*m
= userdata
;
149 assert(m
->current_server_name
);
150 assert(m
->current_server_address
);
152 server_address_pretty(m
->current_server_address
, &pretty
);
153 log_info("Timed out waiting for reply from %s (%s).", strna(pretty
), m
->current_server_name
->string
);
155 return manager_connect(m
);
158 static int manager_send_request(Manager
*m
) {
159 _cleanup_free_
char *pretty
= NULL
;
160 struct ntp_msg ntpmsg
= {
162 * "The client initializes the NTP message header, sends the request
163 * to the server, and strips the time of day from the Transmit
164 * Timestamp field of the reply. For this purpose, all the NTP
165 * header fields are set to 0, except the Mode, VN, and optional
166 * Transmit Timestamp fields."
168 .field
= NTP_FIELD(0, 4, NTP_MODE_CLIENT
),
174 assert(m
->current_server_name
);
175 assert(m
->current_server_address
);
177 m
->event_timeout
= sd_event_source_unref(m
->event_timeout
);
179 r
= manager_listen_setup(m
);
181 return log_warning_errno(r
, "Failed to setup connection socket: %m");
184 * Set transmit timestamp, remember it; the server will send that back
185 * as the origin timestamp and we have an indication that this is the
186 * matching answer to our request.
188 * The actual value does not matter, We do not care about the correct
189 * NTP UINT_MAX fraction; we just pass the plain nanosecond value.
191 assert_se(clock_gettime(clock_boottime_or_monotonic(), &m
->trans_time_mon
) >= 0);
192 assert_se(clock_gettime(CLOCK_REALTIME
, &m
->trans_time
) >= 0);
193 ntpmsg
.trans_time
.sec
= htobe32(m
->trans_time
.tv_sec
+ OFFSET_1900_1970
);
194 ntpmsg
.trans_time
.frac
= htobe32(m
->trans_time
.tv_nsec
);
196 server_address_pretty(m
->current_server_address
, &pretty
);
198 len
= sendto(m
->server_socket
, &ntpmsg
, sizeof(ntpmsg
), MSG_DONTWAIT
, &m
->current_server_address
->sockaddr
.sa
, m
->current_server_address
->socklen
);
199 if (len
== sizeof(ntpmsg
)) {
201 log_debug("Sent NTP request to %s (%s).", strna(pretty
), m
->current_server_name
->string
);
203 log_debug_errno(errno
, "Sending NTP request to %s (%s) failed: %m", strna(pretty
), m
->current_server_name
->string
);
204 return manager_connect(m
);
207 /* re-arm timer with increasing timeout, in case the packets never arrive back */
208 if (m
->retry_interval
> 0) {
209 if (m
->retry_interval
< NTP_POLL_INTERVAL_MAX_SEC
* USEC_PER_SEC
)
210 m
->retry_interval
*= 2;
212 m
->retry_interval
= NTP_POLL_INTERVAL_MIN_SEC
* USEC_PER_SEC
;
214 r
= manager_arm_timer(m
, m
->retry_interval
);
216 return log_error_errno(r
, "Failed to rearm timer: %m");
219 if (m
->missed_replies
> NTP_MAX_MISSED_REPLIES
) {
220 r
= sd_event_add_time(
223 clock_boottime_or_monotonic(),
224 now(clock_boottime_or_monotonic()) + TIMEOUT_USEC
, 0,
227 return log_error_errno(r
, "Failed to arm timeout timer: %m");
233 static int manager_timer(sd_event_source
*source
, usec_t usec
, void *userdata
) {
234 Manager
*m
= userdata
;
238 return manager_send_request(m
);
241 static int manager_arm_timer(Manager
*m
, usec_t next
) {
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_boottime_or_monotonic()) + next
);
256 return sd_event_source_set_enabled(m
->event_timer
, SD_EVENT_ONESHOT
);
259 return sd_event_add_time(
262 clock_boottime_or_monotonic(),
263 now(clock_boottime_or_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_debug("System time changed. Resyncing.");
283 m
->poll_resync
= true;
285 return manager_send_request(m
);
288 /* wake up when the system time changes underneath us */
289 static int manager_clock_watch_setup(Manager
*m
) {
291 struct itimerspec its
= {
292 .it_value
.tv_sec
= TIME_T_MAX
299 m
->event_clock_watch
= sd_event_source_unref(m
->event_clock_watch
);
300 safe_close(m
->clock_watch_fd
);
302 m
->clock_watch_fd
= timerfd_create(CLOCK_REALTIME
, TFD_NONBLOCK
|TFD_CLOEXEC
);
303 if (m
->clock_watch_fd
< 0)
304 return log_error_errno(errno
, "Failed to create timerfd: %m");
306 if (timerfd_settime(m
->clock_watch_fd
, TFD_TIMER_ABSTIME
|TFD_TIMER_CANCEL_ON_SET
, &its
, NULL
) < 0)
307 return log_error_errno(errno
, "Failed to set up timerfd: %m");
309 r
= sd_event_add_io(m
->event
, &m
->event_clock_watch
, m
->clock_watch_fd
, EPOLLIN
, manager_clock_watch
, m
);
311 return log_error_errno(r
, "Failed to create clock watch event source: %m");
316 static int manager_adjust_clock(Manager
*m
, double offset
, int leap_sec
) {
317 struct timex tmx
= {};
323 * For small deltas, tell the kernel to gradually adjust the system
324 * clock to the NTP time, larger deltas are just directly set.
326 if (fabs(offset
) < NTP_MAX_ADJUST
) {
327 tmx
.modes
= ADJ_STATUS
| ADJ_NANO
| ADJ_OFFSET
| ADJ_TIMECONST
| ADJ_MAXERROR
| ADJ_ESTERROR
;
328 tmx
.status
= STA_PLL
;
329 tmx
.offset
= offset
* NSEC_PER_SEC
;
330 tmx
.constant
= log2i(m
->poll_interval_usec
/ USEC_PER_SEC
) - 4;
333 log_debug(" adjust (slew): %+.3f sec", offset
);
335 tmx
.modes
= ADJ_STATUS
| ADJ_NANO
| ADJ_SETOFFSET
;
337 /* ADJ_NANO uses nanoseconds in the microseconds field */
338 tmx
.time
.tv_sec
= (long)offset
;
339 tmx
.time
.tv_usec
= (offset
- tmx
.time
.tv_sec
) * NSEC_PER_SEC
;
341 /* the kernel expects -0.3s as {-1, 7000.000.000} */
342 if (tmx
.time
.tv_usec
< 0) {
343 tmx
.time
.tv_sec
-= 1;
344 tmx
.time
.tv_usec
+= NSEC_PER_SEC
;
348 log_debug(" adjust (jump): %+.3f sec", offset
);
352 * An unset STA_UNSYNC will enable the kernel's 11-minute mode,
353 * which syncs the system time periodically to the RTC.
355 * In case the RTC runs in local time, never touch the RTC,
356 * we have no way to properly handle daylight saving changes and
357 * mobile devices moving between time zones.
359 if (m
->rtc_local_time
)
360 tmx
.status
|= STA_UNSYNC
;
364 tmx
.status
|= STA_INS
;
367 tmx
.status
|= STA_DEL
;
371 r
= clock_adjtime(CLOCK_REALTIME
, &tmx
);
375 touch("/var/lib/systemd/clock");
377 m
->drift_ppm
= tmx
.freq
/ 65536;
379 log_debug(" status : %04i %s\n"
380 " time now : %li.%03llu\n"
382 " offset : %+.3f sec\n"
383 " freq offset : %+li (%i ppm)\n",
384 tmx
.status
, tmx
.status
& STA_UNSYNC
? "unsync" : "sync",
385 tmx
.time
.tv_sec
, (unsigned long long) (tmx
.time
.tv_usec
/ NSEC_PER_MSEC
),
387 (double)tmx
.offset
/ NSEC_PER_SEC
,
388 tmx
.freq
, m
->drift_ppm
);
393 static bool manager_sample_spike_detection(Manager
*m
, double offset
, double delay
) {
394 unsigned int i
, idx_cur
, idx_new
, idx_min
;
402 /* ignore initial sample */
403 if (m
->packet_count
== 1)
406 /* store the current data in our samples array */
407 idx_cur
= m
->samples_idx
;
408 idx_new
= (idx_cur
+ 1) % ELEMENTSOF(m
->samples
);
409 m
->samples_idx
= idx_new
;
410 m
->samples
[idx_new
].offset
= offset
;
411 m
->samples
[idx_new
].delay
= delay
;
413 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
414 jitter
= m
->samples_jitter
;
415 for (idx_min
= idx_cur
, i
= 0; i
< ELEMENTSOF(m
->samples
); i
++)
416 if (m
->samples
[i
].delay
> 0 && m
->samples
[i
].delay
< m
->samples
[idx_min
].delay
)
420 for (i
= 0; i
< ELEMENTSOF(m
->samples
); i
++)
421 j
+= pow(m
->samples
[i
].offset
- m
->samples
[idx_min
].offset
, 2);
422 m
->samples_jitter
= sqrt(j
/ (ELEMENTSOF(m
->samples
) - 1));
424 /* ignore samples when resyncing */
428 /* always accept offset if we are farther off than the round-trip delay */
429 if (fabs(offset
) > delay
)
432 /* we need a few samples before looking at them */
433 if (m
->packet_count
< 4)
436 /* do not accept anything worse than the maximum possible error of the best sample */
437 if (fabs(offset
) > m
->samples
[idx_min
].delay
)
440 /* compare the difference between the current offset to the previous offset and jitter */
441 return fabs(offset
- m
->samples
[idx_cur
].offset
) > 3 * jitter
;
444 static void manager_adjust_poll(Manager
*m
, double offset
, bool spike
) {
447 if (m
->poll_resync
) {
448 m
->poll_interval_usec
= NTP_POLL_INTERVAL_MIN_SEC
* USEC_PER_SEC
;
449 m
->poll_resync
= false;
453 /* set to minimal poll interval */
454 if (!spike
&& fabs(offset
) > NTP_ACCURACY_SEC
) {
455 m
->poll_interval_usec
= NTP_POLL_INTERVAL_MIN_SEC
* USEC_PER_SEC
;
459 /* increase polling interval */
460 if (fabs(offset
) < NTP_ACCURACY_SEC
* 0.25) {
461 if (m
->poll_interval_usec
< NTP_POLL_INTERVAL_MAX_SEC
* USEC_PER_SEC
)
462 m
->poll_interval_usec
*= 2;
466 /* decrease polling interval */
467 if (spike
|| fabs(offset
) > NTP_ACCURACY_SEC
* 0.75) {
468 if (m
->poll_interval_usec
> NTP_POLL_INTERVAL_MIN_SEC
* USEC_PER_SEC
)
469 m
->poll_interval_usec
/= 2;
474 static int manager_receive_response(sd_event_source
*source
, int fd
, uint32_t revents
, void *userdata
) {
475 Manager
*m
= userdata
;
476 struct ntp_msg ntpmsg
;
480 .iov_len
= sizeof(ntpmsg
),
483 struct cmsghdr cmsghdr
;
484 uint8_t buf
[CMSG_SPACE(sizeof(struct timeval
))];
486 union sockaddr_union server_addr
;
487 struct msghdr msghdr
= {
490 .msg_control
= &control
,
491 .msg_controllen
= sizeof(control
),
492 .msg_name
= &server_addr
,
493 .msg_namelen
= sizeof(server_addr
),
495 struct cmsghdr
*cmsg
;
496 struct timespec
*recv_time
;
498 double origin
, receive
, trans
, dest
;
499 double delay
, offset
;
500 double root_distance
;
508 if (revents
& (EPOLLHUP
|EPOLLERR
)) {
509 log_warning("Server connection returned error.");
510 return manager_connect(m
);
513 len
= recvmsg(fd
, &msghdr
, MSG_DONTWAIT
);
518 log_warning("Error receiving message. Disconnecting.");
519 return manager_connect(m
);
522 /* Too short or too long packet? */
523 if (iov
.iov_len
< sizeof(struct ntp_msg
) || (msghdr
.msg_flags
& MSG_TRUNC
)) {
524 log_warning("Invalid response from server. Disconnecting.");
525 return manager_connect(m
);
528 if (!m
->current_server_name
||
529 !m
->current_server_address
||
530 !sockaddr_equal(&server_addr
, &m
->current_server_address
->sockaddr
)) {
531 log_debug("Response from unknown server.");
536 CMSG_FOREACH(cmsg
, &msghdr
) {
537 if (cmsg
->cmsg_level
!= SOL_SOCKET
)
540 switch (cmsg
->cmsg_type
) {
541 case SCM_TIMESTAMPNS
:
542 recv_time
= (struct timespec
*) CMSG_DATA(cmsg
);
547 log_error("Invalid packet timestamp.");
552 log_debug("Unexpected reply. Ignoring.");
556 m
->missed_replies
= 0;
558 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
559 if (be32toh(ntpmsg
.origin_time
.sec
) != m
->trans_time
.tv_sec
+ OFFSET_1900_1970
||
560 be32toh(ntpmsg
.origin_time
.frac
) != m
->trans_time
.tv_nsec
) {
561 log_debug("Invalid reply; not our transmit time. Ignoring.");
565 m
->event_timeout
= sd_event_source_unref(m
->event_timeout
);
567 if (be32toh(ntpmsg
.recv_time
.sec
) < TIME_EPOCH
+ OFFSET_1900_1970
||
568 be32toh(ntpmsg
.trans_time
.sec
) < TIME_EPOCH
+ OFFSET_1900_1970
) {
569 log_debug("Invalid reply, returned times before epoch. Ignoring.");
570 return manager_connect(m
);
573 if (NTP_FIELD_LEAP(ntpmsg
.field
) == NTP_LEAP_NOTINSYNC
||
574 ntpmsg
.stratum
== 0 || ntpmsg
.stratum
>= 16) {
575 log_debug("Server is not synchronized. Disconnecting.");
576 return manager_connect(m
);
579 if (!IN_SET(NTP_FIELD_VERSION(ntpmsg
.field
), 3, 4)) {
580 log_debug("Response NTPv%d. Disconnecting.", NTP_FIELD_VERSION(ntpmsg
.field
));
581 return manager_connect(m
);
584 if (NTP_FIELD_MODE(ntpmsg
.field
) != NTP_MODE_SERVER
) {
585 log_debug("Unsupported mode %d. Disconnecting.", NTP_FIELD_MODE(ntpmsg
.field
));
586 return manager_connect(m
);
589 root_distance
= ntp_ts_short_to_d(&ntpmsg
.root_delay
) / 2 + ntp_ts_short_to_d(&ntpmsg
.root_dispersion
);
590 if (root_distance
> NTP_MAX_ROOT_DISTANCE
) {
591 log_debug("Server has too large root distance. Disconnecting.");
592 return manager_connect(m
);
597 m
->retry_interval
= 0;
600 manager_listen_stop(m
);
602 /* announce leap seconds */
603 if (NTP_FIELD_LEAP(ntpmsg
.field
) & NTP_LEAP_PLUSSEC
)
605 else if (NTP_FIELD_LEAP(ntpmsg
.field
) & NTP_LEAP_MINUSSEC
)
611 * "Timestamp Name ID When Generated
612 * ------------------------------------------------------------
613 * Originate Timestamp T1 time request sent by client
614 * Receive Timestamp T2 time request received by server
615 * Transmit Timestamp T3 time reply sent by server
616 * Destination Timestamp T4 time reply received by client
618 * The round-trip delay, d, and system clock offset, t, are defined as:
619 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
621 origin
= ts_to_d(&m
->trans_time
) + OFFSET_1900_1970
;
622 receive
= ntp_ts_to_d(&ntpmsg
.recv_time
);
623 trans
= ntp_ts_to_d(&ntpmsg
.trans_time
);
624 dest
= ts_to_d(recv_time
) + OFFSET_1900_1970
;
626 offset
= ((receive
- origin
) + (trans
- dest
)) / 2;
627 delay
= (dest
- origin
) - (trans
- receive
);
629 spike
= manager_sample_spike_detection(m
, offset
, delay
);
631 manager_adjust_poll(m
, offset
, spike
);
633 log_debug("NTP response:\n"
638 " precision : %.6f sec (%d)\n"
639 " root distance: %.6f sec\n"
640 " reference : %.4s\n"
645 " offset : %+.3f sec\n"
646 " delay : %+.3f sec\n"
647 " packet count : %"PRIu64
"\n"
649 " poll interval: " USEC_FMT
"\n",
650 NTP_FIELD_LEAP(ntpmsg
.field
),
651 NTP_FIELD_VERSION(ntpmsg
.field
),
652 NTP_FIELD_MODE(ntpmsg
.field
),
654 exp2(ntpmsg
.precision
), ntpmsg
.precision
,
656 ntpmsg
.stratum
== 1 ? ntpmsg
.refid
: "n/a",
657 origin
- OFFSET_1900_1970
,
658 receive
- OFFSET_1900_1970
,
659 trans
- OFFSET_1900_1970
,
660 dest
- OFFSET_1900_1970
,
663 m
->samples_jitter
, spike
? " spike" : "",
664 m
->poll_interval_usec
/ USEC_PER_SEC
);
668 r
= manager_adjust_clock(m
, offset
, leap_sec
);
670 log_error_errno(r
, "Failed to call clock_adjtime(): %m");
673 log_debug("interval/delta/delay/jitter/drift " USEC_FMT
"s/%+.3fs/%.3fs/%.3fs/%+ippm%s",
674 m
->poll_interval_usec
/ USEC_PER_SEC
, offset
, delay
, m
->samples_jitter
, m
->drift_ppm
,
675 spike
? " (ignored)" : "");
678 _cleanup_free_
char *pretty
= NULL
;
682 server_address_pretty(m
->current_server_address
, &pretty
);
683 log_info("Synchronized to time server %s (%s).", strna(pretty
), m
->current_server_name
->string
);
684 sd_notifyf(false, "STATUS=Synchronized to time server %s (%s).", strna(pretty
), m
->current_server_name
->string
);
687 r
= manager_arm_timer(m
, m
->poll_interval_usec
);
689 return log_error_errno(r
, "Failed to rearm timer: %m");
694 static int manager_listen_setup(Manager
*m
) {
695 union sockaddr_union addr
= {};
696 static const int tos
= IPTOS_LOWDELAY
;
697 static const int on
= 1;
702 if (m
->server_socket
>= 0)
705 assert(!m
->event_receive
);
706 assert(m
->current_server_address
);
708 addr
.sa
.sa_family
= m
->current_server_address
->sockaddr
.sa
.sa_family
;
710 m
->server_socket
= socket(addr
.sa
.sa_family
, SOCK_DGRAM
| SOCK_CLOEXEC
, 0);
711 if (m
->server_socket
< 0)
714 r
= bind(m
->server_socket
, &addr
.sa
, m
->current_server_address
->socklen
);
718 r
= setsockopt(m
->server_socket
, SOL_SOCKET
, SO_TIMESTAMPNS
, &on
, sizeof(on
));
722 (void) setsockopt(m
->server_socket
, IPPROTO_IP
, IP_TOS
, &tos
, sizeof(tos
));
724 return sd_event_add_io(m
->event
, &m
->event_receive
, m
->server_socket
, EPOLLIN
, manager_receive_response
, m
);
727 static void manager_listen_stop(Manager
*m
) {
730 m
->event_receive
= sd_event_source_unref(m
->event_receive
);
731 m
->server_socket
= safe_close(m
->server_socket
);
734 static int manager_begin(Manager
*m
) {
735 _cleanup_free_
char *pretty
= NULL
;
739 assert_return(m
->current_server_name
, -EHOSTUNREACH
);
740 assert_return(m
->current_server_address
, -EHOSTUNREACH
);
743 m
->missed_replies
= NTP_MAX_MISSED_REPLIES
;
744 if (m
->poll_interval_usec
== 0)
745 m
->poll_interval_usec
= NTP_POLL_INTERVAL_MIN_SEC
* USEC_PER_SEC
;
747 server_address_pretty(m
->current_server_address
, &pretty
);
748 log_debug("Connecting to time server %s (%s).", strna(pretty
), m
->current_server_name
->string
);
749 sd_notifyf(false, "STATUS=Connecting to time server %s (%s).", strna(pretty
), m
->current_server_name
->string
);
751 r
= manager_clock_watch_setup(m
);
755 return manager_send_request(m
);
758 void manager_set_server_name(Manager
*m
, ServerName
*n
) {
761 if (m
->current_server_name
== n
)
764 m
->current_server_name
= n
;
765 m
->current_server_address
= NULL
;
767 manager_disconnect(m
);
770 log_debug("Selected server %s.", n
->string
);
773 void manager_set_server_address(Manager
*m
, ServerAddress
*a
) {
776 if (m
->current_server_address
== a
)
779 m
->current_server_address
= a
;
780 /* If a is NULL, we are just clearing the address, without
781 * changing the name. Keep the existing name in that case. */
783 m
->current_server_name
= a
->name
;
785 manager_disconnect(m
);
788 _cleanup_free_
char *pretty
= NULL
;
789 server_address_pretty(a
, &pretty
);
790 log_debug("Selected address %s of server %s.", strna(pretty
), a
->name
->string
);
794 static int manager_resolve_handler(sd_resolve_query
*q
, int ret
, const struct addrinfo
*ai
, void *userdata
) {
795 Manager
*m
= userdata
;
800 assert(m
->current_server_name
);
802 m
->resolve_query
= sd_resolve_query_unref(m
->resolve_query
);
805 log_debug("Failed to resolve %s: %s", m
->current_server_name
->string
, gai_strerror(ret
));
808 return manager_connect(m
);
811 for (; ai
; ai
= ai
->ai_next
) {
812 _cleanup_free_
char *pretty
= NULL
;
816 assert(ai
->ai_addrlen
>= offsetof(struct sockaddr
, sa_data
));
818 if (!IN_SET(ai
->ai_addr
->sa_family
, AF_INET
, AF_INET6
)) {
819 log_warning("Unsuitable address protocol for %s", m
->current_server_name
->string
);
823 r
= server_address_new(m
->current_server_name
, &a
, (const union sockaddr_union
*) ai
->ai_addr
, ai
->ai_addrlen
);
825 return log_error_errno(r
, "Failed to add server address: %m");
827 server_address_pretty(a
, &pretty
);
828 log_debug("Resolved address %s for %s.", pretty
, m
->current_server_name
->string
);
831 if (!m
->current_server_name
->addresses
) {
832 log_error("Failed to find suitable address for host %s.", m
->current_server_name
->string
);
835 return manager_connect(m
);
838 manager_set_server_address(m
, m
->current_server_name
->addresses
);
840 return manager_begin(m
);
843 static int manager_retry_connect(sd_event_source
*source
, usec_t usec
, void *userdata
) {
844 Manager
*m
= userdata
;
848 return manager_connect(m
);
851 int manager_connect(Manager
*m
) {
856 manager_disconnect(m
);
858 m
->event_retry
= sd_event_source_unref(m
->event_retry
);
859 if (!ratelimit_test(&m
->ratelimit
)) {
860 log_debug("Slowing down attempts to contact servers.");
862 r
= sd_event_add_time(m
->event
, &m
->event_retry
, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + RETRY_USEC
, 0, manager_retry_connect
, m
);
864 return log_error_errno(r
, "Failed to create retry timer: %m");
869 /* If we already are operating on some address, switch to the
871 if (m
->current_server_address
&& m
->current_server_address
->addresses_next
)
872 manager_set_server_address(m
, m
->current_server_address
->addresses_next
);
874 struct addrinfo hints
= {
875 .ai_flags
= AI_NUMERICSERV
|AI_ADDRCONFIG
,
876 .ai_socktype
= SOCK_DGRAM
,
879 /* Hmm, we are through all addresses, let's look for the next host instead */
880 if (m
->current_server_name
&& m
->current_server_name
->names_next
)
881 manager_set_server_name(m
, m
->current_server_name
->names_next
);
886 /* Our current server name list is exhausted,
887 * let's find the next one to iterate. First
888 * we try the system list, then the link list.
889 * After having processed the link list we
890 * jump back to the system list. However, if
891 * both lists are empty, we change to the
893 if (!m
->current_server_name
|| m
->current_server_name
->type
== SERVER_LINK
) {
894 f
= m
->system_servers
;
900 f
= m
->system_servers
;
906 f
= m
->fallback_servers
;
909 manager_set_server_name(m
, NULL
);
910 log_debug("No server found.");
914 if (restart
&& !m
->exhausted_servers
&& m
->poll_interval_usec
) {
915 log_debug("Waiting after exhausting servers.");
916 r
= sd_event_add_time(m
->event
, &m
->event_retry
, clock_boottime_or_monotonic(), now(clock_boottime_or_monotonic()) + m
->poll_interval_usec
, 0, manager_retry_connect
, m
);
918 return log_error_errno(r
, "Failed to create retry timer: %m");
920 m
->exhausted_servers
= true;
922 /* Increase the polling interval */
923 if (m
->poll_interval_usec
< NTP_POLL_INTERVAL_MAX_SEC
* USEC_PER_SEC
)
924 m
->poll_interval_usec
*= 2;
929 m
->exhausted_servers
= false;
931 manager_set_server_name(m
, f
);
934 /* Tell the resolver to reread /etc/resolv.conf, in
935 * case it changed. */
938 /* Flush out any previously resolved addresses */
939 server_name_flush_addresses(m
->current_server_name
);
941 log_debug("Resolving %s...", m
->current_server_name
->string
);
943 r
= sd_resolve_getaddrinfo(m
->resolve
, &m
->resolve_query
, m
->current_server_name
->string
, "123", &hints
, manager_resolve_handler
, m
);
945 return log_error_errno(r
, "Failed to create resolver: %m");
950 r
= manager_begin(m
);
957 void manager_disconnect(Manager
*m
) {
960 m
->resolve_query
= sd_resolve_query_unref(m
->resolve_query
);
962 m
->event_timer
= sd_event_source_unref(m
->event_timer
);
964 manager_listen_stop(m
);
966 m
->event_clock_watch
= sd_event_source_unref(m
->event_clock_watch
);
967 m
->clock_watch_fd
= safe_close(m
->clock_watch_fd
);
969 m
->event_timeout
= sd_event_source_unref(m
->event_timeout
);
971 sd_notifyf(false, "STATUS=Idle.");
974 void manager_flush_server_names(Manager
*m
, ServerType t
) {
977 if (t
== SERVER_SYSTEM
)
978 while (m
->system_servers
)
979 server_name_free(m
->system_servers
);
981 if (t
== SERVER_LINK
)
982 while (m
->link_servers
)
983 server_name_free(m
->link_servers
);
985 if (t
== SERVER_FALLBACK
)
986 while (m
->fallback_servers
)
987 server_name_free(m
->fallback_servers
);
990 void manager_free(Manager
*m
) {
994 manager_disconnect(m
);
995 manager_flush_server_names(m
, SERVER_SYSTEM
);
996 manager_flush_server_names(m
, SERVER_LINK
);
997 manager_flush_server_names(m
, SERVER_FALLBACK
);
999 sd_event_source_unref(m
->event_retry
);
1001 sd_event_source_unref(m
->network_event_source
);
1002 sd_network_monitor_unref(m
->network_monitor
);
1004 sd_resolve_unref(m
->resolve
);
1005 sd_event_unref(m
->event
);
1010 static int manager_network_read_link_servers(Manager
*m
) {
1011 _cleanup_strv_free_
char **ntp
= NULL
;
1018 r
= sd_network_get_ntp(&ntp
);
1022 LIST_FOREACH(names
, n
, m
->link_servers
)
1025 STRV_FOREACH(i
, ntp
) {
1028 LIST_FOREACH(names
, n
, m
->link_servers
)
1029 if (streq(n
->string
, *i
)) {
1036 r
= server_name_new(m
, NULL
, SERVER_LINK
, *i
);
1042 LIST_FOREACH_SAFE(names
, n
, nx
, m
->link_servers
)
1044 server_name_free(n
);
1049 manager_flush_server_names(m
, SERVER_LINK
);
1053 static int manager_network_event_handler(sd_event_source
*s
, int fd
, uint32_t revents
, void *userdata
) {
1054 Manager
*m
= userdata
;
1055 bool connected
, online
;
1060 sd_network_monitor_flush(m
->network_monitor
);
1062 manager_network_read_link_servers(m
);
1064 /* check if the machine is online */
1065 online
= network_is_online();
1067 /* check if the client is currently connected */
1068 connected
= m
->server_socket
>= 0 || m
->resolve_query
|| m
->exhausted_servers
;
1070 if (connected
&& !online
) {
1071 log_info("No network connectivity, watching for changes.");
1072 manager_disconnect(m
);
1074 } else if (!connected
&& online
) {
1075 log_info("Network configuration changed, trying to establish connection.");
1077 if (m
->current_server_address
)
1078 r
= manager_begin(m
);
1080 r
= manager_connect(m
);
1088 static int manager_network_monitor_listen(Manager
*m
) {
1093 r
= sd_network_monitor_new(&m
->network_monitor
, NULL
);
1097 fd
= sd_network_monitor_get_fd(m
->network_monitor
);
1101 events
= sd_network_monitor_get_events(m
->network_monitor
);
1105 r
= sd_event_add_io(m
->event
, &m
->network_event_source
, fd
, events
, manager_network_event_handler
, m
);
1112 int manager_new(Manager
**ret
) {
1113 _cleanup_(manager_freep
) Manager
*m
= NULL
;
1118 m
= new0(Manager
, 1);
1122 m
->server_socket
= m
->clock_watch_fd
= -1;
1124 RATELIMIT_INIT(m
->ratelimit
, RATELIMIT_INTERVAL_USEC
, RATELIMIT_BURST
);
1126 r
= manager_parse_server_string(m
, SERVER_FALLBACK
, NTP_SERVERS
);
1130 r
= sd_event_default(&m
->event
);
1134 sd_event_add_signal(m
->event
, NULL
, SIGTERM
, NULL
, NULL
);
1135 sd_event_add_signal(m
->event
, NULL
, SIGINT
, NULL
, NULL
);
1137 sd_event_set_watchdog(m
->event
, true);
1139 r
= sd_resolve_default(&m
->resolve
);
1143 r
= sd_resolve_attach_event(m
->resolve
, m
->event
, 0);
1147 r
= manager_network_monitor_listen(m
);
1151 manager_network_read_link_servers(m
);