chiark / gitweb /
880b467a8e6ffef9033e41ae59b2c2644e3e865e
[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/timerfd.h>
46 #include <sys/timex.h>
47 #include <sys/socket.h>
48
49 #include "missing.h"
50 #include "util.h"
51 #include "sparse-endian.h"
52 #include "log.h"
53 #include "sd-event.h"
54 #include "timedate-sntp.h"
55
56 #define TIME_T_MAX (time_t)((1UL << ((sizeof(time_t) << 3) - 1)) - 1)
57
58 #ifndef ADJ_SETOFFSET
59 #define ADJ_SETOFFSET                   0x0100  /* add 'time' to current time */
60 #endif
61
62 /* Maximum delta in seconds which the system clock is gradually adjusted
63  * to approach the network time. Deltas larger that this are set by letting
64  * the system time jump. The maximum for adjtime is 500ms.
65  */
66 #define NTP_MAX_ADJUST                  0.2
67
68 /*
69  * "Define the required accuracy of the system clock, then calculate the
70  * maximum timeout. Use the longest maximum timeout possible given the system
71  * constraints to minimize time server aggregate load."
72  *
73  * "A client MUST NOT under any conditions use a poll interval less
74  * than 15 seconds."
75  */
76 #define NTP_POLL_INTERVAL_MIN_SEC       16
77 #define NTP_POLL_INTERVAL_MAX_SEC       2048
78 #define NTP_ACCURACY_SEC                0.1
79
80 #define NTP_LEAP_PLUSSEC                1
81 #define NTP_LEAP_MINUSSEC               2
82 #define NTP_LEAP_NOTINSYNC              3
83 #define NTP_MODE_CLIENT                 3
84 #define NTP_MODE_SERVER                 4
85 #define NTP_FIELD_LEAP(f)               (((f) >> 6) & 3)
86 #define NTP_FIELD_VERSION(f)            (((f) >> 3) & 7)
87 #define NTP_FIELD_MODE(f)               ((f) & 7)
88 #define NTP_FIELD(l, v, m)              (((l) << 6) | ((v) << 3) | (m))
89
90 /*
91  * "NTP timestamps are represented as a 64-bit unsigned fixed-point number,
92  * in seconds relative to 0h on 1 January 1900."
93  */
94 #define OFFSET_1900_1970        2208988800UL
95
96 struct ntp_ts {
97         be32_t sec;
98         be32_t frac;
99 } _packed_;
100
101 struct ntp_ts_short {
102         be16_t sec;
103         be16_t frac;
104 } _packed_;
105
106 struct ntp_msg {
107         uint8_t field;
108         uint8_t stratum;
109         int8_t poll;
110         int8_t precision;
111         struct ntp_ts_short root_delay;
112         struct ntp_ts_short root_dispersion;
113         char refid[4];
114         struct ntp_ts reference_time;
115         struct ntp_ts origin_time;
116         struct ntp_ts recv_time;
117         struct ntp_ts trans_time;
118 } _packed_;
119
120 struct SNTPContext {
121         void (*report)(usec_t poll, double offset, double delay, double jitter, bool spike);
122
123         /* peer */
124         sd_event_source *event_receive;
125         char *server;
126         struct sockaddr_in server_addr;
127         int server_socket;
128         uint64_t packet_count;
129
130         /* last sent packet */
131         struct timespec trans_time_mon;
132         struct timespec trans_time;
133         usec_t retry_interval;
134         bool pending;
135
136         /* poll timer */
137         sd_event_source *event_timer;
138         usec_t poll_interval_usec;
139         bool poll_resync;
140
141         /* history data */
142         struct {
143                 double offset;
144                 double delay;
145         } samples[8];
146         unsigned int samples_idx;
147         double samples_jitter;
148
149         /* last change */
150         bool jumped;
151
152         /* watch for time changes */
153         sd_event_source *event_clock_watch;
154         int clock_watch_fd;
155 };
156
157 static int sntp_arm_timer(SNTPContext *sntp, usec_t next);
158 static int sntp_clock_watch_setup(SNTPContext *sntp);
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 == sizeof(ntpmsg)) {
220                 sntp->pending = true;
221                 log_debug("Sent NTP request to: %s", sntp->server);
222         } else
223                 log_debug("Sending NTP request to %s failed: %m", sntp->server);
224
225         /* re-arm timer with incresing timeout, in case the packets never arrive back */
226         if (sntp->retry_interval > 0) {
227                 if (sntp->retry_interval < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
228                         sntp->retry_interval *= 2;
229         } else
230                 sntp->retry_interval = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
231         r = sntp_arm_timer(sntp, sntp->retry_interval);
232         if (r < 0)
233                 return r;
234
235         return 0;
236 }
237
238 static int sntp_timer(sd_event_source *source, usec_t usec, void *userdata) {
239         SNTPContext *sntp = userdata;
240
241         assert(sntp);
242
243         sntp_send_request(sntp);
244         return 0;
245 }
246
247 static int sntp_arm_timer(SNTPContext *sntp, usec_t next) {
248         sd_event *e;
249         int r;
250
251         assert(sntp);
252         assert(sntp->event_receive);
253
254         if (next == 0) {
255                 sntp->event_timer = sd_event_source_unref(sntp->event_timer);
256                 return 0;
257         }
258
259         if (sntp->event_timer) {
260                 r = sd_event_source_set_time(sntp->event_timer, now(CLOCK_MONOTONIC) + next);
261                 if (r < 0)
262                         return r;
263
264                 return sd_event_source_set_enabled(sntp->event_timer, SD_EVENT_ONESHOT);
265         }
266
267         e = sd_event_source_get_event(sntp->event_receive);
268         r = sd_event_add_time(
269                         e,
270                         &sntp->event_timer,
271                         CLOCK_MONOTONIC,
272                         now(CLOCK_MONOTONIC) + next, 0,
273                         sntp_timer, sntp);
274         if (r < 0)
275                 return r;
276
277         return 0;
278 }
279
280 static int sntp_clock_watch(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
281         SNTPContext *sntp = userdata;
282
283         assert(sntp);
284         assert(sntp->event_receive);
285
286         /* rearm timer */
287         sntp_clock_watch_setup(sntp);
288
289         /* skip our own jumps */
290         if (sntp->jumped) {
291                 sntp->jumped = false;
292                 return 0;
293         }
294
295         /* resync */
296         log_info("System time changed, resyncing.");
297         sntp->poll_resync = true;
298         sntp_send_request(sntp);
299
300         return 0;
301 }
302
303 /* wake up when the system time changes underneath us */
304 static int sntp_clock_watch_setup(SNTPContext *sntp) {
305         struct itimerspec its = { .it_value.tv_sec = TIME_T_MAX };
306         _cleanup_close_ int fd = -1;
307         sd_event *e;
308         sd_event_source *source;
309         int r;
310
311         assert(sntp);
312         assert(sntp->event_receive);
313
314         fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK|TFD_CLOEXEC);
315         if (fd < 0) {
316                 log_error("Failed to create timerfd: %m");
317                 return -errno;
318         }
319
320         if (timerfd_settime(fd, TFD_TIMER_ABSTIME|TFD_TIMER_CANCEL_ON_SET, &its, NULL) < 0) {
321                 log_error("Failed to set up timerfd: %m");
322                 return -errno;
323         }
324
325         e = sd_event_source_get_event(sntp->event_receive);
326         r = sd_event_add_io(e, &source, fd, EPOLLIN, sntp_clock_watch, sntp);
327         if (r < 0) {
328                 log_error("Failed to create clock watch event source: %s", strerror(-r));
329                 return r;
330         }
331
332         sd_event_source_unref(sntp->event_clock_watch);
333         sntp->event_clock_watch = source;
334
335         if (sntp->clock_watch_fd >= 0)
336                 close(sntp->clock_watch_fd);
337         sntp->clock_watch_fd = fd;
338         fd = -1;
339
340         return 0;
341 }
342
343 static int sntp_adjust_clock(SNTPContext *sntp, double offset, int leap_sec) {
344         struct timex tmx = {};
345         int r;
346
347         /*
348          * For small deltas, tell the kernel to gradually adjust the system
349          * clock to the NTP time, larger deltas are just directly set.
350          *
351          * Clear STA_UNSYNC, it will enable the kernel's 11-minute mode, which
352          * syncs the system time periodically to the hardware clock.
353          */
354         if (offset < NTP_MAX_ADJUST && offset > -NTP_MAX_ADJUST) {
355                 tmx.modes |= ADJ_STATUS | ADJ_OFFSET | ADJ_TIMECONST | ADJ_MAXERROR | ADJ_ESTERROR;
356                 tmx.status = STA_PLL;
357                 tmx.offset = offset * 1000 * 1000;
358                 tmx.constant = log2i(sntp->poll_interval_usec / USEC_PER_SEC) - 6;
359                 tmx.maxerror = 0;
360                 tmx.esterror = 0;
361                 log_debug("  adjust (slew): %+f sec\n", (double)tmx.offset / USEC_PER_SEC);
362         } else {
363                 tmx.modes = ADJ_SETOFFSET;
364                 d_to_tv(offset, &tmx.time);
365
366                 sntp->jumped = true;
367                 log_debug("  adjust (jump): %+f sec\n", tv_to_d(&tmx.time));
368         }
369
370         switch (leap_sec) {
371         case 1:
372                 tmx.status |= STA_INS;
373                 break;
374         case -1:
375                 tmx.status |= STA_DEL;
376                 break;
377         }
378
379         r = clock_adjtime(CLOCK_REALTIME, &tmx);
380         if (r < 0)
381                 return r;
382
383         log_debug("  status       : %04i %s\n"
384                   "  time now     : %li.%06li\n"
385                   "  constant     : %li\n"
386                   "  offset       : %+f sec\n"
387                   "  freq offset  : %+li (%+.3f ppm)\n",
388                   tmx.status, tmx.status & STA_UNSYNC ? "" : "sync",
389                   tmx.time.tv_sec, tmx.time.tv_usec,
390                   tmx.constant,
391                   (double)tmx.offset / USEC_PER_SEC,
392                   tmx.freq, (double)tmx.freq / 65536);
393
394         return 0;
395 }
396
397 static bool sntp_sample_spike_detection(SNTPContext *sntp, double offset, double delay) {
398         unsigned int i, idx_cur, idx_new, idx_min;
399         double jitter;
400         double j;
401
402         /* store the current data in our samples array */
403         idx_cur = sntp->samples_idx;
404         idx_new = (idx_cur + 1) % ELEMENTSOF(sntp->samples);
405         sntp->samples_idx = idx_new;
406         sntp->samples[idx_new].offset = offset;
407         sntp->samples[idx_new].delay = delay;
408
409         sntp->packet_count++;
410         jitter = sntp->samples_jitter;
411
412         /* calculate new jitter value from the RMS differences relative to the lowest delay sample */
413         for (idx_min = idx_cur, i = 0; i < ELEMENTSOF(sntp->samples); i++)
414                 if (sntp->samples[i].delay > 0 && sntp->samples[i].delay < sntp->samples[idx_min].delay)
415                         idx_min = i;
416
417         j = 0;
418         for (i = 0; i < ELEMENTSOF(sntp->samples); i++)
419                 j += square(sntp->samples[i].offset - sntp->samples[idx_min].offset);
420         sntp->samples_jitter = sqrt(j / (ELEMENTSOF(sntp->samples) - 1));
421
422         /* ignore samples when resyncing */
423         if (sntp->poll_resync)
424                 return false;
425
426         /* always accept offset if we are farther off than the round-trip delay */
427         if (fabs(offset) > delay)
428                 return false;
429
430         /* we need a few samples before looking at them */
431         if (sntp->packet_count < 4)
432                 return false;
433
434         /* do not accept anything worse than the maximum possible error of the best sample */
435         if (fabs(offset) > sntp->samples[idx_min].delay)
436                 return true;
437
438         /* compare the difference between the current offset to the previous offset and jitter */
439         return fabs(offset - sntp->samples[idx_cur].offset) > 3 * jitter;
440 }
441
442 static void sntp_adjust_poll(SNTPContext *sntp, double offset, bool spike) {
443         if (sntp->poll_resync) {
444                 sntp->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
445                 sntp->poll_resync = false;
446                 return;
447         }
448
449         /* set to minimal poll interval */
450         if (!spike && fabs(offset) > NTP_ACCURACY_SEC) {
451                 sntp->poll_interval_usec = NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
452                 return;
453         }
454
455         /* increase polling interval */
456         if (fabs(offset) < NTP_ACCURACY_SEC * 0.25) {
457                 if (sntp->poll_interval_usec < NTP_POLL_INTERVAL_MAX_SEC * USEC_PER_SEC)
458                         sntp->poll_interval_usec *= 2;
459                 return;
460         }
461
462         /* decrease polling interval */
463         if (spike || fabs(offset) > NTP_ACCURACY_SEC * 0.75) {
464                 if (sntp->poll_interval_usec > NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC)
465                         sntp->poll_interval_usec /= 2;
466                 return;
467         }
468 }
469
470 static int sntp_receive_response(sd_event_source *source, int fd, uint32_t revents, void *userdata) {
471         SNTPContext *sntp = userdata;
472         unsigned char buf[sizeof(struct ntp_msg)];
473         struct iovec iov = {
474                 .iov_base = buf,
475                 .iov_len = sizeof(buf),
476         };
477         union {
478                 struct cmsghdr cmsghdr;
479                 uint8_t buf[CMSG_SPACE(sizeof(struct timeval))];
480         } control;
481         struct sockaddr_in server_addr;
482         struct msghdr msghdr = {
483                 .msg_iov = &iov,
484                 .msg_iovlen = 1,
485                 .msg_control = &control,
486                 .msg_controllen = sizeof(control),
487                 .msg_name = &server_addr,
488                 .msg_namelen = sizeof(server_addr),
489         };
490         struct cmsghdr *cmsg;
491         struct timespec now_ts;
492         struct timeval *recv_time;
493         ssize_t len;
494         struct ntp_msg *ntpmsg;
495         double origin, receive, trans, dest;
496         double delay, offset;
497         bool spike;
498         int leap_sec;
499         int r;
500
501         if (revents & (EPOLLHUP|EPOLLERR)) {
502                 log_debug("Server connection returned error, closing.");
503                 sntp_server_disconnect(sntp);
504                 return -ENOTCONN;
505         }
506
507         len = recvmsg(fd, &msghdr, MSG_DONTWAIT);
508         if (len < 0) {
509                 log_debug("Error receiving message, disconnecting");
510                 return -EINVAL;
511         }
512
513         if (iov.iov_len < sizeof(struct ntp_msg)) {
514                 log_debug("Invalid response from server, disconnecting");
515                 return -EINVAL;
516         }
517
518         if (sntp->server_addr.sin_addr.s_addr != server_addr.sin_addr.s_addr) {
519                 log_debug("Response from unknown server, disconnecting");
520                 return -EINVAL;
521         }
522
523         recv_time = NULL;
524         for (cmsg = CMSG_FIRSTHDR(&msghdr); cmsg; cmsg = CMSG_NXTHDR(&msghdr, cmsg)) {
525                 if (cmsg->cmsg_level != SOL_SOCKET)
526                         continue;
527
528                 switch (cmsg->cmsg_type) {
529                 case SCM_TIMESTAMP:
530                         recv_time = (struct timeval *) CMSG_DATA(cmsg);
531                         break;
532                 }
533         }
534         if (!recv_time) {
535                 log_debug("Invalid packet timestamp, disconnecting");
536                 return -EINVAL;
537         }
538
539         ntpmsg = iov.iov_base;
540         if (!sntp->pending) {
541                 log_debug("Unexpected reply, ignoring");
542                 return 0;
543         }
544
545         /* check our "time cookie" (we just stored nanoseconds in the fraction field) */
546         if (be32toh(ntpmsg->origin_time.sec) != sntp->trans_time.tv_sec + OFFSET_1900_1970||
547             be32toh(ntpmsg->origin_time.frac) != sntp->trans_time.tv_nsec) {
548                 log_debug("Invalid reply, not our transmit time, ignoring");
549                 return 0;
550         }
551
552         if (NTP_FIELD_LEAP(ntpmsg->field) == NTP_LEAP_NOTINSYNC) {
553                 log_debug("Server is not synchronized, disconnecting");
554                 return -EINVAL;
555         }
556
557         if (NTP_FIELD_VERSION(ntpmsg->field) != 4) {
558                 log_debug("Response NTPv%d, disconnecting", NTP_FIELD_VERSION(ntpmsg->field));
559                 return -EINVAL;
560         }
561
562         if (NTP_FIELD_MODE(ntpmsg->field) != NTP_MODE_SERVER) {
563                 log_debug("Unsupported mode %d, disconnecting", NTP_FIELD_MODE(ntpmsg->field));
564                 return -EINVAL;
565         }
566
567         /* valid packet */
568         sntp->pending = false;
569         sntp->retry_interval = 0;
570
571         /* announce leap seconds */
572         if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_PLUSSEC)
573                 leap_sec = 1;
574         else if (NTP_FIELD_LEAP(ntpmsg->field) & NTP_LEAP_MINUSSEC)
575                 leap_sec = -1;
576         else
577                 leap_sec = 0;
578
579         /*
580          * "Timestamp Name          ID   When Generated
581          *  ------------------------------------------------------------
582          *  Originate Timestamp     T1   time request sent by client
583          *  Receive Timestamp       T2   time request received by server
584          *  Transmit Timestamp      T3   time reply sent by server
585          *  Destination Timestamp   T4   time reply received by client
586          *
587          *  The roundtrip delay d and system clock offset t are defined as:
588          *  d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2"
589          */
590         clock_gettime(CLOCK_MONOTONIC, &now_ts);
591         origin = tv_to_d(recv_time) - (ts_to_d(&now_ts) - ts_to_d(&sntp->trans_time_mon)) + OFFSET_1900_1970;
592         receive = ntp_ts_to_d(&ntpmsg->recv_time);
593         trans = ntp_ts_to_d(&ntpmsg->trans_time);
594         dest = tv_to_d(recv_time) + OFFSET_1900_1970;
595
596         offset = ((receive - origin) + (trans - dest)) / 2;
597         delay = (dest - origin) - (trans - receive);
598
599         spike = sntp_sample_spike_detection(sntp, offset, delay);
600
601         sntp_adjust_poll(sntp, offset, spike);
602
603         log_debug("NTP response:\n"
604                   "  leap         : %u\n"
605                   "  version      : %u\n"
606                   "  mode         : %u\n"
607                   "  stratum      : %u\n"
608                   "  precision    : %f sec (%d)\n"
609                   "  reference    : %.4s\n"
610                   "  origin       : %f\n"
611                   "  receive      : %f\n"
612                   "  transmit     : %f\n"
613                   "  dest         : %f\n"
614                   "  offset       : %+f sec\n"
615                   "  delay        : %+f sec\n"
616                   "  packet count : %"PRIu64"\n"
617                   "  jitter       : %f%s\n"
618                   "  poll interval: %llu\n",
619                   NTP_FIELD_LEAP(ntpmsg->field),
620                   NTP_FIELD_VERSION(ntpmsg->field),
621                   NTP_FIELD_MODE(ntpmsg->field),
622                   ntpmsg->stratum,
623                   exp2(ntpmsg->precision), ntpmsg->precision,
624                   ntpmsg->stratum == 1 ? ntpmsg->refid : "n/a",
625                   origin - OFFSET_1900_1970,
626                   receive - OFFSET_1900_1970,
627                   trans - OFFSET_1900_1970,
628                   dest - OFFSET_1900_1970,
629                   offset, delay,
630                   sntp->packet_count,
631                   sntp->samples_jitter, spike ? " spike" : "",
632                   sntp->poll_interval_usec / USEC_PER_SEC);
633
634         if (sntp->report)
635                 sntp->report(sntp->poll_interval_usec, offset, delay, sntp->samples_jitter, spike);
636
637         if (!spike) {
638                 r = sntp_adjust_clock(sntp, offset, leap_sec);
639                 if (r < 0)
640                         log_error("Failed to call clock_adjtime(): %m");
641         }
642
643         r = sntp_arm_timer(sntp, sntp->poll_interval_usec);
644         if (r < 0)
645                 return r;
646
647         return 0;
648 }
649
650 int sntp_server_connect(SNTPContext *sntp, const char *server) {
651         _cleanup_free_ char *s = NULL;
652
653         assert(sntp);
654         assert(server);
655         assert(sntp->server_socket >= 0);
656
657         s = strdup(server);
658         if (!s)
659                 return -ENOMEM;
660
661         free(sntp->server);
662         sntp->server = s;
663         s = NULL;
664
665         zero(sntp->server_addr);
666         sntp->server_addr.sin_family = AF_INET;
667         sntp->server_addr.sin_addr.s_addr = inet_addr(server);
668
669         sntp->poll_interval_usec = 2 * NTP_POLL_INTERVAL_MIN_SEC * USEC_PER_SEC;
670
671         return sntp_send_request(sntp);
672 }
673
674 void sntp_server_disconnect(SNTPContext *sntp) {
675         if (!sntp->server)
676                 return;
677
678         sntp->event_timer = sd_event_source_unref(sntp->event_timer);
679
680         sntp->event_clock_watch = sd_event_source_unref(sntp->event_clock_watch);
681         if (sntp->clock_watch_fd > 0)
682                 close(sntp->clock_watch_fd);
683         sntp->clock_watch_fd = -1;
684
685         sntp->event_receive = sd_event_source_unref(sntp->event_receive);
686         if (sntp->server_socket > 0)
687                 close(sntp->server_socket);
688         sntp->server_socket = -1;
689
690         zero(sntp->server_addr);
691         free(sntp->server);
692         sntp->server = NULL;
693 }
694
695 static int sntp_listen_setup(SNTPContext *sntp, sd_event *e) {
696         _cleanup_close_ int fd = -1;
697         struct sockaddr_in addr;
698         const int on = 1;
699         const int tos = IPTOS_LOWDELAY;
700         int r;
701
702         fd = socket(PF_INET, SOCK_DGRAM | SOCK_CLOEXEC, 0);
703         if (fd < 0)
704                 return -errno;
705
706         zero(addr);
707         addr.sin_family = AF_INET;
708         r = bind(fd, (struct sockaddr *)&addr, sizeof(addr));
709         if (r < 0)
710                 return -errno;
711
712         r = setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on));
713         if (r < 0)
714                 return -errno;
715
716         r = setsockopt(fd, IPPROTO_IP, IP_TOS, &tos, sizeof(tos));
717         if (r < 0)
718                 return -errno;
719
720         r = sd_event_add_io(e, &sntp->event_receive, fd, EPOLLIN, sntp_receive_response, sntp);
721         if (r < 0)
722                 return r;
723
724         sntp->server_socket = fd;
725         fd = -1;
726
727         return 0;
728 }
729
730 void sntp_report_register(SNTPContext *sntp, void (*report)(usec_t poll_usec, double offset, double delay, double jitter, bool spike)) {
731         sntp->report = report;
732 }
733
734 int sntp_new(SNTPContext **sntp, sd_event *e) {
735         _cleanup_free_ SNTPContext *c;
736         int r;
737
738         c = new0(SNTPContext, 1);
739         if (!c)
740                 return -ENOMEM;
741
742         r = sntp_listen_setup(c, e);
743         if (r < 0)
744                 return r;
745
746         r = sntp_clock_watch_setup(c);
747         if (r < 0)
748                 return r;
749
750         *sntp = c;
751         c = NULL;
752
753         return 0;
754 }
755
756 SNTPContext *sntp_unref(SNTPContext *sntp) {
757         sntp_server_disconnect(sntp);
758         free(sntp);
759         return NULL;
760 }