1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
4 This file is part of systemd.
6 Copyright 2014 Kay Sievers
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/>.
23 * "Simple Network Time Protocol Version 4 (SNTPv4) is a subset of the
24 * Network Time Protocol (NTP) used to synchronize computer clocks in
25 * the Internet. SNTPv4 can be used when the ultimate performance of
26 * a full NTP implementation based on RFC 1305 is neither needed nor
29 * "Unlike most NTP clients, SNTP clients normally operate with only a
30 * single server at a time."
32 * http://tools.ietf.org/html/rfc4330
42 #include <arpa/inet.h>
43 #include <netinet/in.h>
44 #include <netinet/ip.h>
45 #include <sys/timex.h>
46 #include <sys/socket.h>
49 #include "sparse-endian.h"
52 #include "timedate-sntp.h"
55 #define ADJ_SETOFFSET 0x0100 /* add 'time' to current time */
58 /* Maximum delta in seconds which the system clock is gradually adjusted
59 * to approach the network time. Deltas larger that this are set by letting
60 * the system time jump. The maximum for adjtime is 500ms.
62 #define NTP_MAX_ADJUST 0.2
65 * "Define the required accuracy of the system clock, then calculate the
66 * maximum timeout. Use the longest maximum timeout possible given the system
67 * constraints to minimize time server aggregate load."
69 * "A client MUST NOT under any conditions use a poll interval less
72 #define NTP_POLL_INTERVAL_MIN_SEC 16
73 #define NTP_POLL_INTERVAL_MAX_SEC 2048
74 #define NTP_ACCURACY_SEC 0.1
76 #define NTP_LEAP_PLUSSEC 1
77 #define NTP_LEAP_MINUSSEC 2
78 #define NTP_LEAP_NOTINSYNC 3
79 #define NTP_MODE_CLIENT 3
80 #define NTP_MODE_SERVER 4
81 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3)
82 #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7)
83 #define NTP_FIELD_MODE(f) ((f) & 7)
84 #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m))
87 * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
88 * in seconds relative to 0h on 1 January 1900."
90 #define OFFSET_1900_1970 2208988800UL
107 struct ntp_ts_short root_delay;
108 struct ntp_ts_short root_dispersion;
110 struct ntp_ts reference_time;
111 struct ntp_ts origin_time;
112 struct ntp_ts recv_time;
113 struct ntp_ts trans_time;
117 sd_event_source *event_receive;
118 sd_event_source *event_timer;
121 struct sockaddr_in server_addr;
123 uint64_t packet_count;
125 struct timespec trans_time_mon;
126 struct timespec trans_time;
129 usec_t poll_interval;
135 unsigned int samples_idx;
136 double samples_jitter;
139 static int sntp_arm_timer(SNTPContext *sntp);
141 static double ntp_ts_to_d(const struct ntp_ts *ts) {
142 return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
145 static double tv_to_d(const struct timeval *tv) {
146 return tv->tv_sec + (1.0e-6 * tv->tv_usec);
149 static double ts_to_d(const struct timespec *ts) {
150 return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
153 static void d_to_tv(double d, struct timeval *tv) {
154 tv->tv_sec = (long)d;
155 tv->tv_usec = (d - tv->tv_sec) * 1000 * 1000;
157 /* the kernel expects -0.3s as {-1, 7000.000} */
158 if (tv->tv_usec < 0) {
160 tv->tv_usec += 1000 * 1000;
164 static double square(double d) {
168 static int sntp_send_request(SNTPContext *sntp) {
169 struct ntp_msg ntpmsg = {};
170 struct sockaddr_in addr = {};
175 * "The client initializes the NTP message header, sends the request
176 * to the server, and strips the time of day from the Transmit
177 * Timestamp field of the reply. For this purpose, all the NTP
178 * header fields are set to 0, except the Mode, VN, and optional
179 * Transmit Timestamp fields."
181 ntpmsg.field = NTP_FIELD(0, 4, NTP_MODE_CLIENT);
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 clock_gettime(CLOCK_MONOTONIC, &sntp->trans_time_mon);
192 clock_gettime(CLOCK_REALTIME, &sntp->trans_time);
193 ntpmsg.trans_time.sec = htobe32(sntp->trans_time.tv_sec + OFFSET_1900_1970);
194 ntpmsg.trans_time.frac = htobe32(sntp->trans_time.tv_nsec);
196 addr.sin_family = AF_INET;
197 addr.sin_port = htobe16(123);
198 addr.sin_addr.s_addr = inet_addr(sntp->server);
199 len = sendto(sntp->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &addr, sizeof(addr));
201 log_debug("Sending NTP request to %s failed: %m", sntp->server);
205 sntp->pending = true;
207 /* re-arm timer for next poll interval, in case the packet never arrives back */
208 r = sntp_arm_timer(sntp);
212 log_debug("Sent NTP request to: %s", sntp->server);
216 static int sntp_timer(sd_event_source *source, usec_t usec, void *userdata) {
217 SNTPContext *sntp = userdata;
221 sntp_send_request(sntp);
225 static int sntp_arm_timer(SNTPContext *sntp) {
230 assert(sntp->event_receive);
232 if (sntp->poll_interval <= 0) {
233 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
237 if (sntp->event_timer) {
238 r = sd_event_source_set_time(sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval);
242 return sd_event_source_set_enabled(sntp->event_timer, SD_EVENT_ONESHOT);
245 e = sd_event_source_get_event(sntp->event_receive);
246 r = sd_event_add_monotonic(e, &sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval, 0, sntp_timer, sntp);
253 static int sntp_adjust_clock(SNTPContext *sntp, double offset, int leap_sec) {
254 struct timex tmx = {};
258 * For small deltas, tell the kernel to gradually adjust the system
259 * clock to the NTP time, larger deltas are just directly set.
261 * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
262 * syncs the system time periodically to the hardware clock.
264 if (offset < NTP_MAX_ADJUST && offset > -NTP_MAX_ADJUST) {
267 constant = log2i(sntp->poll_interval / USEC_PER_SEC) - 5;
269 tmx.modes |= ADJ_STATUS | ADJ_OFFSET | ADJ_TIMECONST;
270 tmx.status = STA_PLL;
271 tmx.offset = offset * 1000 * 1000;
272 tmx.constant = constant;
274 log_debug(" adjust (slew): %+f sec\n", (double)tmx.offset / USEC_PER_SEC);
276 tmx.modes = ADJ_SETOFFSET;
277 d_to_tv(offset, &tmx.time);
278 log_debug(" adjust (jump): %+f sec\n", tv_to_d(&tmx.time));
283 tmx.status |= STA_INS;
286 tmx.status |= STA_DEL;
290 r = clock_adjtime(CLOCK_REALTIME, &tmx);
294 log_debug(" status : %04i %s\n"
295 " time now : %li.%06li\n"
297 " offset : %+f sec\n"
298 " freq offset : %+li (%+.3f ppm)\n",
299 tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
300 tmx.time.tv_sec, tmx.time.tv_usec,
302 (double)tmx.offset / USEC_PER_SEC,
303 tmx.freq, (double)tmx.freq / 65536);
308 static bool sntp_sample_spike_detection(SNTPContext *sntp, double offset, double delay) {
309 unsigned int i, idx_cur, idx_new, idx_min;
313 /* store the current data in our samples array */
314 idx_cur = sntp->samples_idx;
315 idx_new = (idx_cur + 1) % ELEMENTSOF(sntp->samples);
316 sntp->samples_idx = idx_new;
317 sntp->samples[idx_new].offset = offset;
318 sntp->samples[idx_new].delay = delay;
320 sntp->packet_count++;
323 * Spike detection; compare the difference between the
324 * current offset to the previous offset and jitter.
326 spike = sntp->packet_count > 2 && fabs(offset - sntp->samples[idx_cur].offset) > sntp->samples_jitter * 3;
328 /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
329 for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(sntp->samples); i++)
330 if (sntp->samples[i].delay > 0 && sntp->samples[i].delay < sntp->samples[idx_min].delay)
333 for (jitter = 0, i = 0; i < ELEMENTSOF(sntp->samples); i++)
334 jitter += square(sntp->samples[i].offset - sntp->samples[idx_min].offset);
335 sntp->samples_jitter = sqrt(jitter / (ELEMENTSOF(sntp->samples) - 1));
340 static void sntp_adjust_poll(SNTPContext *sntp, double offset, bool spike) {
344 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
345 sntp->poll_interval /= 2;
349 delta = fabs(offset);
351 /* set to minimal poll interval */
352 if (delta > NTP_ACCURACY_SEC) {
353 sntp->poll_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
357 /* increase polling interval */
358 if (delta < NTP_ACCURACY_SEC * 0.25) {
359 if (sntp->poll_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
360 sntp->poll_interval *= 2;
364 /* decrease polling interval */
365 if (delta > NTP_ACCURACY_SEC * 0.75) {
366 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
367 sntp->poll_interval /= 2;
372 static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
373 SNTPContext *sntp = userdata;
374 unsigned char buf[sizeof(struct ntp_msg)];
377 .iov_len = sizeof(buf),
380 struct cmsghdr cmsghdr;
381 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
383 struct sockaddr_in server_addr;
384 struct msghdr msghdr = {
387 .msg_control = &control,
388 .msg_controllen = sizeof(control),
389 .msg_name = &server_addr,
390 .msg_namelen = sizeof(server_addr),
392 struct cmsghdr *cmsg;
394 struct timeval *recv_time;
396 struct ntp_msg *ntpmsg;
397 double origin, receive, trans, dest;
398 double delay, offset;
403 if (revents & (EPOLLHUP|EPOLLERR)) {
404 log_debug("Server connection returned error, closing.");
405 sntp_server_disconnect(sntp);
409 len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
411 log_debug("Error receiving message, disconnecting");
415 if (iov.iov_len < sizeof(struct ntp_msg)) {
416 log_debug("Invalid response from server, disconnecting");
420 if (sntp->server_addr.sin_addr.s_addr != server_addr.sin_addr.s_addr) {
421 log_debug("Response from unknown server, disconnecting");
426 for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
427 if (cmsg->cmsg_level != SOL_SOCKET)
430 switch (cmsg->cmsg_type) {
432 recv_time = (struct timeval *) CMSG_DATA(cmsg);
437 log_debug("Invalid packet timestamp, disconnecting");
441 ntpmsg = iov.iov_base;
442 if (!sntp->pending) {
443 log_debug("Unexpected reply, ignoring");
446 sntp->pending = false;
448 /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
449 if (be32toh(ntpmsg->origin_time.sec) != sntp->trans_time.tv_sec + OFFSET_1900_1970||
450 be32toh(ntpmsg->origin_time.frac) != sntp->trans_time.tv_nsec) {
451 log_debug("Invalid reply, not our transmit time, ignoring");
455 if (NTP_FIELD_LEAP(ntpmsg->field) == NTP_LEAP_NOTINSYNC) {
456 log_debug("Server is not synchronized, disconnecting");
460 if (NTP_FIELD_VERSION(ntpmsg->field) != 4) {
461 log_debug("Response NTPv%d, disconnecting", NTP_FIELD_VERSION(ntpmsg->field));
465 if (NTP_FIELD_MODE(ntpmsg->field) != NTP_MODE_SERVER) {
466 log_debug("Unsupported mode %d, disconnecting", NTP_FIELD_MODE(ntpmsg->field));
470 /* announce leap seconds */
471 if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_PLUSSEC)
473 else if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_MINUSSEC)
479 * "Timestamp Name ID When Generated
480 * ------------------------------------------------------------
481 * Originate Timestamp T1 time request sent by client
482 * Receive Timestamp T2 time request received by server
483 * Transmit Timestamp T3 time reply sent by server
484 * Destination Timestamp T4 time reply received by client
486 * The roundtrip delay d and system clock offset t are defined as:
487 * d = (T4 - T1) - (T3 - T2) t = ((T2 - T1) + (T3 - T4)) / 2"
489 clock_gettime(CLOCK_MONOTONIC, &now);
490 origin = tv_to_d(recv_time) - (ts_to_d(&now) - ts_to_d(&sntp->trans_time_mon)) + OFFSET_1900_1970;
491 receive = ntp_ts_to_d(&ntpmsg->recv_time);
492 trans = ntp_ts_to_d(&ntpmsg->trans_time);
493 dest = tv_to_d(recv_time) + OFFSET_1900_1970;
495 offset = ((receive - origin) + (trans - dest)) / 2;
496 delay = (dest - origin) - (trans - receive);
498 spike = sntp_sample_spike_detection(sntp, offset, delay);
500 sntp_adjust_poll(sntp, offset, spike);
502 log_debug("NTP response:\n"
507 " precision : %f sec (%d)\n"
508 " reference : %.4s\n"
513 " offset : %+f sec\n"
515 " packet count : %"PRIu64"\n"
516 " jitter/spike : %f (%s)\n"
517 " poll interval: %llu\n",
518 NTP_FIELD_LEAP(ntpmsg->field),
519 NTP_FIELD_VERSION(ntpmsg->field),
520 NTP_FIELD_MODE(ntpmsg->field),
522 exp2(ntpmsg->precision), ntpmsg->precision,
523 ntpmsg->stratum == 1 ? ntpmsg->refid : "n/a",
524 origin - OFFSET_1900_1970,
525 receive - OFFSET_1900_1970,
526 trans - OFFSET_1900_1970,
527 dest - OFFSET_1900_1970,
530 sntp->samples_jitter, spike ? "yes" : "no",
531 sntp->poll_interval / USEC_PER_SEC);
533 log_info("%4llu %+10f %10f %10f %s",
534 sntp->poll_interval / USEC_PER_SEC, offset, delay, sntp->samples_jitter, spike ? "spike" : "");
537 r = sntp_adjust_clock(sntp, offset, leap_sec);
539 log_error("Failed to call clock_adjtime(): %m");
542 r = sntp_arm_timer(sntp);
549 int sntp_server_connect(SNTPContext *sntp, const char *server) {
550 _cleanup_free_ char *s = NULL;
554 assert(sntp->server_socket >= 0);
564 zero(sntp->server_addr);
565 sntp->server_addr.sin_family = AF_INET;
566 sntp->server_addr.sin_addr.s_addr = inet_addr(server);
568 sntp->poll_interval = 2 * NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
570 return sntp_send_request(sntp);
573 void sntp_server_disconnect(SNTPContext *sntp) {
577 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
578 sntp->event_receive = sd_event_source_unref(sntp->event_receive);
579 if (sntp->server_socket > 0)
580 close(sntp->server_socket);
581 sntp->server_socket = -1;
582 zero(sntp->server_addr);
587 int sntp_new(SNTPContext **sntp, sd_event *e) {
588 _cleanup_free_ SNTPContext *c;
589 _cleanup_close_ int fd = -1;
590 struct sockaddr_in addr;
592 const int tos = IPTOS_LOWDELAY;
595 c = new0(SNTPContext, 1);
599 fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
604 addr.sin_family = AF_INET;
605 r = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
609 r = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
613 r = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
617 r = sd_event_add_io(e, &c->event_receive, fd, EPOLLIN, sntp_receive_response, c);
621 c->server_socket = fd;
630 SNTPContext *sntp_unref(SNTPContext *sntp) {
631 sntp_server_disconnect(sntp);