chiark / gitweb /
4d992c49de5cf00b03cac98e21b98cfa3a707eb2
[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 double ntp_ts_to_d(const struct ntp_ts *ts) {
142         return be32toh(ts->sec) + ((double)be32toh(ts->frac) / UINT_MAX);
143 }
144
145 static double tv_to_d(const struct timeval *tv) {
146         return tv->tv_sec + (1.0e-6 * tv->tv_usec);
147 }
148
149 static double ts_to_d(const struct timespec *ts) {
150         return ts->tv_sec + (1.0e-9 * ts->tv_nsec);
151 }
152
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;
156
157         /* the kernel expects -0.3s as {-1, 7000.000} */
158         if (tv->tv_usec < 0) {
159                 tv->tv_sec  -= 1;
160                 tv->tv_usec += 1000 * 1000;
161         }
162 }
163
164 static double square(double d) {
165         return d * d;
166 }
167
168 static int sntp_send_request(SNTPContext *sntp) {
169         struct ntp_msg ntpmsg = {};
170         struct sockaddr_in addr = {};
171         ssize_t len;
172         int r;
173
174         /*
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."
180          */
181         ntpmsg.field = NTP_FIELD(0, 4, NTP_MODE_CLIENT);
182
183         /*
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.
187          *
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.
190          */
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);
195
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));
200         if (len < 0) {
201                 log_debug("Sending NTP request to %s failed: %m", sntp->server);
202                 return -errno;
203         }
204
205         sntp->pending = true;
206
207         /* re-arm timer for next poll interval, in case the packet never arrives back */
208         r = sntp_arm_timer(sntp);
209         if (r < 0)
210                 return r;
211
212         log_debug("Sent NTP request to: %s", sntp->server);
213         return 0;
214 }
215
216 static int sntp_timer(sd_event_source *source, usec_t usec, void *userdata) {
217         SNTPContext *sntp = userdata;
218
219         assert(sntp);
220
221         sntp_send_request(sntp);
222         return 0;
223 }
224
225 static int sntp_arm_timer(SNTPContext *sntp) {
226         sd_event *e;
227         int r;
228
229         assert(sntp);
230         assert(sntp->event_receive);
231
232         if (sntp->poll_interval <= 0) {
233                 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
234                 return 0;
235         }
236
237         if (sntp->event_timer) {
238                 r = sd_event_source_set_time(sntp->event_timer, now(CLOCK_MONOTONIC) + sntp->poll_interval);
239                 if (r < 0)
240                         return r;
241
242                 return sd_event_source_set_enabled(sntp->event_timer, SD_EVENT_ONESHOT);
243         }
244
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);
247         if (r < 0)
248                 return r;
249
250         return 0;
251 }
252
253 static int sntp_adjust_clock(SNTPContext *sntp, double offset, int leap_sec) {
254         struct timex tmx = {};
255         int r;
256
257         /*
258          * For small deltas, tell the kernel to gradually adjust the system
259          * clock to the NTP time, larger deltas are just directly set.
260          *
261          * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
262          * syncs the system time periodically to the hardware clock.
263          */
264         if (offset < NTP_MAX_ADJUST && offset > -NTP_MAX_ADJUST) {
265                 int constant;
266
267                 constant = log2i(sntp->poll_interval / USEC_PER_SEC) - 5;
268
269                 tmx.modes |= ADJ_STATUS | ADJ_OFFSET | ADJ_TIMECONST;
270                 tmx.status = STA_PLL;
271                 tmx.offset = offset * 1000 * 1000;
272                 tmx.constant = constant;
273
274                 log_debug("  adjust (slew): %+f sec\n", (double)tmx.offset / USEC_PER_SEC);
275         } else {
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));
279         }
280
281         switch (leap_sec) {
282         case 1:
283                 tmx.status |= STA_INS;
284                 break;
285         case -1:
286                 tmx.status |= STA_DEL;
287                 break;
288         }
289
290         r = clock_adjtime(CLOCK_REALTIME, &tmx);
291         if (r < 0)
292                 return r;
293
294         log_debug("  status       : %04i %s\n"
295                   "  time now     : %li.%06li\n"
296                   "  constant     : %li\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,
301                   tmx.constant,
302                   (double)tmx.offset / USEC_PER_SEC,
303                   tmx.freq, (double)tmx.freq / 65536);
304
305         return 0;
306 }
307
308 static bool sntp_sample_spike_detection(SNTPContext *sntp, double offset, double delay) {
309         unsigned int i, idx_cur, idx_new, idx_min;
310         double jitter;
311         bool spike;
312
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;
319
320         sntp->packet_count++;
321
322        /*
323         * Spike detection; compare the difference between the
324         * current offset to the previous offset and jitter.
325         */
326         spike = sntp->packet_count > 2 && fabs(offset - sntp->samples[idx_cur].offset) > sntp->samples_jitter * 3;
327
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)
331                         idx_min = i;
332
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));
336
337         return spike;
338 }
339
340 static void snmp_adjust_poll(SNTPContext *sntp, double offset, bool spike) {
341         double delta;
342
343         if (spike) {
344                 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
345                         sntp->poll_interval /= 2;
346                 return;
347         }
348
349         delta = fabs(offset);
350
351         /* set to minimal poll interval */
352         if (delta > NTP_POLL_ACCURACY_SEC) {
353                 sntp->poll_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
354                 return;
355         }
356
357         /* increase polling interval */
358         if (delta < NTP_POLL_ACCURACY_SEC * 0.25) {
359                 if (sntp->poll_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
360                         sntp->poll_interval *= 2;
361                 return;
362         }
363
364         /* decrease polling interval */
365         if (delta > NTP_POLL_ACCURACY_SEC * 0.75) {
366                 if (sntp->poll_interval > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
367                         sntp->poll_interval /= 2;
368                 return;
369         }
370 }
371
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)];
375         struct iovec iov = {
376                 .iov_base = buf,
377                 .iov_len = sizeof(buf),
378         };
379         union {
380                 struct cmsghdr cmsghdr;
381                 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
382         } control;
383         struct sockaddr_in server_addr;
384         struct msghdr msghdr = {
385                 .msg_iov = &iov,
386                 .msg_iovlen = 1,
387                 .msg_control = &control,
388                 .msg_controllen = sizeof(control),
389                 .msg_name = &server_addr,
390                 .msg_namelen = sizeof(server_addr),
391         };
392         struct cmsghdr *cmsg;
393         struct timespec now;
394         struct timeval *recv_time;
395         ssize_t len;
396         struct ntp_msg *ntpmsg;
397         double origin, recv, trans, dest;
398         double delay, offset;
399         bool spike;
400         int leap_sec;
401         int r;
402
403         if (revents & (EPOLLHUP|EPOLLERR)) {
404                 log_debug("Server connection returned error, closing.");
405                 sntp_server_disconnect(sntp);
406                 return -ENOTCONN;
407         }
408
409         len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
410         if (len < 0) {
411                 log_debug("Error receiving message, disconnecting");
412                 return -EINVAL;
413         }
414
415         if (iov.iov_len < sizeof(struct ntp_msg)) {
416                 log_debug("Invalid response from server, disconnecting");
417                 return -EINVAL;
418         }
419
420         if (sntp->server_addr.sin_addr.s_addr != server_addr.sin_addr.s_addr) {
421                 log_debug("Response from unknown server, disconnecting");
422                 return -EINVAL;
423         }
424
425         recv_time = NULL;
426         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
427                 if (cmsg->cmsg_level != SOL_SOCKET)
428                         continue;
429
430                 switch (cmsg->cmsg_type) {
431                 case SCM_TIMESTAMP:
432                         recv_time = (struct timeval *) CMSG_DATA(cmsg);
433                         break;
434                 }
435         }
436         if (!recv_time) {
437                 log_debug("Invalid packet timestamp, disconnecting");
438                 return -EINVAL;
439         }
440
441         ntpmsg = iov.iov_base;
442         if (!sntp->pending) {
443                 log_debug("Unexpected reply, ignoring");
444                 return 0;
445         }
446         sntp->pending = false;
447
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");
452                 return 0;
453         }
454
455         if (NTP_FIELD_LEAP(ntpmsg->field) == NTP_LEAP_NOTINSYNC) {
456                 log_debug("Server is not synchronized, disconnecting");
457                 return -EINVAL;
458         }
459
460         if (NTP_FIELD_VERSION(ntpmsg->field) != 4) {
461                 log_debug("Response NTPv%d, disconnecting", NTP_FIELD_VERSION(ntpmsg->field));
462                 return -EINVAL;
463         }
464
465         if (NTP_FIELD_MODE(ntpmsg->field) != NTP_MODE_SERVER) {
466                 log_debug("Unsupported mode %d, disconnecting", NTP_FIELD_MODE(ntpmsg->field));
467                 return -EINVAL;
468         }
469
470         /* announce leap seconds */
471         if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_PLUSSEC)
472                 leap_sec = 1;
473         else if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_MINUSSEC)
474                 leap_sec = -1;
475         else
476                 leap_sec = 0;
477
478         /*
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
485          *
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"
488          */
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         recv = 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;
494
495         offset = ((recv - origin) + (trans - dest)) / 2;
496         delay = (dest - origin) - (trans - recv);
497
498         spike = sntp_sample_spike_detection(sntp, offset, delay);
499
500         snmp_adjust_poll(sntp, offset, spike);
501
502         log_debug("NTP response:\n"
503                   "  leap         : %u\n"
504                   "  version      : %u\n"
505                   "  mode         : %u\n"
506                   "  stratum      : %u\n"
507                   "  precision    : %f sec (%d)\n"
508                   "  reference    : %.4s\n"
509                   "  origin       : %f\n"
510                   "  recv         : %f\n"
511                   "  transmit     : %f\n"
512                   "  dest         : %f\n"
513                   "  offset       : %+f sec\n"
514                   "  delay        : %+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),
521                   ntpmsg->stratum,
522                   exp2(ntpmsg->precision), ntpmsg->precision,
523                   ntpmsg->stratum == 1 ? ntpmsg->refid : "n/a",
524                   origin - OFFSET_1900_1970,
525                   recv - OFFSET_1900_1970,
526                   trans - OFFSET_1900_1970,
527                   dest - OFFSET_1900_1970,
528                   offset, delay,
529                   sntp->packet_count,
530                   sntp->samples_jitter, spike ? "yes" : "no",
531                   sntp->poll_interval / USEC_PER_SEC);
532
533         log_info("%4llu %s %+12f", sntp->poll_interval / USEC_PER_SEC, spike ? "y" : "n", offset);
534
535         if (!spike) {
536                 r = sntp_adjust_clock(sntp, offset, leap_sec);
537                 if (r < 0)
538                         log_error("Failed to call clock_adjtime(): %m");
539         }
540
541         r = sntp_arm_timer(sntp);
542         if (r < 0)
543                 return r;
544
545         return 0;
546 }
547
548 int sntp_server_connect(SNTPContext *sntp, const char *server) {
549         _cleanup_free_ char *s = NULL;
550
551         assert(sntp);
552         assert(server);
553         assert(sntp->server_socket >= 0);
554
555         s = strdup(server);
556         if (!s)
557                 return -ENOMEM;
558
559         free(sntp->server);
560         sntp->server = s;
561         s = NULL;
562
563         zero(sntp->server_addr);
564         sntp->server_addr.sin_family = AF_INET;
565         sntp->server_addr.sin_addr.s_addr = inet_addr(server);
566
567         sntp->poll_interval = 2 * NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
568
569         return sntp_send_request(sntp);
570 }
571
572 void sntp_server_disconnect(SNTPContext *sntp) {
573         if (!sntp->server)
574                 return;
575
576         sntp->event_timer = sd_event_source_unref(sntp->event_timer);
577         sntp->event_receive = sd_event_source_unref(sntp->event_receive);
578         if (sntp->server_socket > 0)
579                 close(sntp->server_socket);
580         sntp->server_socket = -1;
581         zero(sntp->server_addr);
582         free(sntp->server);
583         sntp->server = NULL;
584 }
585
586 int sntp_new(SNTPContext **sntp, sd_event *e) {
587         _cleanup_free_ SNTPContext *c;
588         _cleanup_close_ int fd = -1;
589         struct sockaddr_in addr;
590         const int on = 1;
591         const int tos = IPTOS_LOWDELAY;
592         int r;
593
594         c = new0(SNTPContext, 1);
595         if (!c)
596                 return -ENOMEM;
597
598         fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
599         if (fd < 0)
600                 return -errno;
601
602         zero(addr);
603         addr.sin_family = AF_INET;
604         r = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
605         if (r < 0)
606                 return -errno;
607
608         r = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
609         if (r < 0)
610                 return -errno;
611
612         r = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
613         if (r < 0)
614                 return -errno;
615
616         r = sd_event_add_io(e, &c->event_receive, fd, EPOLLIN, sntp_receive_response, c);
617         if (r < 0)
618                 return r;
619
620         c->server_socket = fd;
621         fd = -1;
622
623         *sntp = c;
624         c = NULL;
625
626         return 0;
627 }
628
629 SNTPContext *sntp_unref(SNTPContext *sntp) {
630         sntp_server_disconnect(sntp);
631         free(sntp);
632         return NULL;
633 }