ntpd: fix "synced" state detection
[platform/upstream/busybox.git] / networking / ntpd.c
1 /*
2  * NTP client/server, based on OpenNTPD 3.9p1
3  *
4  * Author: Adam Tkac <vonsch@gmail.com>
5  *
6  * Licensed under GPLv2, see file LICENSE in this tarball for details.
7  */
8 #include "libbb.h"
9 #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
10 #ifndef IPTOS_LOWDELAY
11 # define IPTOS_LOWDELAY 0x10
12 #endif
13 #ifndef IP_PKTINFO
14 # error "Sorry, your kernel has to support IP_PKTINFO"
15 #endif
16
17 #define INTERVAL_QUERY_NORMAL           30      /* sync to peers every n secs */
18 #define INTERVAL_QUERY_PATHETIC         60
19 #define INTERVAL_QUERY_AGRESSIVE        5
20
21 #define TRUSTLEVEL_BADPEER              6       /* bad if *less than* TRUSTLEVEL_BADPEER */
22 #define TRUSTLEVEL_PATHETIC             2
23 #define TRUSTLEVEL_AGRESSIVE            8
24 #define TRUSTLEVEL_MAX                  10
25
26 #define QSCALE_OFF_MIN                  0.05
27 #define QSCALE_OFF_MAX                  0.50
28
29 #define QUERYTIME_MAX           15      /* single query might take n secs max */
30 #define OFFSET_ARRAY_SIZE       8
31 #define SETTIME_MIN_OFFSET      180     /* min offset for settime at start */
32 #define SETTIME_TIMEOUT         15      /* max seconds to wait with -s */
33
34 /* Style borrowed from NTP ref/tcpdump and updated for SNTPv4 (RFC2030). */
35
36 /*
37  * RFC Section 3
38  *
39  *    0                   1                   2                   3
40  *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
41  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
42  *   |                         Integer Part                          |
43  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
44  *   |                         Fraction Part                         |
45  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
46  *
47  *    0                   1                   2                   3
48  *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
49  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
50  *   |            Integer Part       |     Fraction Part             |
51  *   +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
52 */
53 typedef struct {
54         uint32_t int_partl;
55         uint32_t fractionl;
56 } l_fixedpt_t;
57
58 typedef struct {
59         uint16_t int_parts;
60         uint16_t fractions;
61 } s_fixedpt_t;
62
63 enum {
64         NTP_DIGESTSIZE     = 16,
65         NTP_MSGSIZE_NOAUTH = 48,
66         NTP_MSGSIZE        = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
67 };
68
69 typedef struct {
70         uint8_t     m_status;     /* status of local clock and leap info */
71         uint8_t     m_stratum;    /* stratum level */
72         uint8_t     m_ppoll;      /* poll value */
73         int8_t      m_precision;
74         s_fixedpt_t m_rootdelay;
75         s_fixedpt_t m_dispersion;
76         uint32_t    m_refid;
77         l_fixedpt_t m_reftime;
78         l_fixedpt_t m_orgtime;
79         l_fixedpt_t m_rectime;
80         l_fixedpt_t m_xmttime;
81         uint32_t    m_keyid;
82         uint8_t     m_digest[NTP_DIGESTSIZE];
83 } ntp_msg_t;
84
85 enum {
86         NTP_VERSION     = 4,
87         NTP_MAXSTRATUM  = 15,
88         /* Leap Second Codes (high order two bits) */
89         LI_NOWARNING    = (0 << 6),     /* no warning */
90         LI_PLUSSEC      = (1 << 6),     /* add a second (61 seconds) */
91         LI_MINUSSEC     = (2 << 6),     /* minus a second (59 seconds) */
92         LI_ALARM        = (3 << 6),     /* alarm condition */
93
94         /* Status Masks */
95         MODE_MASK       = (7 << 0),
96         VERSION_MASK    = (7 << 3),
97         VERSION_SHIFT   = 3,
98         LI_MASK         = (3 << 6),
99
100         /* Mode values */
101         MODE_RES0       = 0,    /* reserved */
102         MODE_SYM_ACT    = 1,    /* symmetric active */
103         MODE_SYM_PAS    = 2,    /* symmetric passive */
104         MODE_CLIENT     = 3,    /* client */
105         MODE_SERVER     = 4,    /* server */
106         MODE_BROADCAST  = 5,    /* broadcast */
107         MODE_RES1       = 6,    /* reserved for NTP control message */
108         MODE_RES2       = 7,    /* reserved for private use */
109 };
110
111 #define OFFSET_1900_1970 2208988800UL  /* 1970 - 1900 in seconds */
112
113 typedef struct {
114         double          o_offset;
115         double          o_delay;
116         //UNUSED: double                o_error;
117         time_t          o_rcvd;
118         uint32_t        o_refid4;
119         uint8_t         o_leap;
120         uint8_t         o_stratum;
121         uint8_t         o_good;
122 } ntp_offset_t;
123
124 typedef struct {
125 //TODO: periodically re-resolve DNS names?
126         len_and_sockaddr        *lsa;
127         char                    *dotted;
128         double                  xmttime;
129         time_t                  next;
130         time_t                  deadline;
131         int                     fd;
132         uint8_t                 state;
133         uint8_t                 shift;
134         uint8_t                 trustlevel;
135         ntp_msg_t               msg;
136         ntp_offset_t            update;
137         ntp_offset_t            reply[OFFSET_ARRAY_SIZE];
138 } ntp_peer_t;
139 /* for ntp_peer_t::state */
140 enum {
141         STATE_NONE,
142         STATE_QUERY_SENT,
143         STATE_REPLY_RECEIVED,
144 };
145
146 enum {
147         OPT_n = (1 << 0),
148         OPT_g = (1 << 1),
149         OPT_q = (1 << 2),
150         OPT_N = (1 << 3),
151         /* Insert new options above this line. */
152         /* Non-compat options: */
153         OPT_p = (1 << 4),
154         OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
155 };
156
157
158 struct globals {
159         double          rootdelay;
160         double          reftime;
161         llist_t         *ntp_peers;
162 #if ENABLE_FEATURE_NTPD_SERVER
163         int             listen_fd;
164 #endif
165         unsigned        verbose;
166         unsigned        peer_cnt;
167         uint32_t        refid;
168         uint32_t        refid4;
169         uint32_t        scale;
170         uint8_t         synced;
171         uint8_t         leap;
172         int8_t          precision;
173         uint8_t         stratum;
174         uint8_t         time_is_stepped;
175         uint8_t         first_adj_done;
176 };
177 #define G (*ptr_to_globals)
178
179
180 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
181
182
183 static void
184 set_next(ntp_peer_t *p, unsigned t)
185 {
186         p->next = time(NULL) + t;
187         p->deadline = 0;
188 }
189
190 static void
191 add_peers(const char *s)
192 {
193         ntp_peer_t *p;
194
195         p = xzalloc(sizeof(*p));
196 //TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
197         p->lsa = xhost2sockaddr(s, 123);
198         p->dotted = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
199         p->fd = -1;
200         p->msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
201         if (STATE_NONE != 0)
202                 p->state = STATE_NONE;
203         p->trustlevel = TRUSTLEVEL_PATHETIC;
204         set_next(p, 0);
205
206         llist_add_to(&G.ntp_peers, p);
207         G.peer_cnt++;
208 }
209
210 static double
211 gettime1900fp(void)
212 {
213         struct timeval tv;
214         gettimeofday(&tv, NULL); /* never fails */
215         return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
216 }
217
218 static void
219 d_to_tv(double d, struct timeval *tv)
220 {
221         tv->tv_sec = (long)d;
222         tv->tv_usec = (d - tv->tv_sec) * 1000000;
223 }
224
225 static double
226 lfp_to_d(l_fixedpt_t lfp)
227 {
228         double ret;
229         lfp.int_partl = ntohl(lfp.int_partl);
230         lfp.fractionl = ntohl(lfp.fractionl);
231         ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
232         return ret;
233 }
234
235 #if 0 //UNUSED
236 static double
237 sfp_to_d(s_fixedpt_t sfp)
238 {
239         double ret;
240         sfp.int_parts = ntohs(sfp.int_parts);
241         sfp.fractions = ntohs(sfp.fractions);
242         ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
243         return ret;
244 }
245 #endif
246
247 #if ENABLE_FEATURE_NTPD_SERVER
248 static l_fixedpt_t
249 d_to_lfp(double d)
250 {
251         l_fixedpt_t lfp;
252         lfp.int_partl = (uint32_t)d;
253         lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
254         lfp.int_partl = htonl(lfp.int_partl);
255         lfp.fractionl = htonl(lfp.fractionl);
256         return lfp;
257 }
258
259 static s_fixedpt_t
260 d_to_sfp(double d)
261 {
262         s_fixedpt_t sfp;
263         sfp.int_parts = (uint16_t)d;
264         sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
265         sfp.int_parts = htons(sfp.int_parts);
266         sfp.fractions = htons(sfp.fractions);
267         return sfp;
268 }
269 #endif
270
271 static void
272 set_deadline(ntp_peer_t *p, time_t t)
273 {
274         p->deadline = time(NULL) + t;
275         p->next = 0;
276 }
277
278 static unsigned
279 error_interval(void)
280 {
281         unsigned interval, r;
282         interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
283         r = (unsigned)random() % (unsigned)(interval / 10);
284         return (interval + r);
285 }
286
287 static int
288 do_sendto(int fd,
289                 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
290                 ntp_msg_t *msg, ssize_t len)
291 {
292         ssize_t ret;
293
294         errno = 0;
295         if (!from) {
296                 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
297         } else {
298                 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
299         }
300         if (ret != len) {
301                 bb_perror_msg("send failed");
302                 return -1;
303         }
304         return 0;
305 }
306
307 static int
308 send_query_to_peer(ntp_peer_t *p)
309 {
310         // Why do we need to bind()?
311         // See what happens when we don't bind:
312         //
313         // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
314         // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
315         // gettimeofday({1259071266, 327885}, NULL) = 0
316         // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
317         // ^^^ we sent it from some source port picked by kernel.
318         // time(NULL)              = 1259071266
319         // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
320         // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
321         // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
322         // ^^^ this recv will receive packets to any local port!
323         //
324         // Uncomment this and use strace to see it in action:
325 #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
326
327         if (p->fd == -1) {
328                 int fd, family;
329                 len_and_sockaddr *local_lsa;
330
331                 family = p->lsa->u.sa.sa_family;
332                 //was: p->fd = xsocket(family, SOCK_DGRAM, 0);
333                 p->fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
334                 /* local_lsa has "null" address and port 0 now.
335                  * bind() ensures we have a *particular port* selected by kernel
336                  * and remembered in p->fd, thus later recv(p->fd)
337                  * receives only packets sent to this port.
338                  */
339                 PROBE_LOCAL_ADDR
340                 xbind(fd, &local_lsa->u.sa, local_lsa->len);
341                 PROBE_LOCAL_ADDR
342 #if ENABLE_FEATURE_IPV6
343                 if (family == AF_INET)
344 #endif
345                         setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
346                 free(local_lsa);
347         }
348
349         /*
350          * Send out a random 64-bit number as our transmit time.  The NTP
351          * server will copy said number into the originate field on the
352          * response that it sends us.  This is totally legal per the SNTP spec.
353          *
354          * The impact of this is two fold: we no longer send out the current
355          * system time for the world to see (which may aid an attacker), and
356          * it gives us a (not very secure) way of knowing that we're not
357          * getting spoofed by an attacker that can't capture our traffic
358          * but can spoof packets from the NTP server we're communicating with.
359          *
360          * Save the real transmit timestamp locally.
361          */
362
363         p->msg.m_xmttime.int_partl = random();
364         p->msg.m_xmttime.fractionl = random();
365         p->xmttime = gettime1900fp();
366
367         if (do_sendto(p->fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
368                         &p->msg, NTP_MSGSIZE_NOAUTH) == -1
369         ) {
370                 set_next(p, INTERVAL_QUERY_PATHETIC);
371                 return -1;
372         }
373
374         if (G.verbose)
375                 bb_error_msg("sent query to %s", p->dotted);
376         p->state = STATE_QUERY_SENT;
377         set_deadline(p, QUERYTIME_MAX);
378
379         return 0;
380 }
381
382 static int
383 compare_offsets(const void *aa, const void *bb)
384 {
385         const ntp_peer_t *const *a = aa;
386         const ntp_peer_t *const *b = bb;
387         if ((*a)->update.o_offset < (*b)->update.o_offset)
388                 return -1;
389         return ((*a)->update.o_offset > (*b)->update.o_offset);
390 }
391
392 static uint32_t
393 updated_scale(double offset)
394 {
395         if (offset < 0)
396                 offset = -offset;
397         if (offset > QSCALE_OFF_MAX)
398                 return 1;
399         if (offset < QSCALE_OFF_MIN)
400                 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
401         return QSCALE_OFF_MAX / offset;
402 }
403
404 static void
405 slew_time(void)
406 {
407         ntp_peer_t       *p;
408         llist_t          *item;
409         unsigned          offset_cnt;
410         double            offset_median;
411         struct timeval    tv;
412
413         offset_cnt = 0;
414         for (item = G.ntp_peers; item != NULL; item = item->link) {
415                 p = (ntp_peer_t *) item->data;
416                 if (p->trustlevel < TRUSTLEVEL_BADPEER)
417                         continue;
418                 if (!p->update.o_good)
419                         return;
420                 offset_cnt++;
421         }
422
423         if (offset_cnt == 0)
424                 goto clear_good;
425
426         {
427                 len_and_sockaddr *lsa;
428                 unsigned middle;
429                 unsigned i = 0;
430                 ntp_peer_t **peers = xzalloc(sizeof(peers[0]) * offset_cnt);
431
432                 for (item = G.ntp_peers; item != NULL; item = item->link) {
433                         p = (ntp_peer_t *) item->data;
434                         if (p->trustlevel < TRUSTLEVEL_BADPEER)
435                                 continue;
436                         peers[i++] = p;
437                 }
438
439                 qsort(peers, offset_cnt, sizeof(peers[0]), compare_offsets);
440
441                 middle = offset_cnt / 2;
442                 if (middle != 0 && (offset_cnt & 1) == 0) {
443                         offset_median = (peers[middle-1]->update.o_offset + peers[middle]->update.o_offset) / 2;
444                         G.rootdelay = (peers[middle-1]->update.o_delay + peers[middle]->update.o_delay) / 2;
445                         G.stratum = 1 + MAX(peers[middle-1]->update.o_stratum, peers[middle]->update.o_stratum);
446                 } else {
447                         offset_median = peers[middle]->update.o_offset;
448                         G.rootdelay = peers[middle]->update.o_delay;
449                         G.stratum = 1 + peers[middle]->update.o_stratum;
450                 }
451                 G.leap = peers[middle]->update.o_leap;
452                 G.refid4 = peers[middle]->update.o_refid4;
453                 lsa = peers[middle]->lsa;
454                 G.refid =
455 #if ENABLE_FEATURE_IPV6
456                         lsa->u.sa.sa_family != AF_INET ?
457                                 G.refid4 :
458 #endif
459                                 lsa->u.sin.sin_addr.s_addr;
460                 free(peers);
461         }
462
463         bb_error_msg("adjusting clock by %fs, our stratum is %u", offset_median, G.stratum);
464
465         errno = 0;
466         d_to_tv(offset_median, &tv);
467         if (adjtime(&tv, &tv) == -1) {
468                 bb_perror_msg("adjtime failed"); //TODO: maybe _and_die?
469         } else {
470                 if (G.verbose >= 2)
471                         bb_error_msg("old adjust: %d.%06u", (int)tv.tv_sec, (unsigned)tv.tv_usec);
472                 if (G.first_adj_done) {
473                         uint8_t synced = (tv.tv_sec == 0 && tv.tv_usec == 0);
474                         if (synced != G.synced) {
475                                 G.synced = synced;
476                                 bb_error_msg("clock is %ssynced", synced ? "" : "un");
477                         }
478                 }
479                 G.first_adj_done = 1;
480         }
481
482         G.reftime = gettime1900fp();
483         G.scale = updated_scale(offset_median);
484
485  clear_good:
486         for (item = G.ntp_peers; item != NULL; item = item->link) {
487                 p = (ntp_peer_t *) item->data;
488                 p->update.o_good = 0;
489         }
490 }
491
492 static void
493 step_time_once(double offset)
494 {
495         ntp_peer_t *p;
496         llist_t *item;
497         struct timeval tv;
498         char buf[80];
499         time_t tval;
500
501         if (G.time_is_stepped)
502                 goto bail;
503         G.time_is_stepped = 1;
504
505         /* if the offset is small, don't call settimeofday */
506         if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
507                 goto bail;
508
509         gettimeofday(&tv, NULL); /* never fails */
510         offset += tv.tv_sec;
511         offset += 1.0e-6 * tv.tv_usec;
512         d_to_tv(offset, &tv);
513
514         if (settimeofday(&tv, NULL) == -1) {
515                 bb_error_msg("settimeofday");
516                 goto bail;
517         }
518
519         tval = tv.tv_sec;
520         strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
521
522 // Do we want to print message below to system log when daemonized?
523         bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
524
525         for (item = G.ntp_peers; item != NULL; item = item->link) {
526                 p = (ntp_peer_t *) item->data;
527                 if (p->next)
528                         p->next -= offset;
529                 if (p->deadline)
530                         p->deadline -= offset;
531         }
532
533  bail:
534         if (option_mask32 & OPT_q)
535                 exit(0);
536 }
537
538 static void
539 update_peer_data(ntp_peer_t *p)
540 {
541         /* Clock filter.
542          * Find the offset which arrived with the lowest delay.
543          * Use that as the peer update.
544          * Invalidate it and all older ones.
545          */
546         int i;
547         int best = best; /* for compiler */
548         int good;
549
550         good = 0;
551         for (i = 0; i < OFFSET_ARRAY_SIZE; i++) {
552                 if (p->reply[i].o_good) {
553                         good++;
554                         best = i++;
555                         break;
556                 }
557         }
558
559         for (; i < OFFSET_ARRAY_SIZE; i++) {
560                 if (p->reply[i].o_good) {
561                         good++;
562                         if (p->reply[i].o_delay < p->reply[best].o_delay)
563                                 best = i;
564                 }
565         }
566
567         if (good < 8) //FIXME: was it meant to be OFFSET_ARRAY_SIZE, not 8?
568                 return;
569
570         memcpy(&p->update, &p->reply[best], sizeof(p->update));
571         slew_time();
572
573         for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
574                 if (p->reply[i].o_rcvd <= p->reply[best].o_rcvd)
575                         p->reply[i].o_good = 0;
576 }
577
578 static unsigned
579 scale_interval(unsigned requested)
580 {
581         unsigned interval, r;
582         interval = requested * G.scale;
583         r = (unsigned)random() % (unsigned)(MAX(5, interval / 10));
584         return (interval + r);
585 }
586
587 static void
588 recv_and_process_peer_pkt(ntp_peer_t *p)
589 {
590         ssize_t                  size;
591         ntp_msg_t                msg;
592         double                   T1, T2, T3, T4;
593         unsigned                 interval;
594         ntp_offset_t            *offset;
595
596         /* We can recvfrom here and check from.IP, but some multihomed
597          * ntp servers reply from their *other IP*.
598          * TODO: maybe we should check at least what we can: from.port == 123?
599          */
600         size = recv(p->fd, &msg, sizeof(msg), MSG_DONTWAIT);
601         if (size == -1) {
602                 bb_perror_msg("recv(%s) error", p->dotted);
603                 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
604                  || errno == ENETUNREACH || errno == ENETDOWN
605                  || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
606                  || errno == EAGAIN
607                 ) {
608 //TODO: always do this?
609                         set_next(p, error_interval());
610                         goto close_sock;
611                 }
612                 xfunc_die();
613         }
614
615         T4 = gettime1900fp();
616
617         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
618                 bb_error_msg("malformed packet received from %s", p->dotted);
619                 goto bail;
620         }
621
622         if (msg.m_orgtime.int_partl != p->msg.m_xmttime.int_partl
623          || msg.m_orgtime.fractionl != p->msg.m_xmttime.fractionl
624         ) {
625                 goto bail;
626         }
627
628         if ((msg.m_status & LI_ALARM) == LI_ALARM
629          || msg.m_stratum == 0
630          || msg.m_stratum > NTP_MAXSTRATUM
631         ) {
632                 interval = error_interval();
633                 bb_error_msg("reply from %s: not synced, next query in %us", p->dotted, interval);
634                 goto close_sock;
635         }
636
637         /*
638          * From RFC 2030 (with a correction to the delay math):
639          *
640          *     Timestamp Name          ID   When Generated
641          *     ------------------------------------------------------------
642          *     Originate Timestamp     T1   time request sent by client
643          *     Receive Timestamp       T2   time request received by server
644          *     Transmit Timestamp      T3   time reply sent by server
645          *     Destination Timestamp   T4   time reply received by client
646          *
647          *  The roundtrip delay d and local clock offset t are defined as
648          *
649          *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
650          */
651
652         T1 = p->xmttime;
653         T2 = lfp_to_d(msg.m_rectime);
654         T3 = lfp_to_d(msg.m_xmttime);
655
656         offset = &p->reply[p->shift];
657
658         offset->o_offset = ((T2 - T1) + (T3 - T4)) / 2;
659         offset->o_delay = (T4 - T1) - (T3 - T2);
660         if (offset->o_delay < 0) {
661                 interval = error_interval();
662                 set_next(p, interval);
663                 bb_error_msg("reply from %s: negative delay %f", p->dotted, p->reply[p->shift].o_delay);
664                 goto close_sock;
665         }
666         //UNUSED: offset->o_error = (T2 - T1) - (T3 - T4);
667 // Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
668         offset->o_rcvd = time(NULL);
669         offset->o_good = 1;
670
671         offset->o_leap = (msg.m_status & LI_MASK);
672         //UNUSED: offset->o_precision = msg.m_precision;
673         //UNUSED: offset->o_rootdelay = sfp_to_d(msg.m_rootdelay);
674         //UNUSED: offset->o_rootdispersion = sfp_to_d(msg.m_dispersion);
675         //UNUSED: offset->o_refid = ntohl(msg.m_refid);
676         offset->o_refid4 = msg.m_xmttime.fractionl;
677         //UNUSED: offset->o_reftime = lfp_to_d(msg.m_reftime);
678         //UNUSED: offset->o_poll = msg.m_ppoll;
679         offset->o_stratum = msg.m_stratum;
680
681         if (p->trustlevel < TRUSTLEVEL_PATHETIC)
682                 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
683         else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
684                 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
685         else
686                 interval = scale_interval(INTERVAL_QUERY_NORMAL);
687
688         set_next(p, interval);
689         p->state = STATE_REPLY_RECEIVED;
690
691         /* every received reply which we do not discard increases trust */
692         if (p->trustlevel < TRUSTLEVEL_MAX) {
693                 p->trustlevel++;
694                 if (p->trustlevel == TRUSTLEVEL_BADPEER)
695                         bb_error_msg("peer %s now valid", p->dotted);
696         }
697
698         if (G.verbose)
699                 bb_error_msg("reply from %s: offset %f delay %f, next query in %us", p->dotted,
700                         offset->o_offset, offset->o_delay, interval);
701
702         update_peer_data(p);
703 //TODO: do it after all peers had a chance to return at least one reply?
704         step_time_once(offset->o_offset);
705
706         p->shift++;
707         if (p->shift >= OFFSET_ARRAY_SIZE)
708                 p->shift = 0;
709
710  close_sock:
711         /* We do not expect any more packets for now.
712          * Closing the socket informs kernel about it.
713          * We open a new socket when we send a new query.
714          */
715         close(p->fd);
716         p->fd = -1;
717  bail:
718         return;
719 }
720
721 #if ENABLE_FEATURE_NTPD_SERVER
722 static void
723 recv_and_process_client_pkt(void /*int fd*/)
724 {
725         ssize_t          size;
726         uint8_t          version;
727         double           rectime;
728         len_and_sockaddr *to;
729         struct sockaddr  *from;
730         ntp_msg_t        msg;
731         uint8_t          query_status;
732         uint8_t          query_ppoll;
733         l_fixedpt_t      query_xmttime;
734
735         to = get_sock_lsa(G.listen_fd);
736         from = xzalloc(to->len);
737
738         size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
739         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
740                 char *addr;
741                 if (size < 0) {
742                         if (errno == EAGAIN)
743                                 goto bail;
744                         bb_perror_msg_and_die("recv_from_to");
745                 }
746                 addr = xmalloc_sockaddr2dotted_noport(from);
747                 bb_error_msg("malformed packet received from %s", addr);
748                 free(addr);
749                 goto bail;
750         }
751
752         query_status = msg.m_status;
753         query_ppoll = msg.m_ppoll;
754         query_xmttime = msg.m_xmttime;
755
756         /* Build a reply packet */
757         memset(&msg, 0, sizeof(msg));
758         msg.m_status = G.synced ? G.leap : LI_ALARM;
759         msg.m_status |= (query_status & VERSION_MASK);
760         msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
761                          MODE_SERVER : MODE_SYM_PAS;
762         msg.m_stratum = G.stratum;
763         msg.m_ppoll = query_ppoll;
764         msg.m_precision = G.precision;
765         rectime = gettime1900fp();
766         msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
767         msg.m_reftime = d_to_lfp(G.reftime);
768         //msg.m_xmttime = d_to_lfp(gettime1900fp()); // = msg.m_rectime
769         msg.m_orgtime = query_xmttime;
770         msg.m_rootdelay = d_to_sfp(G.rootdelay);
771         version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
772         msg.m_refid = (version > (3 << VERSION_SHIFT)) ? G.refid4 : G.refid;
773
774         /* We reply from the local address packet was sent to,
775          * this makes to/from look swapped here: */
776         do_sendto(G.listen_fd,
777                 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
778                 &msg, size);
779
780  bail:
781         free(to);
782         free(from);
783 }
784 #endif
785
786 /* Upstream ntpd's options:
787  *
788  * -4   Force DNS resolution of host names to the IPv4 namespace.
789  * -6   Force DNS resolution of host names to the IPv6 namespace.
790  * -a   Require cryptographic authentication for broadcast client,
791  *      multicast client and symmetric passive associations.
792  *      This is the default.
793  * -A   Do not require cryptographic authentication for broadcast client,
794  *      multicast client and symmetric passive associations.
795  *      This is almost never a good idea.
796  * -b   Enable the client to synchronize to broadcast servers.
797  * -c conffile
798  *      Specify the name and path of the configuration file,
799  *      default /etc/ntp.conf
800  * -d   Specify debugging mode. This option may occur more than once,
801  *      with each occurrence indicating greater detail of display.
802  * -D level
803  *      Specify debugging level directly.
804  * -f driftfile
805  *      Specify the name and path of the frequency file.
806  *      This is the same operation as the "driftfile FILE"
807  *      configuration command.
808  * -g   Normally, ntpd exits with a message to the system log
809  *      if the offset exceeds the panic threshold, which is 1000 s
810  *      by default. This option allows the time to be set to any value
811  *      without restriction; however, this can happen only once.
812  *      If the threshold is exceeded after that, ntpd will exit
813  *      with a message to the system log. This option can be used
814  *      with the -q and -x options. See the tinker command for other options.
815  * -i jaildir
816  *      Chroot the server to the directory jaildir. This option also implies
817  *      that the server attempts to drop root privileges at startup
818  *      (otherwise, chroot gives very little additional security).
819  *      You may need to also specify a -u option.
820  * -k keyfile
821  *      Specify the name and path of the symmetric key file,
822  *      default /etc/ntp/keys. This is the same operation
823  *      as the "keys FILE" configuration command.
824  * -l logfile
825  *      Specify the name and path of the log file. The default
826  *      is the system log file. This is the same operation as
827  *      the "logfile FILE" configuration command.
828  * -L   Do not listen to virtual IPs. The default is to listen.
829  * -n   Don't fork.
830  * -N   To the extent permitted by the operating system,
831  *      run the ntpd at the highest priority.
832  * -p pidfile
833  *      Specify the name and path of the file used to record the ntpd
834  *      process ID. This is the same operation as the "pidfile FILE"
835  *      configuration command.
836  * -P priority
837  *      To the extent permitted by the operating system,
838  *      run the ntpd at the specified priority.
839  * -q   Exit the ntpd just after the first time the clock is set.
840  *      This behavior mimics that of the ntpdate program, which is
841  *      to be retired. The -g and -x options can be used with this option.
842  *      Note: The kernel time discipline is disabled with this option.
843  * -r broadcastdelay
844  *      Specify the default propagation delay from the broadcast/multicast
845  *      server to this client. This is necessary only if the delay
846  *      cannot be computed automatically by the protocol.
847  * -s statsdir
848  *      Specify the directory path for files created by the statistics
849  *      facility. This is the same operation as the "statsdir DIR"
850  *      configuration command.
851  * -t key
852  *      Add a key number to the trusted key list. This option can occur
853  *      more than once.
854  * -u user[:group]
855  *      Specify a user, and optionally a group, to switch to.
856  * -v variable
857  * -V variable
858  *      Add a system variable listed by default.
859  * -x   Normally, the time is slewed if the offset is less than the step
860  *      threshold, which is 128 ms by default, and stepped if above
861  *      the threshold. This option sets the threshold to 600 s, which is
862  *      well within the accuracy window to set the clock manually.
863  *      Note: since the slew rate of typical Unix kernels is limited
864  *      to 0.5 ms/s, each second of adjustment requires an amortization
865  *      interval of 2000 s. Thus, an adjustment as much as 600 s
866  *      will take almost 14 days to complete. This option can be used
867  *      with the -g and -q options. See the tinker command for other options.
868  *      Note: The kernel time discipline is disabled with this option.
869  */
870
871 /* By doing init in a separate function we decrease stack usage
872  * in main loop.
873  */
874 static NOINLINE void ntp_init(char **argv)
875 {
876         unsigned opts;
877         llist_t *peers;
878
879         srandom(getpid());
880         /* tzset(); - why? it's called automatically when needed, no? */
881
882         if (getuid())
883                 bb_error_msg_and_die(bb_msg_you_must_be_root);
884
885         peers = NULL;
886         opt_complementary = "dd:p::"; /* d: counter, p: list */
887         opts = getopt32(argv,
888                         "ngqN" /* compat */
889                         "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
890                         "d" /* compat */
891                         "46aAbLx", /* compat, ignored */
892                         &peers, &G.verbose);
893         if (!(opts & (OPT_p|OPT_l)))
894                 bb_show_usage();
895 //WRONG
896 //      if (opts & OPT_g)
897 //              G.time_is_stepped = 1;
898         while (peers)
899                 add_peers(llist_pop(&peers));
900         if (!(opts & OPT_n)) {
901                 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
902                 logmode = LOGMODE_NONE;
903         }
904 #if ENABLE_FEATURE_NTPD_SERVER
905         G.listen_fd = -1;
906         if (opts & OPT_l) {
907                 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
908                 socket_want_pktinfo(G.listen_fd);
909                 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
910         }
911 #endif
912         /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
913         if (opts & OPT_N)
914                 setpriority(PRIO_PROCESS, 0, -15);
915
916         /* Set some globals */
917         {
918                 int prec = 0;
919                 int b;
920 #if 0
921                 struct timespec tp;
922                 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
923                 clock_getres(CLOCK_REALTIME, &tp);
924                 tp.tv_sec = 0;
925                 tp.tv_nsec = 10000000;
926                 b = 1000000000 / tp.tv_nsec;    /* convert to Hz */
927 #else
928                 b = 100; /* b = 1000000000/10000000 = 100 */
929 #endif
930                 while (b > 1)
931                         prec--, b >>= 1;
932                 G.precision = prec;
933         }
934         G.scale = 1;
935
936         bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
937         bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
938 }
939
940 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
941 int ntpd_main(int argc UNUSED_PARAM, char **argv)
942 {
943         struct globals g;
944         struct pollfd *pfd;
945         ntp_peer_t **idx2peer;
946
947         memset(&g, 0, sizeof(g));
948         SET_PTR_TO_GLOBALS(&g);
949
950         ntp_init(argv);
951
952         {
953                 unsigned cnt = g.peer_cnt;
954                 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
955                 idx2peer = xzalloc(sizeof(void *) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
956                 pfd = xzalloc(sizeof(pfd[0]) * (cnt + ENABLE_FEATURE_NTPD_SERVER));
957         }
958
959         while (!bb_got_signal) {
960                 llist_t *item;
961                 unsigned i, j;
962                 unsigned sent_cnt, trial_cnt;
963                 int nfds, timeout;
964                 time_t cur_time, nextaction;
965
966                 /* Nothing between here and poll() blocks for any significant time */
967
968                 cur_time = time(NULL);
969                 nextaction = cur_time + 3600;
970
971                 i = 0;
972 #if ENABLE_FEATURE_NTPD_SERVER
973                 if (g.listen_fd != -1) {
974                         pfd[0].fd = g.listen_fd;
975                         pfd[0].events = POLLIN;
976                         i++;
977                 }
978 #endif
979                 /* Pass over peer list, send requests, time out on receives */
980                 sent_cnt = trial_cnt = 0;
981                 for (item = g.ntp_peers; item != NULL; item = item->link) {
982                         ntp_peer_t *p = (ntp_peer_t *) item->data;
983
984                         if (p->next != 0 && p->next <= cur_time) {
985                                 /* Time to send new req */
986                                 trial_cnt++;
987                                 if (send_query_to_peer(p) == 0)
988                                         sent_cnt++;
989                         }
990                         if (p->deadline != 0 && p->deadline <= cur_time) {
991                                 /* Timed out waiting for reply */
992                                 timeout = error_interval();
993                                 bb_error_msg("timed out waiting for %s, "
994                                                 "next query in %us", p->dotted, timeout);
995                                 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
996                                         p->trustlevel /= 2;
997                                         if (p->trustlevel < TRUSTLEVEL_BADPEER)
998                                                 bb_error_msg("peer %s now invalid", p->dotted);
999                                 }
1000                                 set_next(p, timeout);
1001                         }
1002
1003                         if (p->next != 0 && p->next < nextaction)
1004                                 nextaction = p->next;
1005                         if (p->deadline != 0 && p->deadline < nextaction)
1006                                 nextaction = p->deadline;
1007
1008                         if (p->state == STATE_QUERY_SENT) {
1009                                 /* Wait for reply from this peer */
1010                                 pfd[i].fd = p->fd;
1011                                 pfd[i].events = POLLIN;
1012                                 idx2peer[i] = p;
1013                                 i++;
1014                         }
1015                 }
1016
1017                 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
1018                         step_time_once(0); /* no good peers, don't wait */
1019
1020                 timeout = nextaction - cur_time;
1021                 if (timeout < 1)
1022                         timeout = 1;
1023
1024                 /* Here we may block */
1025                 if (g.verbose >= 2)
1026                         bb_error_msg("poll %u sec, sockets:%u", timeout, i);
1027                 nfds = poll(pfd, i, timeout * 1000);
1028                 if (nfds <= 0)
1029                         continue;
1030
1031                 /* Process any received packets */
1032                 j = 0;
1033 #if ENABLE_FEATURE_NTPD_SERVER
1034                 if (g.listen_fd != -1) {
1035                         if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1036                                 nfds--;
1037                                 recv_and_process_client_pkt(/*g.listen_fd*/);
1038                         }
1039                         j = 1;
1040                 }
1041 #endif
1042                 for (; nfds != 0 && j < i; j++) {
1043                         if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1044                                 nfds--;
1045                                 recv_and_process_peer_pkt(idx2peer[j]);
1046                         }
1047                 }
1048         } /* while (!bb_got_signal) */
1049
1050         kill_myself_with_sig(bb_got_signal);
1051 }