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