chiark / gitweb /
608177f662ad1f75d841d8ab7632fe2940c536d2
[elogind.git] / src / timedate / timedate-sntp.c
1 /*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3 /***
4   This file is part of systemd.
5
6   Copyright 2014 Kay Sievers
7
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.
12
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.
17
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/>.
20 ***/
21
22 /*
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
27  * justified."
28  *
29  * "Unlike most NTP clients, SNTP clients normally operate with only a
30  * single server at a time."
31  *
32  * http://tools.ietf.org/html/rfc4330
33  */
34
35 #include <stdlib.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <unistd.h>
39 #include <string.h>
40 #include <time.h>
41 #include <math.h>
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>
47
48 #include "util.h"
49 #include "sparse-endian.h"
50 #include "log.h"
51 #include "sd-event.h"
52 #include "timedate-sntp.h"
53
54 #ifndef ADJ_SETOFFSET
55 #define ADJ_SETOFFSET                   0x0100  /* add 'time' to current time */
56 #endif
57
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.
61  */
62 #define NTP_MAX_ADJUST                  0.2
63
64 /*
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."
68  *
69  * "A client MUST NOT under any conditions use a poll interval less
70  * than 15 seconds."
71  */
72 #define NTP_POLL_INTERVAL_MIN_SEC       16
73 #define NTP_POLL_INTERVAL_MAX_SEC       2048
74 #define NTP_POLL_ACCURACY_SEC           0.1
75
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))
85
86 /*
87  * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
88  * in seconds relative to 0h on 1 January 1900."
89  */
90 #define OFFSET_1900_1970        2208988800UL
91
92 struct ntp_ts {
93         be32_t sec;
94         be32_t frac;
95 } _packed_;
96
97 struct ntp_ts_short {
98         be16_t sec;
99         be16_t frac;
100 } _packed_;
101
102 struct ntp_msg {
103         uint8_t field;
104         uint8_t stratum;
105         int8_t poll;
106         int8_t precision;
107         struct ntp_ts_short root_delay;
108         struct ntp_ts_short root_dispersion;
109         char refid[4];
110         struct ntp_ts reference_time;
111         struct ntp_ts origin_time;
112         struct ntp_ts recv_time;
113         struct ntp_ts trans_time;
114 } _packed_;
115
116 struct SNTPContext {
117         sd_event_source *event_receive;
118         sd_event_source *event_timer;
119
120         char *server;
121         struct sockaddr_in server_addr;
122         int server_socket;
123         uint64_t packet_count;
124
125         struct timespec trans_time_mon;
126         struct timespec trans_time;
127         bool pending;
128
129         usec_t poll_interval;
130
131         struct {
132                 double offset;
133                 double delay;
134         } samples[8];
135         unsigned int samples_idx;
136         double samples_jitter;
137 };
138
139 static int sntp_arm_timer(SNTPContext *sntp);
140
141 static int log2i(int a) {
142         int exp = 0;
143
144         assert(a > 0);
145
146         while (a > 0) {
147                 a >>= 1;
148                 exp++;
149         }
150
151         return exp;
152 }
153
154 static double log2d(int a) {
155         if (a < 0)
156                 return 1.0 / (1UL << - a);
157         return 1UL << a;
158 }
159
160 static double ntp_ts_to_d(const struct ntp_ts *ts) {
161         return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
162 }
163
164 static double tv_to_d(const struct timeval *tv) {
165         return tv->tv_sec + (1.0e-6 * tv->tv_usec);
166 }
167
168 static double ts_to_d(const struct timespec *ts) {
169         return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
170 }
171
172 static void d_to_tv(double d, struct timeval *tv) {
173         tv->tv_sec = (long)d;
174         tv->tv_usec = (d - tv->tv_sec) * 1000 * 1000;
175
176         /* the kernel expects -0.3s as {-1, 7000.000} */
177         if (tv->tv_usec < 0) {
178                 tv->tv_sec  -= 1;
179                 tv->tv_usec += 1000 * 1000;
180         }
181 }
182
183 static double square(double d) {
184         return d * d;
185 }
186
187 static int sntp_send_request(SNTPContext *sntp) {
188         struct ntp_msg ntpmsg = {};
189         struct sockaddr_in addr = {};
190         ssize_t len;
191         int r;
192
193         /*
194          * "The client initializes the NTP message header, sends the request
195          * to the server, and strips the time of day from the Transmit
196          * Timestamp field of the reply.  For this purpose, all the NTP
197          * header fields are set to 0, except the Mode, VN, and optional
198          * Transmit Timestamp fields."
199          */
200         ntpmsg.field = NTP_FIELD(0, 4, NTP_MODE_CLIENT);
201
202         /*
203          * Set transmit timestamp, remember it; the server will send that back
204          * as the origin timestamp and we have an indication that this is the
205          * matching answer to our request.
206          *
207          * The actual value does not matter, We do not care about the correct
208          * NTP UINT_MAX fraction, we just pass the plain nanosecond value.
209          */
210         clock_gettime(CLOCK_MONOTONIC, &sntp->trans_time_mon);
211         clock_gettime(CLOCK_REALTIME, &sntp->trans_time);
212         ntpmsg.trans_time.sec = htobe32(sntp->trans_time.tv_sec + OFFSET_1900_1970);
213         ntpmsg.trans_time.frac = htobe32(sntp->trans_time.tv_nsec);
214
215         addr.sin_family = AF_INET;
216         addr.sin_port = htobe16(123);
217         addr.sin_addr.s_addr = inet_addr(sntp->server);
218         len = sendto(sntp->server_socket, &ntpmsg, sizeof(ntpmsg), MSG_DONTWAIT, &addr, sizeof(addr));
219         if (len < 0) {
220                 log_debug("Sending NTP request to %s failed: %m", sntp->server);
221                 return -errno;
222         }
223
224         sntp->pending = true;
225
226         /* re-arm timer for next poll interval, in case the packet never arrives back */
227         r = sntp_arm_timer(sntp);
228         if (r < 0)
229                 return r;
230
231         log_debug("Sent NTP request to: %s", sntp->server);
232         return 0;
233 }
234
235 static int sntp_timer(sd_event_source *source, usec_t usec, void *userdata) {
236         SNTPContext *sntp = userdata;
237
238         assert(sntp);
239
240         sntp_send_request(sntp);
241         return 0;
242 }
243
244 static int sntp_arm_timer(SNTPContext *sntp) {
245         sd_event *e;
246         int r;
247
248         assert(sntp);
249         assert(sntp->event_receive);
250
251         if (sntp->poll_interval <= 0) {
252                 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
253                 return 0;
254         }
255
256         if (sntp->event_timer) {
257                 r = sd_event_source_set_time(sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval);
258                 if (r < 0)
259                         return r;
260
261                 return sd_event_source_set_enabled(sntp->event_timer, SD_EVENT_ONESHOT);
262         }
263
264         e = sd_event_source_get_event(sntp->event_receive);
265         r = sd_event_add_monotonic(e, &sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval, 0, sntp_timer, sntp);
266         if (r < 0)
267                 return r;
268
269         return 0;
270 }
271
272 static int sntp_adjust_clock(SNTPContext *sntp, double offset, int leap_sec) {
273         struct timex tmx = {};
274         int r;
275
276         /*
277          * For small deltas, tell the kernel to gradually adjust the system
278          * clock to the NTP time, larger deltas are just directly set.
279          *
280          * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
281          * syncs the system time periodically to the hardware clock.
282          */
283         if (offset < NTP_MAX_ADJUST && offset > -NTP_MAX_ADJUST) {
284                 int constant;
285
286                 constant = log2i(sntp->poll_interval / USEC_PER_SEC) - 5;
287
288                 tmx.modes |= ADJ_STATUS | ADJ_OFFSET | ADJ_TIMECONST;
289                 tmx.status = STA_PLL;
290                 tmx.offset = offset * 1000 * 1000;
291                 tmx.constant = constant;
292
293                 log_debug("  adjust (slew): %+f sec\n", (double)tmx.offset / USEC_PER_SEC);
294         } else {
295                 tmx.modes = ADJ_SETOFFSET;
296                 d_to_tv(offset, &tmx.time);
297                 log_debug("  adjust (jump): %+f sec\n", tv_to_d(&tmx.time));
298         }
299
300         switch (leap_sec) {
301         case 1:
302                 tmx.status |= STA_INS;
303                 break;
304         case -1:
305                 tmx.status |= STA_DEL;
306                 break;
307         }
308
309         r = clock_adjtime(CLOCK_REALTIME, &tmx);
310         if (r < 0)
311                 return r;
312
313         log_debug("  status       : %04i %s\n"
314                   "  time now     : %li.%06li\n"
315                   "  constant     : %li\n"
316                   "  offset       : %+f sec\n"
317                   "  freq offset  : %+li (%+.3f ppm)\n",
318                   tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
319                   tmx.time.tv_sec, tmx.time.tv_usec,
320                   tmx.constant,
321                   (double)tmx.offset / USEC_PER_SEC,
322                   tmx.freq, (double)tmx.freq / 65536);
323
324         return 0;
325 }
326
327 static bool sntp_sample_spike_detection(SNTPContext *sntp, double offset, double delay) {
328         unsigned int i, idx_cur, idx_new, idx_min;
329         double jitter;
330         bool spike;
331
332         /* store the current data in our samples array */
333         idx_cur = sntp->samples_idx;
334         idx_new = (idx_cur + 1) % ELEMENTSOF(sntp->samples);
335         sntp->samples_idx = idx_new;
336         sntp->samples[idx_new].offset = offset;
337         sntp->samples[idx_new].delay = delay;
338
339         sntp->packet_count++;
340
341        /*
342         * Spike detection; compare the difference between the
343         * current offset to the previous offset and jitter.
344         */
345         spike = sntp->packet_count > 2 && fabs(offset - sntp->samples[idx_cur].offset) > sntp->samples_jitter * 3;
346
347         /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
348         for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(sntp->samples); i++)
349                 if (sntp->samples[i].delay > 0 && sntp->samples[i].delay < sntp->samples[idx_min].delay)
350                         idx_min = i;
351
352         for (jitter = 0, i = 0; i < ELEMENTSOF(sntp->samples); i++)
353                 jitter += square(sntp->samples[i].offset - sntp->samples[idx_min].offset);
354         sntp->samples_jitter = sqrt(jitter / (ELEMENTSOF(sntp->samples) - 1));
355
356         return spike;
357 }
358
359 static void snmp_adjust_poll(SNTPContext *sntp, double offset, bool spike) {
360         double delta;
361
362         if (spike) {
363                 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
364                         sntp->poll_interval /= 2;
365                 return;
366         }
367
368         delta = fabs(offset);
369
370         /* set to minimal poll interval */
371         if (delta > NTP_POLL_ACCURACY_SEC) {
372                 sntp->poll_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
373                 return;
374         }
375
376         /* increase polling interval */
377         if (delta < NTP_POLL_ACCURACY_SEC * 0.25) {
378                 if (sntp->poll_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
379                         sntp->poll_interval *= 2;
380                 return;
381         }
382
383         /* decrease polling interval */
384         if (delta > NTP_POLL_ACCURACY_SEC * 0.75) {
385                 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
386                         sntp->poll_interval /= 2;
387                 return;
388         }
389 }
390
391 static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
392         SNTPContext *sntp = userdata;
393         unsigned char buf[sizeof(struct ntp_msg)];
394         struct iovec iov = {
395                 .iov_base = buf,
396                 .iov_len = sizeof(buf),
397         };
398         union {
399                 struct cmsghdr cmsghdr;
400                 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
401         } control;
402         struct sockaddr_in server_addr;
403         struct msghdr msghdr = {
404                 .msg_iov = &iov,
405                 .msg_iovlen = 1,
406                 .msg_control = &control,
407                 .msg_controllen = sizeof(control),
408                 .msg_name = &server_addr,
409                 .msg_namelen = sizeof(server_addr),
410         };
411         struct cmsghdr *cmsg;
412         struct timespec now;
413         struct timeval *recv_time;
414         ssize_t len;
415         struct ntp_msg *ntpmsg;
416         double origin, recv, trans, dest;
417         double delay, offset;
418         bool spike;
419         int leap_sec;
420         int r;
421
422         if (revents & (EPOLLHUP|EPOLLERR)) {
423                 log_debug("Server connection returned error, closing.");
424                 sntp_server_disconnect(sntp);
425                 return -ENOTCONN;
426         }
427
428         len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
429         if (len < 0) {
430                 log_debug("Error receiving message, disconnecting");
431                 return -EINVAL;
432         }
433
434         if (iov.iov_len < sizeof(struct ntp_msg)) {
435                 log_debug("Invalid response from server, disconnecting");
436                 return -EINVAL;
437         }
438
439         if (sntp->server_addr.sin_addr.s_addr != server_addr.sin_addr.s_addr) {
440                 log_debug("Response from unknown server, disconnecting");
441                 return -EINVAL;
442         }
443
444         recv_time = NULL;
445         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
446                 if (cmsg->cmsg_level != SOL_SOCKET)
447                         continue;
448
449                 switch (cmsg->cmsg_type) {
450                 case SCM_TIMESTAMP:
451                         recv_time = (struct timeval *) CMSG_DATA(cmsg);
452                         break;
453                 }
454         }
455         if (!recv_time) {
456                 log_debug("Invalid packet timestamp, disconnecting");
457                 return -EINVAL;
458         }
459
460         ntpmsg = iov.iov_base;
461         if (!sntp->pending) {
462                 log_debug("Unexpected reply, ignoring");
463                 return 0;
464         }
465         sntp->pending = false;
466
467         /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
468         if (be32toh(ntpmsg->origin_time.sec) != sntp->trans_time.tv_sec + OFFSET_1900_1970||
469             be32toh(ntpmsg->origin_time.frac) != sntp->trans_time.tv_nsec) {
470                 log_debug("Invalid reply, not our transmit time, ignoring");
471                 return 0;
472         }
473
474         if (NTP_FIELD_LEAP(ntpmsg->field) == NTP_LEAP_NOTINSYNC) {
475                 log_debug("Server is not synchronized, disconnecting");
476                 return -EINVAL;
477         }
478
479         if (NTP_FIELD_VERSION(ntpmsg->field) != 4) {
480                 log_debug("Response NTPv%d, disconnecting", NTP_FIELD_VERSION(ntpmsg->field));
481                 return -EINVAL;
482         }
483
484         if (NTP_FIELD_MODE(ntpmsg->field) != NTP_MODE_SERVER) {
485                 log_debug("Unsupported mode %d, disconnecting", NTP_FIELD_MODE(ntpmsg->field));
486                 return -EINVAL;
487         }
488
489         /* announce leap seconds */
490         if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_PLUSSEC)
491                 leap_sec = 1;
492         else if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_MINUSSEC)
493                 leap_sec = -1;
494         else
495                 leap_sec = 0;
496
497         /*
498          * "Timestamp Name          ID   When Generated
499          *  ------------------------------------------------------------
500          *  Originate Timestamp     T1   time request sent by client
501          *  Receive Timestamp       T2   time request received by server
502          *  Transmit Timestamp      T3   time reply sent by server
503          *  Destination Timestamp   T4   time reply received by client
504          *
505          *  The roundtrip delay d and system clock offset t are defined as:
506          *  d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2"
507          */
508         clock_gettime(CLOCK_MONOTONIC, &now);
509         origin = tv_to_d(recv_time) - (ts_to_d(&now) - ts_to_d(&sntp->trans_time_mon)) + OFFSET_1900_1970;
510         recv = ntp_ts_to_d(&ntpmsg->recv_time);
511         trans = ntp_ts_to_d(&ntpmsg->trans_time);
512         dest = tv_to_d(recv_time) + OFFSET_1900_1970;
513
514         offset = ((recv - origin) + (trans - dest)) / 2;
515         delay = (dest - origin) - (trans - recv);
516
517         spike = sntp_sample_spike_detection(sntp, offset, delay);
518
519         snmp_adjust_poll(sntp, offset, spike);
520
521         log_debug("NTP response:\n"
522                   "  leap         : %u\n"
523                   "  version      : %u\n"
524                   "  mode         : %u\n"
525                   "  stratum      : %u\n"
526                   "  precision    : %f sec (%d)\n"
527                   "  reference    : %.4s\n"
528                   "  origin       : %f\n"
529                   "  recv         : %f\n"
530                   "  transmit     : %f\n"
531                   "  dest         : %f\n"
532                   "  offset       : %+f sec\n"
533                   "  delay        : %+f sec\n"
534                   "  packet count : %llu\n"
535                   "  jitter/spike : %f (%s)\n"
536                   "  poll interval: %llu\n",
537                   NTP_FIELD_LEAP(ntpmsg->field),
538                   NTP_FIELD_VERSION(ntpmsg->field),
539                   NTP_FIELD_MODE(ntpmsg->field),
540                   ntpmsg->stratum,
541                   log2d(ntpmsg->precision), ntpmsg->precision,
542                   ntpmsg->stratum == 1 ? ntpmsg->refid : "n/a",
543                   origin - OFFSET_1900_1970,
544                   recv - OFFSET_1900_1970,
545                   trans - OFFSET_1900_1970,
546                   dest - OFFSET_1900_1970,
547                   offset, delay,
548                   (unsigned long long)sntp->packet_count,
549                   sntp->samples_jitter, spike ? "yes" : "no",
550                   sntp->poll_interval / USEC_PER_SEC);
551
552         log_info("%4llu %s %+12f", sntp->poll_interval / USEC_PER_SEC, spike ? "y" : "n", offset);
553
554         if (!spike) {
555                 r = sntp_adjust_clock(sntp, offset, leap_sec);
556                 if (r < 0)
557                         log_error("Failed to call clock_adjtime(): %m");
558         }
559
560         r = sntp_arm_timer(sntp);
561         if (r < 0)
562                 return r;
563
564         return 0;
565 }
566
567 int sntp_server_connect(SNTPContext *sntp, const char *server) {
568         _cleanup_free_ char *s = NULL;
569
570         assert(sntp);
571         assert(server);
572         assert(sntp->server_socket >= 0);
573
574         s = strdup(server);
575         if (!s)
576                 return -ENOMEM;
577
578         free(sntp->server);
579         sntp->server = s;
580         s = NULL;
581
582         zero(sntp->server_addr);
583         sntp->server_addr.sin_family = AF_INET;
584         sntp->server_addr.sin_addr.s_addr = inet_addr(server);
585
586         sntp->poll_interval = 2 * NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
587
588         return sntp_send_request(sntp);
589 }
590
591 void sntp_server_disconnect(SNTPContext *sntp) {
592         if (!sntp->server)
593                 return;
594
595         sntp->event_timer = sd_event_source_unref(sntp->event_timer);
596         sntp->event_receive = sd_event_source_unref(sntp->event_receive);
597         if (sntp->server_socket > 0)
598                 close(sntp->server_socket);
599         sntp->server_socket = -1;
600         zero(sntp->server_addr);
601         free(sntp->server);
602         sntp->server = NULL;
603 }
604
605 int sntp_new(SNTPContext **sntp, sd_event *e) {
606         _cleanup_free_ SNTPContext *c;
607         _cleanup_close_ int fd = -1;
608         struct sockaddr_in addr;
609         const int on = 1;
610         const int tos = IPTOS_LOWDELAY;
611         int r;
612
613         c = new0(SNTPContext, 1);
614         if (!c)
615                 return -ENOMEM;
616
617         fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
618         if (fd < 0)
619                 return -errno;
620
621         zero(addr);
622         addr.sin_family = AF_INET;
623         r = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
624         if (r < 0)
625                 return -errno;
626
627         r = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
628         if (r < 0)
629                 return -errno;
630
631         r = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
632         if (r < 0)
633                 return -errno;
634
635         r = sd_event_add_io(e, &c->event_receive, fd, EPOLLIN, sntp_receive_response, c);
636         if (r < 0)
637                 return r;
638
639         c->server_socket = fd;
640         fd = -1;
641
642         *sntp = c;
643         c = NULL;
644
645         return 0;
646 }
647
648 SNTPContext *sntp_unref(SNTPContext *sntp) {
649         sntp_server_disconnect(sntp);
650         free(sntp);
651         return NULL;
652 }