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