e2c3506ed53fcabf258fa2201dfc5a726ca92720
[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 #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     status;     /* status of local clock and leap info */
71         uint8_t     stratum;    /* stratum level */
72         uint8_t     ppoll;      /* poll value */
73         int8_t      precision;
74         s_fixedpt_t rootdelay;
75         s_fixedpt_t dispersion;
76         uint32_t    refid;
77         l_fixedpt_t reftime;
78         l_fixedpt_t orgtime;
79         l_fixedpt_t rectime;
80         l_fixedpt_t xmttime;
81         uint32_t    keyid;
82         uint8_t     digest[NTP_DIGESTSIZE];
83 } ntp_msg_t;
84
85 typedef struct {
86         int       fd;
87         ntp_msg_t msg;
88         double    xmttime;
89 } ntp_query_t;
90
91 enum {
92         NTP_VERSION     = 4,
93         NTP_MAXSTRATUM  = 15,
94         /* Leap Second Codes (high order two bits) */
95         LI_NOWARNING    = (0 << 6),     /* no warning */
96         LI_PLUSSEC      = (1 << 6),     /* add a second (61 seconds) */
97         LI_MINUSSEC     = (2 << 6),     /* minus a second (59 seconds) */
98         LI_ALARM        = (3 << 6),     /* alarm condition */
99
100         /* Status Masks */
101         MODE_MASK       = (7 << 0),
102         VERSION_MASK    = (7 << 3),
103         VERSION_SHIFT   = 3,
104         LI_MASK         = (3 << 6),
105
106         /* Mode values */
107         MODE_RES0       = 0,    /* reserved */
108         MODE_SYM_ACT    = 1,    /* symmetric active */
109         MODE_SYM_PAS    = 2,    /* symmetric passive */
110         MODE_CLIENT     = 3,    /* client */
111         MODE_SERVER     = 4,    /* server */
112         MODE_BROADCAST  = 5,    /* broadcast */
113         MODE_RES1       = 6,    /* reserved for NTP control message */
114         MODE_RES2       = 7,    /* reserved for private use */
115 };
116
117 #define OFFSET_1900_1970 2208988800UL  /* 1970 - 1900 in seconds */
118
119 enum client_state {
120         STATE_NONE,
121         STATE_QUERY_SENT,
122         STATE_REPLY_RECEIVED,
123 };
124
125 typedef struct {
126         double          rootdelay;
127         double          rootdispersion;
128         double          reftime;
129         uint32_t        refid;
130         uint32_t        refid4;
131         uint8_t         synced;
132         uint8_t         leap;
133         int8_t          precision;
134         uint8_t         poll;
135         uint8_t         stratum;
136 } ntp_status_t;
137
138 typedef struct {
139         ntp_status_t    status;
140         double          offset;
141         double          delay;
142         double          error;
143         time_t          rcvd;
144         uint8_t         good;
145 } ntp_offset_t;
146
147 typedef struct {
148 //TODO:
149 // (1) store dotted addr str, to avoid constant translations
150 // (2) periodically re-resolve DNS names
151         len_and_sockaddr        *lsa;
152         ntp_query_t             query;
153         ntp_offset_t            reply[OFFSET_ARRAY_SIZE];
154         ntp_offset_t            update;
155         enum client_state       state;
156         time_t                  next;
157         time_t                  deadline;
158         uint8_t                 shift;
159         uint8_t                 trustlevel;
160 } ntp_peer_t;
161
162 enum {
163         OPT_n = (1 << 0),
164         OPT_g = (1 << 1),
165         OPT_q = (1 << 2),
166         OPT_N = (1 << 3),
167         /* Insert new options above this line. */
168         /* Non-compat options: */
169         OPT_p = (1 << 4),
170         OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
171 };
172
173
174 struct globals {
175         unsigned        verbose;
176 #if ENABLE_FEATURE_NTPD_SERVER
177         int             listen_fd;
178 #endif
179         unsigned        peer_cnt;
180         llist_t         *ntp_peers;
181         ntp_status_t    status;
182         uint32_t        scale;
183         uint8_t         settime;
184         uint8_t         firstadj;
185 };
186 #define G (*ptr_to_globals)
187
188
189 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
190
191
192 static void
193 set_next(ntp_peer_t *p, time_t t)
194 {
195         p->next = time(NULL) + t;
196         p->deadline = 0;
197 }
198
199 static void
200 add_peers(const char *s)
201 {
202         ntp_peer_t *p;
203
204         p = xzalloc(sizeof(*p));
205 //TODO: big ntpd uses all IPs, not just 1st, do we need to mimic that?
206         p->lsa = xhost2sockaddr(s, 123);
207         p->query.fd = -1;
208         p->query.msg.status = MODE_CLIENT | (NTP_VERSION << 3);
209         if (STATE_NONE != 0)
210                 p->state = STATE_NONE;
211         p->trustlevel = TRUSTLEVEL_PATHETIC;
212         p->query.fd = -1;
213         set_next(p, 0);
214
215         llist_add_to(&G.ntp_peers, p);
216         G.peer_cnt++;
217 }
218
219 static double
220 gettime1900fp(void)
221 {
222         struct timeval tv;
223         gettimeofday(&tv, NULL); /* never fails */
224         return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
225 }
226
227 static void
228 d_to_tv(double d, struct timeval *tv)
229 {
230         tv->tv_sec = (long)d;
231         tv->tv_usec = (d - tv->tv_sec) * 1000000;
232 }
233
234 static double
235 lfp_to_d(l_fixedpt_t lfp)
236 {
237         double ret;
238         lfp.int_partl = ntohl(lfp.int_partl);
239         lfp.fractionl = ntohl(lfp.fractionl);
240         ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
241         return ret;
242 }
243
244 static double
245 sfp_to_d(s_fixedpt_t sfp)
246 {
247         double ret;
248         sfp.int_parts = ntohs(sfp.int_parts);
249         sfp.fractions = ntohs(sfp.fractions);
250         ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
251         return ret;
252 }
253
254 #if ENABLE_FEATURE_NTPD_SERVER
255 static l_fixedpt_t
256 d_to_lfp(double d)
257 {
258         l_fixedpt_t lfp;
259         lfp.int_partl = (uint32_t)d;
260         lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
261         lfp.int_partl = htonl(lfp.int_partl);
262         lfp.fractionl = htonl(lfp.fractionl);
263         return lfp;
264 }
265
266 static s_fixedpt_t
267 d_to_sfp(double d)
268 {
269         s_fixedpt_t sfp;
270         sfp.int_parts = (uint16_t)d;
271         sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
272         sfp.int_parts = htons(sfp.int_parts);
273         sfp.fractions = htons(sfp.fractions);
274         return sfp;
275 }
276 #endif
277
278 static void
279 set_deadline(ntp_peer_t *p, time_t t)
280 {
281         p->deadline = time(NULL) + t;
282         p->next = 0;
283 }
284
285 static time_t
286 error_interval(void)
287 {
288         time_t interval, r;
289         interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
290         r = (unsigned)random() % (unsigned long)(interval / 10);
291         return (interval + r);
292 }
293
294 static int
295 sendmsg_wrap(int fd,
296                 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
297                 ntp_msg_t *msg, ssize_t len)
298 {
299         ssize_t ret;
300
301         errno = 0;
302         if (!from) {
303                 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
304         } else {
305                 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
306         }
307         if (ret != len) {
308                 bb_perror_msg("send failed");
309                 return -1;
310         }
311         return 0;
312 }
313
314 static int
315 send_query_to_peer(ntp_peer_t *p)
316 {
317         // Why do we need to bind()?
318         // See what happens when we don't bind:
319         //
320         // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
321         // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
322         // gettimeofday({1259071266, 327885}, NULL) = 0
323         // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
324         // ^^^ we sent it from some source port picked by kernel.
325         // time(NULL)              = 1259071266
326         // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
327         // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
328         // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
329         // ^^^ this recv will receive packets to any local port!
330         //
331         // Uncomment this and use strace to see it in action:
332 #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
333
334         if (p->query.fd == -1) {
335                 int fd, family;
336                 len_and_sockaddr *local_lsa;
337
338                 family = p->lsa->u.sa.sa_family;
339                 //was: p->query.fd = xsocket(family, SOCK_DGRAM, 0);
340                 p->query.fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
341                 /* local_lsa has "null" address and port 0 now.
342                  * bind() ensures we have a *particular port* selected by kernel
343                  * and remembered in p->query.fd, thus later recv(p->query.fd)
344                  * receives only packets sent to this port.
345                  */
346                 PROBE_LOCAL_ADDR
347                 xbind(fd, &local_lsa->u.sa, local_lsa->len);
348                 PROBE_LOCAL_ADDR
349 #if ENABLE_FEATURE_IPV6
350                 if (family == AF_INET)
351 #endif
352                         setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
353                 free(local_lsa);
354         }
355
356         /*
357          * Send out a random 64-bit number as our transmit time.  The NTP
358          * server will copy said number into the originate field on the
359          * response that it sends us.  This is totally legal per the SNTP spec.
360          *
361          * The impact of this is two fold: we no longer send out the current
362          * system time for the world to see (which may aid an attacker), and
363          * it gives us a (not very secure) way of knowing that we're not
364          * getting spoofed by an attacker that can't capture our traffic
365          * but can spoof packets from the NTP server we're communicating with.
366          *
367          * Save the real transmit timestamp locally.
368          */
369
370         p->query.msg.xmttime.int_partl = random();
371         p->query.msg.xmttime.fractionl = random();
372         p->query.xmttime = gettime1900fp();
373
374         if (sendmsg_wrap(p->query.fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
375                         &p->query.msg, NTP_MSGSIZE_NOAUTH) == -1) {
376                 set_next(p, INTERVAL_QUERY_PATHETIC);
377                 return -1;
378         }
379
380         p->state = STATE_QUERY_SENT;
381         set_deadline(p, QUERYTIME_MAX);
382
383         return 0;
384 }
385
386 static int
387 offset_compare(const void *aa, const void *bb)
388 {
389         const ntp_peer_t *const *a = aa;
390         const ntp_peer_t *const *b = bb;
391         if ((*a)->update.offset < (*b)->update.offset)
392                 return -1;
393         return ((*a)->update.offset > (*b)->update.offset);
394 }
395
396 static uint32_t
397 updated_scale(double offset)
398 {
399         if (offset < 0)
400                 offset = -offset;
401         if (offset > QSCALE_OFF_MAX)
402                 return 1;
403         if (offset < QSCALE_OFF_MIN)
404                 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
405         return QSCALE_OFF_MAX / offset;
406 }
407
408 static void
409 adjtime_wrap(void)
410 {
411         ntp_peer_t       *p;
412         unsigned          offset_cnt;
413         unsigned          middle;
414         int               i = 0;
415         ntp_peer_t      **peers;
416         double            offset_median;
417         llist_t          *item;
418         len_and_sockaddr *lsa;
419         struct timeval    tv, olddelta;
420
421         offset_cnt = 0;
422         for (item = G.ntp_peers; item != NULL; item = item->link) {
423                 p = (ntp_peer_t *) item->data;
424                 if (p->trustlevel < TRUSTLEVEL_BADPEER)
425                         continue;
426                 if (!p->update.good)
427                         return;
428                 offset_cnt++;
429         }
430
431         if (offset_cnt == 0)
432                 goto clear_good;
433
434         peers = xzalloc(sizeof(peers[0]) * offset_cnt);
435         for (item = G.ntp_peers; item != NULL; item = item->link) {
436                 p = (ntp_peer_t *) item->data;
437                 if (p->trustlevel < TRUSTLEVEL_BADPEER)
438                         continue;
439                 peers[i++] = p;
440         }
441
442         qsort(peers, offset_cnt, sizeof(peers[0]), offset_compare);
443
444         middle = offset_cnt / 2;
445         if ((offset_cnt & 1) == 0 && middle != 0) {
446                 offset_median = (peers[middle-1]->update.offset + peers[middle]->update.offset) / 2;
447                 G.status.rootdelay = (peers[middle-1]->update.delay + peers[middle]->update.delay) / 2;
448                 G.status.stratum = MAX(peers[middle-1]->update.status.stratum, peers[middle]->update.status.stratum);
449         } else {
450                 offset_median = peers[middle]->update.offset;
451                 G.status.rootdelay = peers[middle]->update.delay;
452                 G.status.stratum = peers[middle]->update.status.stratum;
453         }
454         G.status.leap = peers[middle]->update.status.leap;
455
456         bb_info_msg("adjusting local clock by %fs", offset_median);
457
458         d_to_tv(offset_median, &tv);
459         if (adjtime(&tv, &olddelta) == -1)
460                 bb_error_msg("adjtime failed");
461         else if (!G.firstadj
462          && olddelta.tv_sec == 0
463          && olddelta.tv_usec == 0
464          && !G.status.synced
465         ) {
466                 bb_info_msg("clock synced");
467                 G.status.synced = 1;
468         } else if (G.status.synced) {
469                 bb_info_msg("clock unsynced");
470                 G.status.synced = 0;
471         }
472
473         G.firstadj = 0;
474         G.status.reftime = gettime1900fp();
475         G.status.stratum++;     /* one more than selected peer */
476         G.scale = updated_scale(offset_median);
477
478         G.status.refid4 = peers[middle]->update.status.refid4;
479
480         lsa = peers[middle]->lsa;
481         G.status.refid =
482 #if ENABLE_FEATURE_IPV6
483                 lsa->u.sa.sa_family != AF_INET ?
484                         G.status.refid4 :
485 #endif
486                         lsa->u.sin.sin_addr.s_addr;
487
488         free(peers);
489
490  clear_good:
491         for (item = G.ntp_peers; item != NULL; item = item->link) {
492                 p = (ntp_peer_t *) item->data;
493                 p->update.good = 0;
494         }
495 }
496
497 static void
498 settime(double offset)
499 {
500         ntp_peer_t *p;
501         llist_t         *item;
502         struct timeval  tv, curtime;
503         char            buf[80];
504         time_t          tval;
505
506         if (!G.settime)
507                 goto bail;
508
509         G.settime = 0;
510
511         /* if the offset is small, don't call settimeofday */
512         if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
513                 goto bail;
514
515         gettimeofday(&curtime, NULL); /* never fails */
516
517         d_to_tv(offset, &tv);
518         curtime.tv_usec += tv.tv_usec + 1000000;
519         curtime.tv_sec += tv.tv_sec - 1 + (curtime.tv_usec / 1000000);
520         curtime.tv_usec %= 1000000;
521
522         if (settimeofday(&curtime, NULL) == -1) {
523                 bb_error_msg("settimeofday");
524                 goto bail;
525         }
526
527         tval = curtime.tv_sec;
528         strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
529
530         /* Do we want to print message below to system log when daemonized? */
531         bb_info_msg("set local clock to %s (offset %fs)", buf, offset);
532
533         for (item = G.ntp_peers; item != NULL; item = item->link) {
534                 p = (ntp_peer_t *) item->data;
535                 if (p->next)
536                         p->next -= offset;
537                 if (p->deadline)
538                         p->deadline -= offset;
539         }
540
541  bail:
542         if (option_mask32 & OPT_q)
543                 exit(0);
544 }
545
546 static void
547 update_peer_data(ntp_peer_t *p)
548 {
549         int i, best = 0, good = 0;
550
551         /*
552          * clock filter
553          * find the offset which arrived with the lowest delay
554          * use that as the peer update
555          * invalidate it and all older ones
556          */
557
558         for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
559                 if (p->reply[i].good) {
560                         good++;
561                         best = i;
562                 }
563         }
564
565         for (; i < OFFSET_ARRAY_SIZE; i++) {
566                 if (p->reply[i].good) {
567                         good++;
568                         if (p->reply[i].delay < p->reply[best].delay)
569                                 best = i;
570                 }
571         }
572
573         if (good < 8)
574                 return;
575
576         memcpy(&p->update, &p->reply[best], sizeof(p->update));
577         adjtime_wrap();
578
579         for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
580                 if (p->reply[i].rcvd <= p->reply[best].rcvd)
581                         p->reply[i].good = 0;
582 }
583
584 static time_t
585 scale_interval(time_t requested)
586 {
587         time_t interval, r;
588         interval = requested * G.scale;
589         r = (unsigned)random() % (unsigned long)(MAX(5, interval / 10));
590         return (interval + r);
591 }
592
593 static void
594 recv_and_process_peer_pkt(ntp_peer_t *p)
595 {
596         char                     *addr;
597         ssize_t                  size;
598         ntp_msg_t                msg;
599         double                   T1, T2, T3, T4;
600         time_t                   interval;
601         ntp_offset_t            *offset;
602
603         addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
604
605         /* We can recvfrom here and check from.IP, but some multihomed
606          * ntp servers reply from their *other IP*.
607          * TODO: maybe we should check at least what we can: from.port == 123?
608          */
609         size = recv(p->query.fd, &msg, sizeof(msg), MSG_DONTWAIT);
610         if (size == -1) {
611                 bb_perror_msg("recv(%s) error", addr);
612                 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
613                  || errno == ENETUNREACH || errno == ENETDOWN
614                  || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
615                  || errno == EAGAIN
616                 ) {
617 //TODO: always do this?
618                         set_next(p, error_interval());
619                         goto bail;
620                 }
621                 xfunc_die();
622         }
623
624         T4 = gettime1900fp();
625
626         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
627                 bb_error_msg("malformed packet received from %s", addr);
628                 goto bail;
629         }
630
631         if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
632          || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
633         ) {
634                 goto bail;
635         }
636
637         if ((msg.status & LI_ALARM) == LI_ALARM
638          || msg.stratum == 0
639          || msg.stratum > NTP_MAXSTRATUM
640         ) {
641                 interval = error_interval();
642                 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
643                 goto bail;
644         }
645
646         /*
647          * From RFC 2030 (with a correction to the delay math):
648          *
649          *     Timestamp Name          ID   When Generated
650          *     ------------------------------------------------------------
651          *     Originate Timestamp     T1   time request sent by client
652          *     Receive Timestamp       T2   time request received by server
653          *     Transmit Timestamp      T3   time reply sent by server
654          *     Destination Timestamp   T4   time reply received by client
655          *
656          *  The roundtrip delay d and local clock offset t are defined as
657          *
658          *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
659          */
660
661         T1 = p->query.xmttime;
662         T2 = lfp_to_d(msg.rectime);
663         T3 = lfp_to_d(msg.xmttime);
664
665         offset = &p->reply[p->shift];
666
667         offset->offset = ((T2 - T1) + (T3 - T4)) / 2;
668         offset->delay = (T4 - T1) - (T3 - T2);
669         if (offset->delay < 0) {
670                 interval = error_interval();
671                 set_next(p, interval);
672                 bb_info_msg("reply from %s: negative delay %f", addr, p->reply[p->shift].delay);
673                 goto bail;
674         }
675         offset->error = (T2 - T1) - (T3 - T4);
676 // Can we use (T4 - OFFSET_1900_1970) instead of time(NULL)?
677         offset->rcvd = time(NULL);
678         offset->good = 1;
679
680         offset->status.leap = (msg.status & LI_MASK);
681         offset->status.precision = msg.precision;
682         offset->status.rootdelay = sfp_to_d(msg.rootdelay);
683         offset->status.rootdispersion = sfp_to_d(msg.dispersion);
684         offset->status.refid = ntohl(msg.refid);
685         offset->status.refid4 = msg.xmttime.fractionl;
686         offset->status.reftime = lfp_to_d(msg.reftime);
687         offset->status.poll = msg.ppoll;
688         offset->status.stratum = msg.stratum;
689
690         if (p->trustlevel < TRUSTLEVEL_PATHETIC)
691                 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
692         else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
693                 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
694         else
695                 interval = scale_interval(INTERVAL_QUERY_NORMAL);
696
697         set_next(p, interval);
698         p->state = STATE_REPLY_RECEIVED;
699
700         /* every received reply which we do not discard increases trust */
701         if (p->trustlevel < TRUSTLEVEL_MAX) {
702                 p->trustlevel++;
703                 if (p->trustlevel == TRUSTLEVEL_BADPEER)
704                         bb_info_msg("peer %s now valid", addr);
705         }
706
707         bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
708                         offset->offset, offset->delay, (int) interval);
709
710         update_peer_data(p);
711         settime(offset->offset);
712
713         p->shift++;
714         if (p->shift >= OFFSET_ARRAY_SIZE)
715                 p->shift = 0;
716
717  bail:
718         free(addr);
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.status;
753         query_ppoll = msg.ppoll;
754         query_xmttime = msg.xmttime;
755
756         /* Build a reply packet */
757         memset(&msg, 0, sizeof(msg));
758         msg.status = G.status.synced ? G.status.leap : LI_ALARM;
759         msg.status |= (query_status & VERSION_MASK);
760         msg.status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
761                          MODE_SERVER : MODE_SYM_PAS;
762         msg.stratum = G.status.stratum;
763         msg.ppoll = query_ppoll;
764         msg.precision = G.status.precision;
765         rectime = gettime1900fp();
766         msg.xmttime = msg.rectime = d_to_lfp(rectime);
767         msg.reftime = d_to_lfp(G.status.reftime);
768         //msg.xmttime = d_to_lfp(gettime1900fp()); // = msg.rectime
769         msg.orgtime = query_xmttime;
770         msg.rootdelay = d_to_sfp(G.status.rootdelay);
771         version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
772         msg.refid = (version > (3 << VERSION_SHIFT)) ? G.status.refid4 : G.status.refid;
773
774         /* We reply from the local address packet was sent to,
775          * this makes to/from look swapped here: */
776         sendmsg_wrap(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 #if ENABLE_FEATURE_NTPD_SERVER
896         G.listen_fd = -1;
897         if (opts & OPT_l) {
898                 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
899                 socket_want_pktinfo(G.listen_fd);
900                 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
901         }
902 #endif
903         if (opts & OPT_g)
904                 G.settime = 1;
905         while (peers)
906                 add_peers(llist_pop(&peers));
907         if (!(opts & OPT_n)) {
908                 logmode = LOGMODE_NONE;
909                 bb_daemonize(DAEMON_DEVNULL_STDIO);
910         }
911         /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
912         if (opts & OPT_N)
913                 setpriority(PRIO_PROCESS, 0, -15);
914
915         /* Set some globals */
916         {
917                 int prec = 0;
918                 int b;
919 #if 0
920                 struct timespec tp;
921                 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
922                 clock_getres(CLOCK_REALTIME, &tp);
923                 tp.tv_sec = 0;
924                 tp.tv_nsec = 10000000;
925                 b = 1000000000 / tp.tv_nsec;    /* convert to Hz */
926 #else
927                 b = 100; /* b = 1000000000/10000000 = 100 */
928 #endif
929                 while (b > 1)
930                         prec--, b >>= 1;
931                 G.status.precision = prec;
932         }
933         G.scale = 1;
934         G.firstadj = 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                                 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
993
994                                 timeout = error_interval();
995                                 bb_info_msg("no reply from %s received in time, "
996                                                 "next query %ds", addr, timeout);
997                                 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
998                                         p->trustlevel /= 2;
999                                         if (p->trustlevel < TRUSTLEVEL_BADPEER)
1000                                                 bb_info_msg("peer %s now invalid", addr);
1001                                 }
1002                                 free(addr);
1003
1004                                 set_next(p, timeout);
1005                         }
1006
1007                         if (p->next != 0 && p->next < nextaction)
1008                                 nextaction = p->next;
1009                         if (p->deadline != 0 && p->deadline < nextaction)
1010                                 nextaction = p->deadline;
1011
1012                         if (p->state == STATE_QUERY_SENT) {
1013                                 /* Wait for reply from this peer */
1014                                 pfd[i].fd = p->query.fd;
1015                                 pfd[i].events = POLLIN;
1016                                 idx2peer[i] = p;
1017                                 i++;
1018                         }
1019                 }
1020
1021                 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
1022                         settime(0); /* no good peers, don't wait */
1023
1024                 timeout = nextaction - cur_time;
1025                 if (timeout < 0)
1026                         timeout = 0;
1027
1028                 /* Here we may block */
1029                 if (g.verbose)
1030                         bb_error_msg("entering poll %u secs", timeout);
1031                 nfds = poll(pfd, i, timeout * 1000);
1032                 if (nfds <= 0)
1033                         continue;
1034
1035                 /* Process any received packets */
1036                 j = 0;
1037 #if ENABLE_FEATURE_NTPD_SERVER
1038                 if (g.listen_fd != -1) {
1039                         if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1040                                 nfds--;
1041                                 recv_and_process_client_pkt(/*g.listen_fd*/);
1042                         }
1043                         j = 1;
1044                 }
1045 #endif
1046                 for (; nfds != 0 && j < i; j++) {
1047                         if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1048                                 nfds--;
1049                                 recv_and_process_peer_pkt(idx2peer[j]);
1050                         }
1051                 }
1052         } /* while (!bb_got_signal) */
1053
1054         kill_myself_with_sig(bb_got_signal);
1055 }