ntp: simplifications; libbb: simpler resolution of numeric hostnames
[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
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
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 JAN_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         llist_t         *ntp_peers;
177         ntp_status_t    status;
178         uint32_t        scale;
179         uint8_t         settime;
180         uint8_t         firstadj;
181         smallint        peer_cnt;
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 gettime(void)
218 {
219         struct timeval tv;
220         gettimeofday(&tv, NULL); /* never fails */
221         return (tv.tv_sec + JAN_1970 + 1.0e-6 * tv.tv_usec);
222 }
223
224
225 static void
226 d_to_tv(double d, struct timeval *tv)
227 {
228         tv->tv_sec = (long)d;
229         tv->tv_usec = (d - tv->tv_sec) * 1000000;
230 }
231
232 static double
233 lfp_to_d(l_fixedpt_t lfp)
234 {
235         double ret;
236         lfp.int_partl = ntohl(lfp.int_partl);
237         lfp.fractionl = ntohl(lfp.fractionl);
238         ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
239         return ret;
240 }
241
242 static double
243 sfp_to_d(s_fixedpt_t sfp)
244 {
245         double ret;
246         sfp.int_parts = ntohs(sfp.int_parts);
247         sfp.fractions = ntohs(sfp.fractions);
248         ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
249         return ret;
250 }
251
252 #if ENABLE_FEATURE_NTPD_SERVER
253 static l_fixedpt_t
254 d_to_lfp(double d)
255 {
256         l_fixedpt_t lfp;
257         lfp.int_partl = (uint32_t)d;
258         lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
259         lfp.int_partl = htonl(lfp.int_partl);
260         lfp.fractionl = htonl(lfp.fractionl);
261         return lfp;
262 }
263
264 static s_fixedpt_t
265 d_to_sfp(double d)
266 {
267         s_fixedpt_t sfp;
268         sfp.int_parts = (uint16_t)d;
269         sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
270         sfp.int_parts = htons(sfp.int_parts);
271         sfp.fractions = htons(sfp.fractions);
272         return sfp;
273 }
274 #endif
275
276 static void
277 set_deadline(ntp_peer_t *p, time_t t)
278 {
279         p->deadline = time(NULL) + t;
280         p->next = 0;
281 }
282
283 static time_t
284 error_interval(void)
285 {
286         time_t interval, r;
287         interval = INTERVAL_QUERY_PATHETIC * QSCALE_OFF_MAX / QSCALE_OFF_MIN;
288         r = (unsigned)random() % (unsigned long)(interval / 10);
289         return (interval + r);
290 }
291
292 static int
293 sendmsg_wrap(int fd,
294                 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
295                 ntp_msg_t *msg, ssize_t len)
296 {
297         ssize_t ret;
298
299         errno = 0;
300         if (!from) {
301                 ret = sendto(fd, msg, len, 0, to, addrlen);
302         } else {
303                 ret = send_to_from(fd, msg, len, 0, to, from, addrlen);
304         }
305         if (ret != len) {
306                 bb_perror_msg("send failed");
307                 return -1;
308         }
309         return 0;
310 }
311
312 static int
313 client_query(ntp_peer_t *p)
314 {
315         if (p->query.fd == -1) {
316                 p->query.fd = xsocket(p->lsa->u.sa.sa_family, SOCK_DGRAM, 0);
317 #if ENABLE_FEATURE_IPV6
318                 if (p->lsa->u.sa.sa_family == AF_INET)
319 #endif
320                         setsockopt(p->query.fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
321         }
322
323         /*
324          * Send out a random 64-bit number as our transmit time.  The NTP
325          * server will copy said number into the originate field on the
326          * response that it sends us.  This is totally legal per the SNTP spec.
327          *
328          * The impact of this is two fold: we no longer send out the current
329          * system time for the world to see (which may aid an attacker), and
330          * it gives us a (not very secure) way of knowing that we're not
331          * getting spoofed by an attacker that can't capture our traffic
332          * but can spoof packets from the NTP server we're communicating with.
333          *
334          * Save the real transmit timestamp locally.
335          */
336
337         p->query.msg.xmttime.int_partl = random();
338         p->query.msg.xmttime.fractionl = random();
339         p->query.xmttime = gettime();
340
341         if (sendmsg_wrap(p->query.fd, /*from:*/ NULL, /*to:*/ &p->lsa->u.sa, /*addrlen:*/ p->lsa->len,
342                         &p->query.msg, NTP_MSGSIZE_NOAUTH) == -1) {
343                 set_next(p, INTERVAL_QUERY_PATHETIC);
344                 return -1;
345         }
346
347         p->state = STATE_QUERY_SENT;
348         set_deadline(p, QUERYTIME_MAX);
349
350         return 0;
351 }
352
353 static int
354 offset_compare(const void *aa, const void *bb)
355 {
356         const ntp_peer_t *const *a = aa;
357         const ntp_peer_t *const *b = bb;
358         if ((*a)->update.offset < (*b)->update.offset)
359                 return -1;
360         return ((*a)->update.offset > (*b)->update.offset);
361 }
362
363 static uint32_t
364 updated_scale(double offset)
365 {
366         if (offset < 0)
367                 offset = -offset;
368         if (offset > QSCALE_OFF_MAX)
369                 return 1;
370         if (offset < QSCALE_OFF_MIN)
371                 return QSCALE_OFF_MAX / QSCALE_OFF_MIN;
372         return QSCALE_OFF_MAX / offset;
373 }
374
375 static void
376 adjtime_wrap(void)
377 {
378         ntp_peer_t       *p;
379         unsigned          offset_cnt;
380         int               i = 0;
381         ntp_peer_t      **peers;
382         double            offset_median;
383         llist_t          *item;
384         len_and_sockaddr *lsa;
385         struct timeval    tv, olddelta;
386
387         offset_cnt = 0;
388         for (item = G.ntp_peers; item != NULL; item = item->link) {
389                 p = (ntp_peer_t *) item->data;
390                 if (p->trustlevel < TRUSTLEVEL_BADPEER)
391                         continue;
392                 if (!p->update.good)
393                         return;
394                 offset_cnt++;
395         }
396
397         peers = xzalloc(sizeof(ntp_peer_t *) * offset_cnt);
398         for (item = G.ntp_peers; item != NULL; item = item->link) {
399                 p = (ntp_peer_t *) item->data;
400                 if (p->trustlevel < TRUSTLEVEL_BADPEER)
401                         continue;
402                 peers[i++] = p;
403         }
404
405         qsort(peers, offset_cnt, sizeof(ntp_peer_t *), offset_compare);
406
407         if (offset_cnt != 0) {
408                 if ((offset_cnt & 1) == 0) {
409 //TODO: try offset_cnt /= 2...
410                         offset_median =
411                             (peers[offset_cnt / 2 - 1]->update.offset +
412                             peers[offset_cnt / 2]->update.offset) / 2;
413                         G.status.rootdelay =
414                             (peers[offset_cnt / 2 - 1]->update.delay +
415                             peers[offset_cnt / 2]->update.delay) / 2;
416                         G.status.stratum = MAX(
417                             peers[offset_cnt / 2 - 1]->update.status.stratum,
418                             peers[offset_cnt / 2]->update.status.stratum);
419                 } else {
420                         offset_median = peers[offset_cnt / 2]->update.offset;
421                         G.status.rootdelay = peers[offset_cnt / 2]->update.delay;
422                         G.status.stratum = peers[offset_cnt / 2]->update.status.stratum;
423                 }
424                 G.status.leap = peers[offset_cnt / 2]->update.status.leap;
425
426                 bb_info_msg("adjusting local clock by %fs", offset_median);
427
428                 d_to_tv(offset_median, &tv);
429                 if (adjtime(&tv, &olddelta) == -1)
430                         bb_error_msg("adjtime failed");
431                 else if (!G.firstadj
432                  && olddelta.tv_sec == 0
433                  && olddelta.tv_usec == 0
434                  && !G.status.synced
435                 ) {
436                         bb_info_msg("clock synced");
437                         G.status.synced = 1;
438                 } else if (G.status.synced) {
439                         bb_info_msg("clock unsynced");
440                         G.status.synced = 0;
441                 }
442
443                 G.firstadj = 0;
444                 G.status.reftime = gettime();
445                 G.status.stratum++;     /* one more than selected peer */
446                 G.scale = updated_scale(offset_median);
447
448                 G.status.refid4 = peers[offset_cnt / 2]->update.status.refid4;
449
450                 lsa = peers[offset_cnt / 2]->lsa;
451                 G.status.refid =
452 #if ENABLE_FEATURE_IPV6
453                         lsa->u.sa.sa_family != AF_INET ?
454                                 G.status.refid4 :
455 #endif
456                                 lsa->u.sin.sin_addr.s_addr;
457         }
458
459         free(peers);
460
461         for (item = G.ntp_peers; item != NULL; item = item->link) {
462                 p = (ntp_peer_t *) item->data;
463                 p->update.good = 0;
464         }
465 }
466
467 static void
468 settime(double offset)
469 {
470         ntp_peer_t *p;
471         llist_t         *item;
472         struct timeval  tv, curtime;
473         char            buf[80];
474         time_t          tval;
475
476         if (!G.settime)
477                 goto bail;
478
479         G.settime = 0;
480
481         /* if the offset is small, don't call settimeofday */
482         if (offset < SETTIME_MIN_OFFSET && offset > -SETTIME_MIN_OFFSET)
483                 goto bail;
484
485         gettimeofday(&curtime, NULL); /* never fails */
486
487         d_to_tv(offset, &tv);
488         curtime.tv_usec += tv.tv_usec + 1000000;
489         curtime.tv_sec += tv.tv_sec - 1 + (curtime.tv_usec / 1000000);
490         curtime.tv_usec %= 1000000;
491
492         if (settimeofday(&curtime, NULL) == -1) {
493                 bb_error_msg("settimeofday");
494                 goto bail;
495         }
496
497         tval = curtime.tv_sec;
498         strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
499
500         /* Do we want to print message below to system log when daemonized? */
501         bb_info_msg("set local clock to %s (offset %fs)", buf, offset);
502
503         for (item = G.ntp_peers; item != NULL; item = item->link) {
504                 p = (ntp_peer_t *) item->data;
505                 if (p->next)
506                         p->next -= offset;
507                 if (p->deadline)
508                         p->deadline -= offset;
509         }
510
511  bail:
512         if (option_mask32 & OPT_q)
513                 exit(0);
514 }
515
516 static void
517 client_update(ntp_peer_t *p)
518 {
519         int i, best = 0, good = 0;
520
521         /*
522          * clock filter
523          * find the offset which arrived with the lowest delay
524          * use that as the peer update
525          * invalidate it and all older ones
526          */
527
528         for (i = 0; good == 0 && i < OFFSET_ARRAY_SIZE; i++) {
529                 if (p->reply[i].good) {
530                         good++;
531                         best = i;
532                 }
533         }
534
535         for (; i < OFFSET_ARRAY_SIZE; i++) {
536                 if (p->reply[i].good) {
537                         good++;
538                         if (p->reply[i].delay < p->reply[best].delay)
539                                 best = i;
540                 }
541         }
542
543         if (good < 8)
544                 return;
545
546         memcpy(&p->update, &p->reply[best], sizeof(p->update));
547         adjtime_wrap();
548
549         for (i = 0; i < OFFSET_ARRAY_SIZE; i++)
550                 if (p->reply[i].rcvd <= p->reply[best].rcvd)
551                         p->reply[i].good = 0;
552 }
553
554 static time_t
555 scale_interval(time_t requested)
556 {
557         time_t interval, r;
558         interval = requested * G.scale;
559         r = (unsigned)random() % (unsigned long)(MAX(5, interval / 10));
560         return (interval + r);
561 }
562
563 static void
564 client_dispatch(ntp_peer_t *p)
565 {
566         char                     *addr;
567         ssize_t                  size;
568         ntp_msg_t                msg;
569         double                   T1, T2, T3, T4;
570         time_t                   interval;
571         ntp_offset_t            *offset;
572
573         addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
574
575 //TODO: use MSG_DONTWAIT flag?
576         size = recv(p->query.fd, &msg, sizeof(msg), 0);
577         if (size == -1) {
578                 bb_perror_msg("recv(%s) error", addr);
579                 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
580                  || errno == ENETUNREACH || errno == ENETDOWN
581                  || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
582                 ) {
583 //TODO: always do this?
584                         set_next(p, error_interval());
585                         goto bail;
586                 }
587                 xfunc_die();
588         }
589
590         T4 = gettime();
591
592         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
593                 bb_error_msg("malformed packet received from %s", addr);
594                 goto bail;
595         }
596
597         if (msg.orgtime.int_partl != p->query.msg.xmttime.int_partl
598          || msg.orgtime.fractionl != p->query.msg.xmttime.fractionl
599         ) {
600                 goto bail;
601         }
602
603         if ((msg.status & LI_ALARM) == LI_ALARM
604          || msg.stratum == 0
605          || msg.stratum > NTP_MAXSTRATUM
606         ) {
607                 interval = error_interval();
608                 bb_info_msg("reply from %s: not synced, next query %ds", addr, (int) interval);
609                 goto bail;
610         }
611
612         /*
613          * From RFC 2030 (with a correction to the delay math):
614          *
615          *     Timestamp Name          ID   When Generated
616          *     ------------------------------------------------------------
617          *     Originate Timestamp     T1   time request sent by client
618          *     Receive Timestamp       T2   time request received by server
619          *     Transmit Timestamp      T3   time reply sent by server
620          *     Destination Timestamp   T4   time reply received by client
621          *
622          *  The roundtrip delay d and local clock offset t are defined as
623          *
624          *    d = (T4 - T1) - (T3 - T2)     t = ((T2 - T1) + (T3 - T4)) / 2.
625          */
626
627         T1 = p->query.xmttime;
628         T2 = lfp_to_d(msg.rectime);
629         T3 = lfp_to_d(msg.xmttime);
630
631         offset = &p->reply[p->shift];
632
633         offset->offset = ((T2 - T1) + (T3 - T4)) / 2;
634         offset->delay = (T4 - T1) - (T3 - T2);
635         if (offset->delay < 0) {
636                 interval = error_interval();
637                 set_next(p, interval);
638                 bb_info_msg("reply from %s: negative delay %f", addr, p->reply[p->shift].delay);
639                 goto bail;
640         }
641         offset->error = (T2 - T1) - (T3 - T4);
642         offset->rcvd = time(NULL);
643         offset->good = 1;
644
645         offset->status.leap = (msg.status & LI_MASK);
646         offset->status.precision = msg.precision;
647         offset->status.rootdelay = sfp_to_d(msg.rootdelay);
648         offset->status.rootdispersion = sfp_to_d(msg.dispersion);
649         offset->status.refid = ntohl(msg.refid);
650         offset->status.refid4 = msg.xmttime.fractionl;
651         offset->status.reftime = lfp_to_d(msg.reftime);
652         offset->status.poll = msg.ppoll;
653         offset->status.stratum = msg.stratum;
654
655         if (p->trustlevel < TRUSTLEVEL_PATHETIC)
656                 interval = scale_interval(INTERVAL_QUERY_PATHETIC);
657         else if (p->trustlevel < TRUSTLEVEL_AGRESSIVE)
658                 interval = scale_interval(INTERVAL_QUERY_AGRESSIVE);
659         else
660                 interval = scale_interval(INTERVAL_QUERY_NORMAL);
661
662         set_next(p, interval);
663         p->state = STATE_REPLY_RECEIVED;
664
665         /* every received reply which we do not discard increases trust */
666         if (p->trustlevel < TRUSTLEVEL_MAX) {
667                 if (p->trustlevel < TRUSTLEVEL_BADPEER
668                  && p->trustlevel + 1 >= TRUSTLEVEL_BADPEER
669                 ) {
670                         bb_info_msg("peer %s now valid", addr);
671                 }
672                 p->trustlevel++;
673         }
674
675         bb_info_msg("reply from %s: offset %f delay %f, next query %ds", addr,
676                         offset->offset, offset->delay, (int) interval);
677
678         client_update(p);
679         settime(offset->offset);
680
681         if (++p->shift >= OFFSET_ARRAY_SIZE)
682                 p->shift = 0;
683
684  bail:
685         free(addr);
686 }
687
688 #if ENABLE_FEATURE_NTPD_SERVER
689 static void
690 server_dispatch(int fd)
691 {
692         ssize_t          size;
693         uint8_t          version;
694         double           rectime;
695         len_and_sockaddr *to;
696         struct sockaddr  *from;
697         ntp_msg_t        msg;
698         uint8_t          query_status;
699         uint8_t          query_ppoll;
700         l_fixedpt_t      query_xmttime;
701
702         to = get_sock_lsa(G.listen_fd);
703         from = xzalloc(to->len);
704
705 //TODO: use MGS_DONTWAIT flag?
706         size = recv_from_to(fd, &msg, sizeof(msg), 0, from, &to->u.sa, to->len);
707         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
708                 char *addr;
709                 if (size < 0)
710                         bb_error_msg_and_die("recv_from_to");
711                 addr = xmalloc_sockaddr2dotted_noport(from);
712                 bb_error_msg("malformed packet received from %s", addr);
713                 free(addr);
714                 goto bail;
715         }
716
717         query_status = msg.status;
718         query_ppoll = msg.ppoll;
719         query_xmttime = msg.xmttime;
720
721         /* Build a reply packet */
722         memset(&msg, 0, sizeof(msg));
723         msg.status = G.status.synced ? G.status.leap : LI_ALARM;
724         msg.status |= (query_status & VERSION_MASK);
725         msg.status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
726                          MODE_SERVER : MODE_SYM_PAS;
727         msg.stratum = G.status.stratum;
728         msg.ppoll = query_ppoll;
729         msg.precision = G.status.precision;
730         rectime = gettime();
731         msg.xmttime = msg.rectime = d_to_lfp(rectime);
732         msg.reftime = d_to_lfp(G.status.reftime);
733         //msg.xmttime = d_to_lfp(gettime()); // = msg.rectime
734         msg.orgtime = query_xmttime;
735         msg.rootdelay = d_to_sfp(G.status.rootdelay);
736         version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
737         msg.refid = (version > (3 << VERSION_SHIFT)) ? G.status.refid4 : G.status.refid;
738
739         /* We reply from the address packet was sent to,
740          * this makes to/from look swapped here: */
741         sendmsg_wrap(fd,
742                 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
743                 &msg, size);
744
745  bail:
746         free(to);
747         free(from);
748 }
749 #endif
750
751 /* Upstream ntpd's options:
752  *
753  * -4   Force DNS resolution of host names to the IPv4 namespace.
754  * -6   Force DNS resolution of host names to the IPv6 namespace.
755  * -a   Require cryptographic authentication for broadcast client,
756  *      multicast client and symmetric passive associations.
757  *      This is the default.
758  * -A   Do not require cryptographic authentication for broadcast client,
759  *      multicast client and symmetric passive associations.
760  *      This is almost never a good idea.
761  * -b   Enable the client to synchronize to broadcast servers.
762  * -c conffile
763  *      Specify the name and path of the configuration file,
764  *      default /etc/ntp.conf
765  * -d   Specify debugging mode. This option may occur more than once,
766  *      with each occurrence indicating greater detail of display.
767  * -D level
768  *      Specify debugging level directly.
769  * -f driftfile
770  *      Specify the name and path of the frequency file.
771  *      This is the same operation as the "driftfile FILE"
772  *      configuration command.
773  * -g   Normally, ntpd exits with a message to the system log
774  *      if the offset exceeds the panic threshold, which is 1000 s
775  *      by default. This option allows the time to be set to any value
776  *      without restriction; however, this can happen only once.
777  *      If the threshold is exceeded after that, ntpd will exit
778  *      with a message to the system log. This option can be used
779  *      with the -q and -x options. See the tinker command for other options.
780  * -i jaildir
781  *      Chroot the server to the directory jaildir. This option also implies
782  *      that the server attempts to drop root privileges at startup
783  *      (otherwise, chroot gives very little additional security).
784  *      You may need to also specify a -u option.
785  * -k keyfile
786  *      Specify the name and path of the symmetric key file,
787  *      default /etc/ntp/keys. This is the same operation
788  *      as the "keys FILE" configuration command.
789  * -l logfile
790  *      Specify the name and path of the log file. The default
791  *      is the system log file. This is the same operation as
792  *      the "logfile FILE" configuration command.
793  * -L   Do not listen to virtual IPs. The default is to listen.
794  * -n   Don't fork.
795  * -N   To the extent permitted by the operating system,
796  *      run the ntpd at the highest priority.
797  * -p pidfile
798  *      Specify the name and path of the file used to record the ntpd
799  *      process ID. This is the same operation as the "pidfile FILE"
800  *      configuration command.
801  * -P priority
802  *      To the extent permitted by the operating system,
803  *      run the ntpd at the specified priority.
804  * -q   Exit the ntpd just after the first time the clock is set.
805  *      This behavior mimics that of the ntpdate program, which is
806  *      to be retired. The -g and -x options can be used with this option.
807  *      Note: The kernel time discipline is disabled with this option.
808  * -r broadcastdelay
809  *      Specify the default propagation delay from the broadcast/multicast
810  *      server to this client. This is necessary only if the delay
811  *      cannot be computed automatically by the protocol.
812  * -s statsdir
813  *      Specify the directory path for files created by the statistics
814  *      facility. This is the same operation as the "statsdir DIR"
815  *      configuration command.
816  * -t key
817  *      Add a key number to the trusted key list. This option can occur
818  *      more than once.
819  * -u user[:group]
820  *      Specify a user, and optionally a group, to switch to.
821  * -v variable
822  * -V variable
823  *      Add a system variable listed by default.
824  * -x   Normally, the time is slewed if the offset is less than the step
825  *      threshold, which is 128 ms by default, and stepped if above
826  *      the threshold. This option sets the threshold to 600 s, which is
827  *      well within the accuracy window to set the clock manually.
828  *      Note: since the slew rate of typical Unix kernels is limited
829  *      to 0.5 ms/s, each second of adjustment requires an amortization
830  *      interval of 2000 s. Thus, an adjustment as much as 600 s
831  *      will take almost 14 days to complete. This option can be used
832  *      with the -g and -q options. See the tinker command for other options.
833  *      Note: The kernel time discipline is disabled with this option.
834  */
835
836 /* By doing init in a separate function we decrease stack usage
837  * in main loop.
838  */
839 static NOINLINE void ntp_init(char **argv)
840 {
841         unsigned opts;
842         llist_t *peers;
843
844         srandom(getpid());
845         /* tzset(); - why? it's called automatically when needed, no? */
846
847         if (getuid())
848                 bb_error_msg_and_die("need root privileges");
849
850         peers = NULL;
851         opt_complementary = "dd:p::"; /* d: counter, p: list */
852         opts = getopt32(argv,
853                         "ngq" /* compat */
854                         "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
855                         "d" /* compat */
856                         "46aAbLNx", /* compat, ignored */
857                         &peers, &G.verbose);
858 #if ENABLE_FEATURE_NTPD_SERVER
859         G.listen_fd = -1;
860         if (opts & OPT_l) {
861                 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
862                 socket_want_pktinfo(G.listen_fd);
863                 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
864         }
865 #endif
866         if (opts & OPT_g)
867                 G.settime = 1;
868         while (peers)
869                 add_peers(llist_pop(&peers));
870         if (!(opts & OPT_n)) {
871                 logmode = LOGMODE_NONE;
872                 bb_daemonize(DAEMON_DEVNULL_STDIO);
873         }
874
875         /* Set some globals */
876         {
877                 int prec = 0;
878                 int b;
879 #if 0
880                 struct timespec tp;
881                 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
882                 clock_getres(CLOCK_REALTIME, &tp);
883                 tp.tv_sec = 0;
884                 tp.tv_nsec = 10000000;
885                 b = 1000000000 / tp.tv_nsec;    /* convert to Hz */
886 #else
887                 b = 100; /* b = 1000000000/10000000 = 100 */
888 #endif
889                 while (b > 1)
890                         prec--, b >>= 1;
891                 G.status.precision = prec;
892         }
893         G.scale = 1;
894         G.firstadj = 1;
895
896         bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
897         bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
898 }
899
900 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
901 int ntpd_main(int argc UNUSED_PARAM, char **argv)
902 {
903         struct globals g;
904         struct pollfd *pfd;
905         ntp_peer_t **idx2peer;
906
907         memset(&g, 0, sizeof(g));
908         SET_PTR_TO_GLOBALS(&g);
909
910         ntp_init(argv);
911
912         {
913                 unsigned new_cnt = g.peer_cnt;
914                 idx2peer = xzalloc(sizeof(void *) * new_cnt);
915                 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
916                 pfd = xzalloc(sizeof(pfd[0]) * (new_cnt + ENABLE_FEATURE_NTPD_SERVER));
917         }
918
919         while (!bb_got_signal) {
920                 llist_t *item;
921                 unsigned i, j, first_peer_idx;
922                 unsigned sent_cnt, trial_cnt;
923                 int nfds, timeout;
924                 time_t nextaction;
925
926                 nextaction = time(NULL) + 3600;
927
928                 i = 0;
929 #if ENABLE_FEATURE_NTPD_SERVER
930                 if (g.listen_fd != -1) {
931                         pfd[0].fd = g.listen_fd;
932                         pfd[0].events = POLLIN;
933                         i++;
934                 }
935 #endif
936                 first_peer_idx = i;
937                 sent_cnt = trial_cnt = 0;
938                 for (item = g.ntp_peers; item != NULL; item = item->link) {
939                         ntp_peer_t *p = (ntp_peer_t *) item->data;
940
941                         if (p->next > 0 && p->next <= time(NULL)) {
942                                 trial_cnt++;
943                                 if (client_query(p) == 0)
944                                         sent_cnt++;
945                         }
946                         if (p->next > 0 && p->next < nextaction)
947                                 nextaction = p->next;
948                         if (p->deadline > 0 && p->deadline < nextaction)
949                                 nextaction = p->deadline;
950
951                         if (p->deadline > 0 && p->deadline <= time(NULL)) {
952                                 char *addr = xmalloc_sockaddr2dotted_noport(&p->lsa->u.sa);
953
954                                 timeout = error_interval();
955                                 bb_info_msg("no reply from %s received in time, "
956                                                 "next query %ds", addr, timeout);
957                                 if (p->trustlevel >= TRUSTLEVEL_BADPEER) {
958                                         p->trustlevel /= 2;
959                                         if (p->trustlevel < TRUSTLEVEL_BADPEER)
960                                                 bb_info_msg("peer %s now invalid", addr);
961                                 }
962                                 free(addr);
963
964                                 set_next(p, timeout);
965                         }
966
967                         if (p->state == STATE_QUERY_SENT) {
968                                 pfd[i].fd = p->query.fd;
969                                 pfd[i].events = POLLIN;
970                                 idx2peer[i - first_peer_idx] = p;
971                                 i++;
972                         }
973                 }
974
975                 if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0)
976                         settime(0);     /* no good peers, don't wait */
977
978                 timeout = nextaction - time(NULL);
979                 if (timeout < 0)
980                         timeout = 0;
981
982                 if (g.verbose)
983                         bb_error_msg("entering poll %u secs", timeout);
984                 nfds = poll(pfd, i, timeout * 1000);
985
986                 j = 0;
987 #if ENABLE_FEATURE_NTPD_SERVER
988 //TODO: simplify. There is only one server fd!
989                 for (; nfds > 0 && j < first_peer_idx; j++) {
990                         if (pfd[j].revents & (POLLIN|POLLERR)) {
991                                 nfds--;
992                                 server_dispatch(pfd[j].fd);
993                         }
994                 }
995 #endif
996                 for (; nfds > 0 && j < i; j++) {
997                         if (pfd[j].revents & (POLLIN|POLLERR)) {
998                                 nfds--;
999                                 client_dispatch(idx2peer[j - first_peer_idx]);
1000                         }
1001                 }
1002         } /* while (!bb_got_signal) */
1003
1004         kill_myself_with_sig(bb_got_signal);
1005 }