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