508e355c9f8920d5e22cc2b4430dd71f79ef4948
[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  * Parts of OpenNTPD clock syncronization code is replaced by
9  * code which is based on ntp-4.2.6. It carries the following
10  * copyright notice:
11  *
12  ***********************************************************************
13  *                                                                     *
14  * Copyright (c) University of Delaware 1992-2009                      *
15  *                                                                     *
16  * Permission to use, copy, modify, and distribute this software and   *
17  * its documentation for any purpose with or without fee is hereby     *
18  * granted, provided that the above copyright notice appears in all    *
19  * copies and that both the copyright notice and this permission       *
20  * notice appear in supporting documentation, and that the name        *
21  * University of Delaware not be used in advertising or publicity      *
22  * pertaining to distribution of the software without specific,        *
23  * written prior permission. The University of Delaware makes no       *
24  * representations about the suitability this software for any         *
25  * purpose. It is provided "as is" without express or implied          *
26  * warranty.                                                           *
27  *                                                                     *
28  ***********************************************************************
29  */
30 #include "libbb.h"
31 #include <math.h>
32 #include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
33 #include <sys/timex.h>
34 #ifndef IPTOS_LOWDELAY
35 # define IPTOS_LOWDELAY 0x10
36 #endif
37 #ifndef IP_PKTINFO
38 # error "Sorry, your kernel has to support IP_PKTINFO"
39 #endif
40
41
42 #define RETRY_INTERVAL  5       /* on error, retry in N secs */
43 #define QUERYTIME_MAX   15      /* wait for reply up to N secs */
44
45 #define FREQ_TOLERANCE  15e-6   /* % frequency tolerance (15 PPM) */
46 #define MINPOLL         4       /* % minimum poll interval (6: 64 s) */
47 #define MAXPOLL         12      /* % maximum poll interval (12: 1.1h, 17: 36.4h) (was 17) */
48 #define MINDISP         0.01    /* % minimum dispersion (s) */
49 #define MAXDISP         16      /* maximum dispersion (s) */
50 #define MAXSTRAT        16      /* maximum stratum (infinity metric) */
51 #define MAXDIST         1       /* % distance threshold (s) */
52 #define MIN_SELECTED    1       /* % minimum intersection survivors */
53 #define MIN_CLUSTERED   3       /* % minimum cluster survivors */
54
55 #define MAXFREQ  0.000500       /* frequency tolerance (500 PPM) */
56
57 /* Clock discipline parameters and constants */
58 #define STEP_THRESHOLD  0.128   /* step threshold (s) */
59 #define WATCH_THRESHOLD  150    /* stepout threshold (s). std ntpd uses 900 (11 mins (!)) */
60 /* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
61 #define PANIC_THRESHOLD 1000    /* panic threshold (s) */
62
63 /* Poll-adjust threshold.
64  * When we see that offset is small enough compared to discipline jitter,
65  * we grow a counter: += poll_ext. When it goes over POLLADJ_LIMIT,
66  * we poll_ext++. If offset isn't small, counter -= poll_ext*2,
67  * and when it goes below -POLLADJ_LIMIT, we poll_ext--
68  */
69 #define POLLADJ_LIMIT     30
70 /* If offset < POLLADJ_GATE * discipline_jitter, then we can increase
71  * poll interval (we think we can't improve timekeeping
72  * by staying at smaller poll).
73  */
74 #define POLLADJ_GATE       4
75 /* Compromise Allan intercept (s). doc uses 1500, std ntpd uses 512 */
76 #define ALLAN            512
77 /* PLL loop gain */
78 #define PLL            65536
79 /* FLL loop gain [why it depends on MAXPOLL??] */
80 #define FLL    (MAXPOLL + 1)
81 /* Parameter averaging constant */
82 #define AVG                4
83
84 /* Verbosity control (max level of -dddd options accepted).
85  * max 5 is very talkative (and bloated). 2 is non-bloated,
86  * production level setting.
87  */
88 #define MAX_VERBOSE        2
89
90 #define VERB1 if (MAX_VERBOSE && G.verbose)
91 #define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
92 #define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
93 #define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
94 #define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
95
96
97 enum {
98         NTP_VERSION     = 4,
99         NTP_MAXSTRATUM  = 15,
100
101         NTP_DIGESTSIZE     = 16,
102         NTP_MSGSIZE_NOAUTH = 48,
103         NTP_MSGSIZE        = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
104
105         /* Status Masks */
106         MODE_MASK       = (7 << 0),
107         VERSION_MASK    = (7 << 3),
108         VERSION_SHIFT   = 3,
109         LI_MASK         = (3 << 6),
110
111         /* Leap Second Codes (high order two bits of m_status) */
112         LI_NOWARNING    = (0 << 6),    /* no warning */
113         LI_PLUSSEC      = (1 << 6),    /* add a second (61 seconds) */
114         LI_MINUSSEC     = (2 << 6),    /* minus a second (59 seconds) */
115         LI_ALARM        = (3 << 6),    /* alarm condition */
116
117         /* Mode values */
118         MODE_RES0       = 0,    /* reserved */
119         MODE_SYM_ACT    = 1,    /* symmetric active */
120         MODE_SYM_PAS    = 2,    /* symmetric passive */
121         MODE_CLIENT     = 3,    /* client */
122         MODE_SERVER     = 4,    /* server */
123         MODE_BROADCAST  = 5,    /* broadcast */
124         MODE_RES1       = 6,    /* reserved for NTP control message */
125         MODE_RES2       = 7,    /* reserved for private use */
126 };
127
128 //TODO: better base selection
129 #define OFFSET_1900_1970 2208988800UL  /* 1970 - 1900 in seconds */
130
131 #define NUM_DATAPOINTS  8
132
133 typedef struct {
134         uint32_t int_partl;
135         uint32_t fractionl;
136 } l_fixedpt_t;
137
138 typedef struct {
139         uint16_t int_parts;
140         uint16_t fractions;
141 } s_fixedpt_t;
142
143 typedef struct {
144         uint8_t     m_status;     /* status of local clock and leap info */
145         uint8_t     m_stratum;
146         uint8_t     m_ppoll;      /* poll value */
147         int8_t      m_precision_exp;
148         s_fixedpt_t m_rootdelay;
149         s_fixedpt_t m_rootdisp;
150         uint32_t    m_refid;
151         l_fixedpt_t m_reftime;
152         l_fixedpt_t m_orgtime;
153         l_fixedpt_t m_rectime;
154         l_fixedpt_t m_xmttime;
155         uint32_t    m_keyid;
156         uint8_t     m_digest[NTP_DIGESTSIZE];
157 } msg_t;
158
159 typedef struct {
160         double d_recv_time;
161         double d_offset;
162         double d_dispersion;
163 } datapoint_t;
164
165 typedef struct {
166         len_and_sockaddr *p_lsa;
167         char             *p_dotted;
168         /* when to send new query (if p_fd == -1)
169          * or when receive times out (if p_fd >= 0): */
170         time_t           next_action_time;
171         int              p_fd;
172         int              datapoint_idx;
173         uint32_t         lastpkt_refid;
174         uint8_t          lastpkt_leap;
175         uint8_t          lastpkt_stratum;
176         uint8_t          p_reachable_bits;
177         double           p_xmttime;
178         double           lastpkt_recv_time;
179         double           lastpkt_delay;
180         double           lastpkt_rootdelay;
181         double           lastpkt_rootdisp;
182         /* produced by filter algorithm: */
183         double           filter_offset;
184         double           filter_dispersion;
185         double           filter_jitter;
186         datapoint_t      filter_datapoint[NUM_DATAPOINTS];
187         /* last sent packet: */
188         msg_t            p_xmt_msg;
189 } peer_t;
190
191
192 enum {
193         OPT_n = (1 << 0),
194         OPT_q = (1 << 1),
195         OPT_N = (1 << 2),
196         OPT_x = (1 << 3),
197         /* Insert new options above this line. */
198         /* Non-compat options: */
199         OPT_p = (1 << 4),
200         OPT_l = (1 << 5) * ENABLE_FEATURE_NTPD_SERVER,
201 };
202
203 struct globals {
204         /* total round trip delay to currently selected reference clock */
205         double   rootdelay;
206         /* reference timestamp: time when the system clock was last set or corrected */
207         double   reftime;
208         /* total dispersion to currently selected reference clock */
209         double   rootdisp;
210         llist_t  *ntp_peers;
211 #if ENABLE_FEATURE_NTPD_SERVER
212         int      listen_fd;
213 #endif
214         unsigned verbose;
215         unsigned peer_cnt;
216         /* refid: 32-bit code identifying the particular server or reference clock
217          *  in stratum 0 packets this is a four-character ASCII string,
218          *  called the kiss code, used for debugging and monitoring
219          *  in stratum 1 packets this is a four-character ASCII string
220          *  assigned to the reference clock by IANA. Example: "GPS "
221          *  in stratum 2+ packets, it's IPv4 address or 4 first bytes of MD5 hash of IPv6
222          */
223         uint32_t refid;
224         uint8_t  leap;
225         /* precision is defined as the larger of the resolution and time to
226          * read the clock, in log2 units.  For instance, the precision of a
227          * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
228          * system clock hardware representation is to the nanosecond.
229          *
230          * Delays, jitters of various kinds are clamper down to precision.
231          *
232          * If precision_sec is too large, discipline_jitter gets clamped to it
233          * and if offset is much smaller than discipline_jitter, poll interval
234          * grows even though we really can benefit from staying at smaller one,
235          * collecting non-lagged datapoits and correcting the offset.
236          * (Lagged datapoits exist when poll_exp is large but we still have
237          * systematic offset error - the time distance between datapoints
238          * is significat and older datapoints have smaller offsets.
239          * This makes our offset estimation a bit smaller than reality)
240          * Due to this effect, setting G_precision_sec close to
241          * STEP_THRESHOLD isn't such a good idea - offsets may grow
242          * too big and we will step. I observed it with -6.
243          *
244          * OTOH, setting precision too small would result in futile attempts
245          * to syncronize to the unachievable precision.
246          *
247          * -6 is 1/64 sec, -7 is 1/128 sec and so on.
248          */
249 #define G_precision_exp  -8
250 #define G_precision_sec  (1.0 / (1 << (- G_precision_exp)))
251         uint8_t  stratum;
252         /* Bool. After set to 1, never goes back to 0: */
253 //TODO: fix logic:
254 //      uint8_t  time_was_stepped;
255         uint8_t  adjtimex_was_done;
256
257         uint8_t  discipline_state;      // doc calls it c.state
258         uint8_t  poll_exp;              // s.poll
259         int      polladj_count;         // c.count
260         double   discipline_jitter;     // c.jitter
261         double   last_update_offset;    // c.last
262         double   discipline_freq_drift; // c.freq
263 //TODO: conditionally calculate wander? it's used only for logging
264         double   discipline_wander;     // c.wander
265         double   last_update_recv_time; // s.t
266 //TODO: add s.jitter - grep for it here and see clock_combine() in doc
267 };
268 #define G (*ptr_to_globals)
269
270 static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
271
272
273 static double LOG2D(int a)
274 {
275         if (a < 0)
276                 return 1.0 / (1UL << -a);
277         return 1UL << a;
278 }
279 static ALWAYS_INLINE double SQUARE(double x)
280 {
281         return x * x;
282 }
283 static ALWAYS_INLINE double MAXD(double a, double b)
284 {
285         if (a > b)
286                 return a;
287         return b;
288 }
289 static ALWAYS_INLINE double MIND(double a, double b)
290 {
291         if (a < b)
292                 return a;
293         return b;
294 }
295 #define SQRT(x) (sqrt(x))
296
297 static double
298 gettime1900d(void)
299 {
300         struct timeval tv;
301         gettimeofday(&tv, NULL); /* never fails */
302         return (tv.tv_sec + 1.0e-6 * tv.tv_usec + OFFSET_1900_1970);
303 }
304
305 static void
306 d_to_tv(double d, struct timeval *tv)
307 {
308         tv->tv_sec = (long)d;
309         tv->tv_usec = (d - tv->tv_sec) * 1000000;
310 }
311
312 static double
313 lfp_to_d(l_fixedpt_t lfp)
314 {
315         double ret;
316         lfp.int_partl = ntohl(lfp.int_partl);
317         lfp.fractionl = ntohl(lfp.fractionl);
318         ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
319         return ret;
320 }
321 static double
322 sfp_to_d(s_fixedpt_t sfp)
323 {
324         double ret;
325         sfp.int_parts = ntohs(sfp.int_parts);
326         sfp.fractions = ntohs(sfp.fractions);
327         ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
328         return ret;
329 }
330 #if ENABLE_FEATURE_NTPD_SERVER
331 static l_fixedpt_t
332 d_to_lfp(double d)
333 {
334         l_fixedpt_t lfp;
335         lfp.int_partl = (uint32_t)d;
336         lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
337         lfp.int_partl = htonl(lfp.int_partl);
338         lfp.fractionl = htonl(lfp.fractionl);
339         return lfp;
340 }
341 static s_fixedpt_t
342 d_to_sfp(double d)
343 {
344         s_fixedpt_t sfp;
345         sfp.int_parts = (uint16_t)d;
346         sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
347         sfp.int_parts = htons(sfp.int_parts);
348         sfp.fractions = htons(sfp.fractions);
349         return sfp;
350 }
351 #endif
352
353 static double
354 dispersion(const datapoint_t *dp, double t)
355 {
356         return dp->d_dispersion + FREQ_TOLERANCE * (t - dp->d_recv_time);
357 }
358
359 static double
360 root_distance(peer_t *p, double t)
361 {
362         /* The root synchronization distance is the maximum error due to
363          * all causes of the local clock relative to the primary server.
364          * It is defined as half the total delay plus total dispersion
365          * plus peer jitter.
366          */
367         return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
368                 + p->lastpkt_rootdisp
369                 + p->filter_dispersion
370                 + FREQ_TOLERANCE * (t - p->lastpkt_recv_time)
371                 + p->filter_jitter;
372 }
373
374 static void
375 set_next(peer_t *p, unsigned t)
376 {
377         p->next_action_time = time(NULL) + t;
378 }
379
380 /*
381  * Peer clock filter and its helpers
382  */
383 static void
384 filter_datapoints(peer_t *p, double t)
385 {
386         int i, idx;
387         double minoff, maxoff, wavg, sum, w;
388         double x = x;
389
390         minoff = maxoff = p->filter_datapoint[0].d_offset;
391         for (i = 1; i < NUM_DATAPOINTS; i++) {
392                 if (minoff > p->filter_datapoint[i].d_offset)
393                         minoff = p->filter_datapoint[i].d_offset;
394                 if (maxoff < p->filter_datapoint[i].d_offset)
395                         maxoff = p->filter_datapoint[i].d_offset;
396         }
397
398         idx = p->datapoint_idx; /* most recent datapoint */
399         /* Average offset:
400          * Drop two outliers and take weighted average of the rest:
401          * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
402          * we use older6/32, not older6/64 since sum of weights should be 1:
403          * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
404          */
405         wavg = 0;
406         w = 0.5;
407         //                     n-1
408         //                     ---    dispersion(i)
409         // filter_dispersion =  \     -------------
410         //                      /       (i+1)
411         //                     ---     2
412         //                     i=0
413         sum = 0;
414         for (i = 0; i < NUM_DATAPOINTS; i++) {
415                 VERB4 {
416                         bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
417                                 i,
418                                 p->filter_datapoint[idx].d_offset,
419                                 p->filter_datapoint[idx].d_dispersion, dispersion(&p->filter_datapoint[idx], t),
420                                 t - p->filter_datapoint[idx].d_recv_time,
421                                 (minoff == p->filter_datapoint[idx].d_offset || maxoff == p->filter_datapoint[idx].d_offset)
422                                         ? " (outlier by offset)" : ""
423                         );
424                 }
425
426                 sum += dispersion(&p->filter_datapoint[idx], t) / (2 << i);
427
428                 if (minoff == p->filter_datapoint[idx].d_offset) {
429                         minoff -= 1;
430                 } else
431                 if (maxoff == p->filter_datapoint[idx].d_offset) {
432                         maxoff += 1;
433                 } else {
434                         x = p->filter_datapoint[idx].d_offset * w;
435                         wavg += x;
436                         w /= 2;
437                 }
438
439                 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
440         }
441         wavg += x; /* add another older6/64 to form older6/32 */
442         p->filter_offset = wavg;
443         p->filter_dispersion = sum;
444
445         //                       +-----            -----+ ^ 1/2
446         //                       |  n-1                 |
447         //                       |  ---                 |
448         //                  1    |  \                2  |
449         // filter_jitter = --- * |  /  (avg-offset_j)   |
450         //                  n    |  ---                 |
451         //                       |  j=0                 |
452         //                       +-----            -----+
453         // where n is the number of valid datapoints in the filter (n > 1);
454         // if filter_jitter < precision then filter_jitter = precision
455         sum = 0;
456         for (i = 0; i < NUM_DATAPOINTS; i++) {
457                 sum += SQUARE(wavg - p->filter_datapoint[i].d_offset);
458         }
459         sum = SQRT(sum) / NUM_DATAPOINTS;
460         p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
461
462         VERB3 bb_error_msg("filter offset:%f disp:%f jitter:%f",
463                         p->filter_offset, p->filter_dispersion, p->filter_jitter);
464
465 }
466
467 static void
468 reset_peer_stats(peer_t *p, double t, double offset)
469 {
470         int i;
471         for (i = 0; i < NUM_DATAPOINTS; i++) {
472                 if (offset < 16 * STEP_THRESHOLD) {
473                         p->filter_datapoint[i].d_recv_time -= offset;
474                         if (p->filter_datapoint[i].d_offset != 0) {
475                                 p->filter_datapoint[i].d_offset -= offset;
476                         }
477                 } else {
478                         p->filter_datapoint[i].d_recv_time  = t;
479                         p->filter_datapoint[i].d_offset     = 0;
480                         p->filter_datapoint[i].d_dispersion = MAXDISP;
481                 }
482         }
483         if (offset < 16 * STEP_THRESHOLD) {
484                 p->lastpkt_recv_time -= offset;
485         } else {
486                 p->p_reachable_bits = 0;
487                 p->lastpkt_recv_time = t;
488         }
489         filter_datapoints(p, t); /* recalc p->filter_xxx */
490         p->next_action_time -= (time_t)offset;
491         VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
492 }
493
494 static void
495 add_peers(char *s)
496 {
497         peer_t *p;
498
499         p = xzalloc(sizeof(*p));
500         p->p_lsa = xhost2sockaddr(s, 123);
501         p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
502         p->p_fd = -1;
503         p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
504         p->next_action_time = time(NULL); /* = set_next(p, 0); */
505         reset_peer_stats(p, gettime1900d(), 16 * STEP_THRESHOLD);
506         /* Speed up initial sync: with small offsets from peers,
507          * 3 samples will sync
508          */
509         p->filter_datapoint[6].d_dispersion = 0;
510         p->filter_datapoint[7].d_dispersion = 0;
511
512         llist_add_to(&G.ntp_peers, p);
513         G.peer_cnt++;
514 }
515
516 static int
517 do_sendto(int fd,
518                 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
519                 msg_t *msg, ssize_t len)
520 {
521         ssize_t ret;
522
523         errno = 0;
524         if (!from) {
525                 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
526         } else {
527                 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
528         }
529         if (ret != len) {
530                 bb_perror_msg("send failed");
531                 return -1;
532         }
533         return 0;
534 }
535
536 static int
537 send_query_to_peer(peer_t *p)
538 {
539         // Why do we need to bind()?
540         // See what happens when we don't bind:
541         //
542         // socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
543         // setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
544         // gettimeofday({1259071266, 327885}, NULL) = 0
545         // sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
546         // ^^^ we sent it from some source port picked by kernel.
547         // time(NULL)              = 1259071266
548         // write(2, "ntpd: entering poll 15 secs\n", 28) = 28
549         // poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
550         // recv(3, "yyy", 68, MSG_DONTWAIT) = 48
551         // ^^^ this recv will receive packets to any local port!
552         //
553         // Uncomment this and use strace to see it in action:
554 #define PROBE_LOCAL_ADDR // { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); }
555
556         if (p->p_fd == -1) {
557                 int fd, family;
558                 len_and_sockaddr *local_lsa;
559
560                 family = p->p_lsa->u.sa.sa_family;
561                 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
562                 /* local_lsa has "null" address and port 0 now.
563                  * bind() ensures we have a *particular port* selected by kernel
564                  * and remembered in p->p_fd, thus later recv(p->p_fd)
565                  * receives only packets sent to this port.
566                  */
567                 PROBE_LOCAL_ADDR
568                 xbind(fd, &local_lsa->u.sa, local_lsa->len);
569                 PROBE_LOCAL_ADDR
570 #if ENABLE_FEATURE_IPV6
571                 if (family == AF_INET)
572 #endif
573                         setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
574                 free(local_lsa);
575         }
576
577         /*
578          * Send out a random 64-bit number as our transmit time.  The NTP
579          * server will copy said number into the originate field on the
580          * response that it sends us.  This is totally legal per the SNTP spec.
581          *
582          * The impact of this is two fold: we no longer send out the current
583          * system time for the world to see (which may aid an attacker), and
584          * it gives us a (not very secure) way of knowing that we're not
585          * getting spoofed by an attacker that can't capture our traffic
586          * but can spoof packets from the NTP server we're communicating with.
587          *
588          * Save the real transmit timestamp locally.
589          */
590         p->p_xmt_msg.m_xmttime.int_partl = random();
591         p->p_xmt_msg.m_xmttime.fractionl = random();
592         p->p_xmttime = gettime1900d();
593
594         if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
595                         &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
596         ) {
597                 close(p->p_fd);
598                 p->p_fd = -1;
599                 set_next(p, RETRY_INTERVAL);
600                 return -1;
601         }
602
603         p->p_reachable_bits <<= 1;
604         VERB1 bb_error_msg("sent query to %s", p->p_dotted);
605         set_next(p, QUERYTIME_MAX);
606
607         return 0;
608 }
609
610
611 static void
612 step_time(double offset)
613 {
614         double dtime;
615         struct timeval tv;
616         char buf[80];
617         time_t tval;
618
619         gettimeofday(&tv, NULL); /* never fails */
620         dtime = offset + tv.tv_sec;
621         dtime += 1.0e-6 * tv.tv_usec;
622         d_to_tv(dtime, &tv);
623
624         if (settimeofday(&tv, NULL) == -1)
625                 bb_perror_msg_and_die("settimeofday");
626
627         tval = tv.tv_sec;
628         strftime(buf, sizeof(buf), "%a %b %e %H:%M:%S %Z %Y", localtime(&tval));
629
630         bb_error_msg("setting clock to %s (offset %fs)", buf, offset);
631
632 //      G.time_was_stepped = 1;
633 }
634
635
636 /*
637  * Selection and clustering, and their helpers
638  */
639 typedef struct {
640         peer_t *p;
641         int    type;
642         double edge;
643 } point_t;
644 static int
645 compare_point_edge(const void *aa, const void *bb)
646 {
647         const point_t *a = aa;
648         const point_t *b = bb;
649         if (a->edge < b->edge) {
650                 return -1;
651         }
652         return (a->edge > b->edge);
653 }
654 typedef struct {
655         peer_t *p;
656         double metric;
657 } survivor_t;
658 static int
659 compare_survivor_metric(const void *aa, const void *bb)
660 {
661         const survivor_t *a = aa;
662         const survivor_t *b = bb;
663         if (a->metric < b->metric)
664                 return -1;
665         return (a->metric > b->metric);
666 }
667 static int
668 fit(peer_t *p, double rd)
669 {
670         if (p->p_reachable_bits == 0) {
671                 VERB3 bb_error_msg("peer %s unfit for selection: unreachable", p->p_dotted);
672                 return 0;
673         }
674 //TODO: we never accept such packets anyway, right?
675         if ((p->lastpkt_leap & LI_ALARM) == LI_ALARM
676          || p->lastpkt_stratum >= MAXSTRAT
677         ) {
678                 VERB3 bb_error_msg("peer %s unfit for selection: bad status/stratum", p->p_dotted);
679                 return 0;
680         }
681         /* rd is root_distance(p, t) */
682         if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
683                 VERB3 bb_error_msg("peer %s unfit for selection: root distance too high", p->p_dotted);
684                 return 0;
685         }
686 //TODO
687 //      /* Do we have a loop? */
688 //      if (p->refid == p->dstaddr || p->refid == s.refid)
689 //              return 0;
690         return 1;
691 }
692 static peer_t*
693 select_and_cluster(double t)
694 {
695         llist_t    *item;
696         int        i, j;
697         int        size = 3 * G.peer_cnt;
698         /* for selection algorithm */
699         point_t    point[size];
700         unsigned   num_points, num_candidates;
701         double     low, high;
702         unsigned   num_falsetickers;
703         /* for cluster algorithm */
704         survivor_t survivor[size];
705         unsigned   num_survivors;
706
707         /* Selection */
708
709         num_points = 0;
710         item = G.ntp_peers;
711         while (item != NULL) {
712                 peer_t *p = (peer_t *) item->data;
713                 double rd = root_distance(p, t);
714                 double offset = p->filter_offset;
715
716                 if (!fit(p, rd)) {
717                         item = item->link;
718                         continue;
719                 }
720
721                 VERB4 bb_error_msg("interval: [%f %f %f] %s",
722                                 offset - rd,
723                                 offset,
724                                 offset + rd,
725                                 p->p_dotted
726                 );
727                 point[num_points].p = p;
728                 point[num_points].type = -1;
729                 point[num_points].edge = offset - rd;
730                 num_points++;
731                 point[num_points].p = p;
732                 point[num_points].type = 0;
733                 point[num_points].edge = offset;
734                 num_points++;
735                 point[num_points].p = p;
736                 point[num_points].type = 1;
737                 point[num_points].edge = offset + rd;
738                 num_points++;
739                 item = item->link;
740         }
741         num_candidates = num_points / 3;
742         if (num_candidates == 0) {
743                 VERB3 bb_error_msg("no valid datapoints, no peer selected");
744                 return NULL; /* never happers? */
745         }
746 //TODO: sorting does not seem to be done in reference code
747         qsort(point, num_points, sizeof(point[0]), compare_point_edge);
748
749         /* Start with the assumption that there are no falsetickers.
750          * Attempt to find a nonempty intersection interval containing
751          * the midpoints of all truechimers.
752          * If a nonempty interval cannot be found, increase the number
753          * of assumed falsetickers by one and try again.
754          * If a nonempty interval is found and the number of falsetickers
755          * is less than the number of truechimers, a majority has been found
756          * and the midpoint of each truechimer represents
757          * the candidates available to the cluster algorithm.
758          */
759         num_falsetickers = 0;
760         while (1) {
761                 int c;
762                 unsigned num_midpoints = 0;
763
764                 low = 1 << 9;
765                 high = - (1 << 9);
766                 c = 0;
767                 for (i = 0; i < num_points; i++) {
768                         /* We want to do:
769                          * if (point[i].type == -1) c++;
770                          * if (point[i].type == 1) c--;
771                          * and it's simpler to do it this way:
772                          */
773                         c -= point[i].type;
774                         if (c >= num_candidates - num_falsetickers) {
775                                 /* If it was c++ and it got big enough... */
776                                 low = point[i].edge;
777                                 break;
778                         }
779                         if (point[i].type == 0)
780                                 num_midpoints++;
781                 }
782                 c = 0;
783                 for (i = num_points-1; i >= 0; i--) {
784                         c += point[i].type;
785                         if (c >= num_candidates - num_falsetickers) {
786                                 high = point[i].edge;
787                                 break;
788                         }
789                         if (point[i].type == 0)
790                                 num_midpoints++;
791                 }
792                 /* If the number of midpoints is greater than the number
793                  * of allowed falsetickers, the intersection contains at
794                  * least one truechimer with no midpoint - bad.
795                  * Also, interval should be nonempty.
796                  */
797                 if (num_midpoints <= num_falsetickers && low < high)
798                         break;
799                 num_falsetickers++;
800                 if (num_falsetickers * 2 >= num_candidates) {
801                         VERB3 bb_error_msg("too many falsetickers:%d (candidates:%d), no peer selected",
802                                         num_falsetickers, num_candidates);
803                         return NULL;
804                 }
805         }
806         VERB3 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
807                         low, high, num_candidates, num_falsetickers);
808
809         /* Clustering */
810
811         /* Construct a list of survivors (p, metric)
812          * from the chime list, where metric is dominated
813          * first by stratum and then by root distance.
814          * All other things being equal, this is the order of preference.
815          */
816         num_survivors = 0;
817         for (i = 0; i < num_points; i++) {
818                 peer_t *p;
819
820                 if (point[i].edge < low || point[i].edge > high)
821                         continue;
822                 p = point[i].p;
823                 survivor[num_survivors].p = p;
824 //TODO: save root_distance in point_t and reuse here?
825                 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + root_distance(p, t);
826                 VERB4 bb_error_msg("survivor[%d] metric:%f peer:%s",
827                         num_survivors, survivor[num_survivors].metric, p->p_dotted);
828                 num_survivors++;
829         }
830         /* There must be at least MIN_SELECTED survivors to satisfy the
831          * correctness assertions. Ordinarily, the Byzantine criteria
832          * require four survivors, but for the demonstration here, one
833          * is acceptable.
834          */
835         if (num_survivors < MIN_SELECTED) {
836                 VERB3 bb_error_msg("num_survivors %d < %d, no peer selected",
837                                 num_survivors, MIN_SELECTED);
838                 return NULL;
839         }
840
841 //looks like this is ONLY used by the fact that later we pick survivor[0].
842 //we can avoid sorting then, just find the minimum once!
843         qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
844
845         /* For each association p in turn, calculate the selection
846          * jitter p->sjitter as the square root of the sum of squares
847          * (p->offset - q->offset) over all q associations. The idea is
848          * to repeatedly discard the survivor with maximum selection
849          * jitter until a termination condition is met.
850          */
851         while (1) {
852                 unsigned max_idx = max_idx;
853                 double max_selection_jitter = max_selection_jitter;
854                 double min_jitter = min_jitter;
855
856                 if (num_survivors <= MIN_CLUSTERED) {
857                         bb_error_msg("num_survivors %d <= %d, not discarding more",
858                                         num_survivors, MIN_CLUSTERED);
859                         break;
860                 }
861
862                 /* To make sure a few survivors are left
863                  * for the clustering algorithm to chew on,
864                  * we stop if the number of survivors
865                  * is less than or equal to MIN_CLUSTERED (3).
866                  */
867                 for (i = 0; i < num_survivors; i++) {
868                         double selection_jitter_sq;
869                         peer_t *p = survivor[i].p;
870
871                         if (i == 0 || p->filter_jitter < min_jitter)
872                                 min_jitter = p->filter_jitter;
873
874                         selection_jitter_sq = 0;
875                         for (j = 0; j < num_survivors; j++) {
876                                 peer_t *q = survivor[j].p;
877 //TODO: where is 1/(n-1) * ... multiplier?
878                                 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
879                         }
880                         if (i == 0 || selection_jitter_sq > max_selection_jitter) {
881                                 max_selection_jitter = selection_jitter_sq;
882                                 max_idx = i;
883                         }
884                         VERB5 bb_error_msg("survivor %d selection_jitter^2:%f",
885                                         i, selection_jitter_sq);
886                 }
887                 max_selection_jitter = SQRT(max_selection_jitter);
888                 VERB4 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
889                                 max_idx, max_selection_jitter, min_jitter);
890
891                 /* If the maximum selection jitter is less than the
892                  * minimum peer jitter, then tossing out more survivors
893                  * will not lower the minimum peer jitter, so we might
894                  * as well stop.
895                  */
896                 if (max_selection_jitter < min_jitter) {
897                         VERB3 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
898                                         max_selection_jitter, min_jitter, num_survivors);
899                         break;
900                 }
901
902                 /* Delete survivor[max_idx] from the list
903                  * and go around again.
904                  */
905                 VERB5 bb_error_msg("dropping survivor %d", max_idx);
906                 num_survivors--;
907                 while (max_idx < num_survivors) {
908                         survivor[max_idx] = survivor[max_idx + 1];
909                         max_idx++;
910                 }
911         }
912
913         /* Pick the best clock. If the old system peer is on the list
914          * and at the same stratum as the first survivor on the list,
915          * then don't do a clock hop. Otherwise, select the first
916          * survivor on the list as the new system peer.
917          */
918 //TODO - see clock_combine()
919         VERB3 bb_error_msg("selected peer %s filter_offset:%f age:%f",
920                         survivor[0].p->p_dotted,
921                         survivor[0].p->filter_offset,
922                         t - survivor[0].p->lastpkt_recv_time
923         );
924         return survivor[0].p;
925 }
926
927
928 /*
929  * Local clock discipline and its helpers
930  */
931 static void
932 set_new_values(int disc_state, double offset, double recv_time)
933 {
934         /* Enter new state and set state variables. Note we use the time
935          * of the last clock filter sample, which must be earlier than
936          * the current time.
937          */
938         VERB3 bb_error_msg("disc_state=%d last_update_offset=%f last_update_recv_time=%f",
939                         disc_state, offset, recv_time);
940         G.discipline_state = disc_state;
941         G.last_update_offset = offset;
942         G.last_update_recv_time = recv_time;
943 }
944 /* Clock state definitions */
945 #define STATE_NSET      0       /* initial state, "nothing is set" */
946 #define STATE_FSET      1       /* frequency set from file */
947 #define STATE_SPIK      2       /* spike detected */
948 #define STATE_FREQ      3       /* initial frequency */
949 #define STATE_SYNC      4       /* clock synchronized (normal operation) */
950 /* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
951 static int
952 update_local_clock(peer_t *p, double t)
953 {
954         int rc;
955         long old_tmx_offset;
956         struct timex tmx;
957         double offset = p->filter_offset;
958         double recv_time = p->lastpkt_recv_time;
959         double abs_offset;
960         double freq_drift;
961         double since_last_update;
962         double etemp, dtemp;
963
964         abs_offset = fabs(offset);
965
966         /* If the offset is too large, give up and go home */
967         if (abs_offset > PANIC_THRESHOLD) {
968                 bb_error_msg_and_die("offset %f far too big, exiting", offset);
969         }
970
971         /* If this is an old update, for instance as the result
972          * of a system peer change, avoid it. We never use
973          * an old sample or the same sample twice.
974          */
975         if (recv_time <= G.last_update_recv_time) {
976                 VERB3 bb_error_msg("same or older datapoint: %f >= %f, not using it",
977                                 G.last_update_recv_time, recv_time);
978                 return 0; /* "leave poll interval as is" */
979         }
980
981         /* Clock state machine transition function. This is where the
982          * action is and defines how the system reacts to large time
983          * and frequency errors.
984          */
985         since_last_update = recv_time - G.reftime;
986         freq_drift = 0;
987         if (G.discipline_state == STATE_FREQ) {
988                 /* Ignore updates until the stepout threshold */
989                 if (since_last_update < WATCH_THRESHOLD) {
990                         VERB3 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
991                                         WATCH_THRESHOLD - since_last_update);
992                         return 0; /* "leave poll interval as is" */
993                 }
994                 freq_drift = (offset - G.last_update_offset) / since_last_update;
995         }
996
997         /* There are two main regimes: when the
998          * offset exceeds the step threshold and when it does not.
999          */
1000         if (abs_offset > STEP_THRESHOLD) {
1001                 llist_t *item;
1002
1003                 switch (G.discipline_state) {
1004                 case STATE_SYNC:
1005                         /* The first outlyer: ignore it, switch to SPIK state */
1006                         VERB3 bb_error_msg("offset:%f - spike detected", offset);
1007                         G.discipline_state = STATE_SPIK;
1008                         return -1; /* "decrease poll interval" */
1009
1010                 case STATE_SPIK:
1011                         /* Ignore succeeding outlyers until either an inlyer
1012                          * is found or the stepout threshold is exceeded.
1013                          */
1014                         if (since_last_update < WATCH_THRESHOLD) {
1015                                 VERB3 bb_error_msg("spike detected, datapoint ignored, %f sec remains",
1016                                                 WATCH_THRESHOLD - since_last_update);
1017                                 return -1; /* "decrease poll interval" */
1018                         }
1019                         /* fall through: we need to step */
1020                 } /* switch */
1021
1022                 /* Step the time and clamp down the poll interval.
1023                  *
1024                  * In NSET state an initial frequency correction is
1025                  * not available, usually because the frequency file has
1026                  * not yet been written. Since the time is outside the
1027                  * capture range, the clock is stepped. The frequency
1028                  * will be set directly following the stepout interval.
1029                  *
1030                  * In FSET state the initial frequency has been set
1031                  * from the frequency file. Since the time is outside
1032                  * the capture range, the clock is stepped immediately,
1033                  * rather than after the stepout interval. Guys get
1034                  * nervous if it takes 17 minutes to set the clock for
1035                  * the first time.
1036                  *
1037                  * In SPIK state the stepout threshold has expired and
1038                  * the phase is still above the step threshold. Note
1039                  * that a single spike greater than the step threshold
1040                  * is always suppressed, even at the longer poll
1041                  * intervals.
1042                  */
1043                 VERB3 bb_error_msg("stepping time by %f; poll_exp=MINPOLL", offset);
1044                 step_time(offset);
1045                 if (option_mask32 & OPT_q) {
1046                         /* We were only asked to set time once. Done. */
1047                         exit(0);
1048                 }
1049
1050                 G.polladj_count = 0;
1051                 G.poll_exp = MINPOLL;
1052                 G.stratum = MAXSTRAT;
1053                 for (item = G.ntp_peers; item != NULL; item = item->link) {
1054                         peer_t *pp = (peer_t *) item->data;
1055                         reset_peer_stats(pp, t, offset);
1056                 }
1057                 if (G.discipline_state == STATE_NSET) {
1058                         set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1059                         return 1; /* "ok to increase poll interval" */
1060                 }
1061                 set_new_values(STATE_SYNC, /*offset:*/ 0, recv_time);
1062
1063         } else { /* abs_offset <= STEP_THRESHOLD */
1064
1065                 if (G.poll_exp < MINPOLL) {
1066                         VERB3 bb_error_msg("saw small offset %f, disabling burst mode", offset);
1067                         G.poll_exp = MINPOLL;
1068                 }
1069
1070                 /* Compute the clock jitter as the RMS of exponentially
1071                  * weighted offset differences. Used by the poll adjust code.
1072                  */
1073                 etemp = SQUARE(G.discipline_jitter);
1074                 dtemp = SQUARE(MAXD(fabs(offset - G.last_update_offset), G_precision_sec));
1075                 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1076                 VERB3 bb_error_msg("discipline jitter=%f", G.discipline_jitter);
1077
1078                 switch (G.discipline_state) {
1079                 case STATE_NSET:
1080                         if (option_mask32 & OPT_q) {
1081                                 /* We were only asked to set time once.
1082                                  * The clock is precise enough, no need to step.
1083                                  */
1084                                 exit(0);
1085                         }
1086                         /* This is the first update received and the frequency
1087                          * has not been initialized. The first thing to do
1088                          * is directly measure the oscillator frequency.
1089                          */
1090                         set_new_values(STATE_FREQ, offset, recv_time);
1091                         VERB3 bb_error_msg("transitioning to FREQ, datapoint ignored");
1092                         return -1; /* "decrease poll interval" */
1093
1094 #if 0 /* this is dead code for now */
1095                 case STATE_FSET:
1096                         /* This is the first update and the frequency
1097                          * has been initialized. Adjust the phase, but
1098                          * don't adjust the frequency until the next update.
1099                          */
1100                         set_new_values(STATE_SYNC, offset, recv_time);
1101                         /* freq_drift remains 0 */
1102                         break;
1103 #endif
1104
1105                 case STATE_FREQ:
1106                         /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1107                          * Correct the phase and frequency and switch to SYNC state.
1108                          * freq_drift was already estimated (see code above)
1109                          */
1110                         set_new_values(STATE_SYNC, offset, recv_time);
1111                         break;
1112
1113                 default:
1114                         /* Compute freq_drift due to PLL and FLL contributions.
1115                          *
1116                          * The FLL and PLL frequency gain constants
1117                          * depend on the poll interval and Allan
1118                          * intercept. The FLL is not used below one-half
1119                          * the Allan intercept. Above that the loop gain
1120                          * increases in steps to 1 / AVG.
1121                          */
1122                         if ((1 << G.poll_exp) > ALLAN / 2) {
1123                                 etemp = FLL - G.poll_exp;
1124                                 if (etemp < AVG)
1125                                         etemp = AVG;
1126                                 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1127                         }
1128                         /* For the PLL the integration interval
1129                          * (numerator) is the minimum of the update
1130                          * interval and poll interval. This allows
1131                          * oversampling, but not undersampling.
1132                          */
1133                         etemp = MIND(since_last_update, (1 << G.poll_exp));
1134                         dtemp = (4 * PLL) << G.poll_exp;
1135                         freq_drift += offset * etemp / SQUARE(dtemp);
1136                         set_new_values(STATE_SYNC, offset, recv_time);
1137                         break;
1138                 }
1139                 G.stratum = p->lastpkt_stratum + 1;
1140         }
1141
1142         G.reftime = t;
1143         G.leap = p->lastpkt_leap;
1144         G.refid = p->lastpkt_refid;
1145         G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1146         dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(s.jitter));
1147         dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (t - p->lastpkt_recv_time) + abs_offset, MINDISP);
1148         G.rootdisp = p->lastpkt_rootdisp + dtemp;
1149         VERB3 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1150
1151         /* We are in STATE_SYNC now, but did not do adjtimex yet.
1152          * (Any other state does not reach this, they all return earlier)
1153          * By this time, freq_drift and G.last_update_offset are set
1154          * to values suitable for adjtimex.
1155          *
1156          * Calculate the new frequency drift and frequency stability (wander).
1157          * Compute the clock wander as the RMS of exponentially weighted
1158          * frequency differences. This is not used directly, but can,
1159          * along with the jitter, be a highly useful monitoring and
1160          * debugging tool.
1161          */
1162         dtemp = G.discipline_freq_drift + freq_drift;
1163         G.discipline_freq_drift = MAXD(MIND(MAXFREQ, dtemp), -MAXFREQ);
1164         etemp = SQUARE(G.discipline_wander);
1165         dtemp = SQUARE(dtemp);
1166         G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1167
1168         VERB3 {
1169                 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1170                                 G.discipline_freq_drift,
1171                                 (long)(G.discipline_freq_drift * 65536e6),
1172                                 freq_drift,
1173                                 G.discipline_wander);
1174                 memset(&tmx, 0, sizeof(tmx));
1175                 if (adjtimex(&tmx) < 0)
1176                         bb_perror_msg_and_die("adjtimex");
1177                 VERB3 bb_error_msg("p adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1178                                 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1179         }
1180
1181         old_tmx_offset = 0;
1182         if (!G.adjtimex_was_done) {
1183                 G.adjtimex_was_done = 1;
1184                 /* When we use adjtimex for the very first time,
1185                  * we need to ADD to pre-existing tmx.offset - it may be !0
1186                  */
1187                 memset(&tmx, 0, sizeof(tmx));
1188                 if (adjtimex(&tmx) < 0)
1189                         bb_perror_msg_and_die("adjtimex");
1190                 old_tmx_offset = tmx.offset;
1191         }
1192         memset(&tmx, 0, sizeof(tmx));
1193 #if 0
1194 //doesn't work, offset remains 0 (!):
1195 //ntpd:  set adjtimex freq:1786097 tmx.offset:77487
1196 //ntpd: prev adjtimex freq:1786097 tmx.offset:0
1197 //ntpd:  cur adjtimex freq:1786097 tmx.offset:0
1198         tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1199         /* 65536 is one ppm */
1200         tmx.freq = G.discipline_freq_drift * 65536e6;
1201         tmx.offset = G.last_update_offset * 1000000; /* usec */
1202 #endif
1203         tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1204         tmx.offset = (G.last_update_offset * 1000000) /* usec */
1205                         /* + (G.last_update_offset < 0 ? -0.5 : 0.5) - too small to bother */
1206                         + old_tmx_offset; /* almost always 0 */
1207         tmx.status = STA_PLL;
1208         //if (sys_leap == LEAP_ADDSECOND)
1209         //      tmx.status |= STA_INS;
1210         //else if (sys_leap == LEAP_DELSECOND)
1211         //      tmx.status |= STA_DEL;
1212         tmx.constant = G.poll_exp - 4;
1213         //tmx.esterror = (u_int32)(clock_jitter * 1e6);
1214         //tmx.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1215         VERB3 bb_error_msg("b adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1216                         tmx.freq, tmx.offset, tmx.constant, tmx.status);
1217         rc = adjtimex(&tmx);
1218         if (rc < 0)
1219                 bb_perror_msg_and_die("adjtimex");
1220         VERB3 {
1221                 bb_error_msg("adjtimex:%d freq:%ld offset:%ld constant:%ld status:0x%x",
1222                                 rc, tmx.freq, tmx.offset, tmx.constant, tmx.status);
1223                 memset(&tmx, 0, sizeof(tmx));
1224                 if (adjtimex(&tmx) < 0)
1225                         bb_perror_msg_and_die("adjtimex");
1226                 VERB3 bb_error_msg("c adjtimex freq:%ld offset:%ld constant:%ld status:0x%x",
1227                                 tmx.freq, tmx.offset, tmx.constant, tmx.status);
1228         }
1229 // #define STA_MODE 0x4000  /* mode (0 = PLL, 1 = FLL) (ro) */ - ?
1230 // it appeared after a while:
1231 //ntpd: p adjtimex freq:-14545653 offset:-5396 constant:10 status:0x41
1232 //ntpd: c adjtimex freq:-14547835 offset:-8307 constant:10 status:0x1
1233 //ntpd: p adjtimex freq:-14547835 offset:-6398 constant:10 status:0x41
1234 //ntpd: c adjtimex freq:-14550486 offset:-10158 constant:10 status:0x1
1235 //ntpd: p adjtimex freq:-14550486 offset:-6132 constant:10 status:0x41
1236 //ntpd: c adjtimex freq:-14636129 offset:-10158 constant:10 status:0x4001
1237 //ntpd: p adjtimex freq:-14636129 offset:-10002 constant:10 status:0x4041
1238 //ntpd: c adjtimex freq:-14636245 offset:-7497 constant:10 status:0x1
1239 //ntpd: p adjtimex freq:-14636245 offset:-4573 constant:10 status:0x41
1240 //ntpd: c adjtimex freq:-14642034 offset:-11715 constant:10 status:0x1
1241 //ntpd: p adjtimex freq:-14642034 offset:-4098 constant:10 status:0x41
1242 //ntpd: c adjtimex freq:-14699112 offset:-11746 constant:10 status:0x4001
1243 //ntpd: p adjtimex freq:-14699112 offset:-4239 constant:10 status:0x4041
1244 //ntpd: c adjtimex freq:-14762330 offset:-12786 constant:10 status:0x4001
1245 //ntpd: p adjtimex freq:-14762330 offset:-4434 constant:10 status:0x4041
1246 //ntpd: b adjtimex freq:0 offset:-9669 constant:8 status:0x1
1247 //ntpd: adjtimex:0 freq:-14809095 offset:-9669 constant:10 status:0x4001
1248 //ntpd: c adjtimex freq:-14809095 offset:-9669 constant:10 status:0x4001
1249
1250         return 1; /* "ok to increase poll interval" */
1251 }
1252
1253
1254 /*
1255  * We've got a new reply packet from a peer, process it
1256  * (helpers first)
1257  */
1258 static unsigned
1259 retry_interval(void)
1260 {
1261         /* Local problem, want to retry soon */
1262         unsigned interval, r;
1263         interval = RETRY_INTERVAL;
1264         r = random();
1265         interval += r % (unsigned)(RETRY_INTERVAL / 4);
1266         VERB3 bb_error_msg("chose retry interval:%u", interval);
1267         return interval;
1268 }
1269 static unsigned
1270 poll_interval(int exponent) /* exp is always -1 or 0 */
1271 {
1272         /* Want to send next packet at (1 << G.poll_exp) + small random value */
1273         unsigned interval, r;
1274         exponent += G.poll_exp; /* G.poll_exp is always > 0 */
1275         /* never true: if (exp < 0) exp = 0; */
1276         interval = 1 << exponent;
1277         r = random();
1278         interval += ((r & (interval-1)) >> 4) + ((r >> 8) & 1); /* + 1/16 of interval, max */
1279         VERB3 bb_error_msg("chose poll interval:%u (poll_exp:%d exp:%d)", interval, G.poll_exp, exponent);
1280         return interval;
1281 }
1282 static void
1283 recv_and_process_peer_pkt(peer_t *p)
1284 {
1285         int         rc;
1286         ssize_t     size;
1287         msg_t       msg;
1288         double      T1, T2, T3, T4;
1289         unsigned    interval;
1290         datapoint_t *datapoint;
1291         peer_t      *q;
1292
1293         /* We can recvfrom here and check from.IP, but some multihomed
1294          * ntp servers reply from their *other IP*.
1295          * TODO: maybe we should check at least what we can: from.port == 123?
1296          */
1297         size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
1298         if (size == -1) {
1299                 bb_perror_msg("recv(%s) error", p->p_dotted);
1300                 if (errno == EHOSTUNREACH || errno == EHOSTDOWN
1301                  || errno == ENETUNREACH || errno == ENETDOWN
1302                  || errno == ECONNREFUSED || errno == EADDRNOTAVAIL
1303                  || errno == EAGAIN
1304                 ) {
1305 //TODO: always do this?
1306                         set_next(p, retry_interval());
1307                         goto close_sock;
1308                 }
1309                 xfunc_die();
1310         }
1311
1312         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1313                 bb_error_msg("malformed packet received from %s", p->p_dotted);
1314                 goto bail;
1315         }
1316
1317         if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
1318          || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
1319         ) {
1320                 goto bail;
1321         }
1322
1323         if ((msg.m_status & LI_ALARM) == LI_ALARM
1324          || msg.m_stratum == 0
1325          || msg.m_stratum > NTP_MAXSTRATUM
1326         ) {
1327 // TODO: stratum 0 responses may have commands in 32-bit m_refid field:
1328 // "DENY", "RSTR" - peer does not like us at all
1329 // "RATE" - peer is overloaded, reduce polling freq
1330                 interval = poll_interval(0);
1331                 bb_error_msg("reply from %s: not synced, next query in %us", p->p_dotted, interval);
1332                 goto close_sock;
1333         }
1334
1335 //      /*
1336 //       * Verify the server is synchronized with valid stratum and
1337 //       * reference time not later than the transmit time.
1338 //       */
1339 //      if (p->lastpkt_leap == NOSYNC || p->lastpkt_stratum >= MAXSTRAT)
1340 //              return;                 /* unsynchronized */
1341 //
1342 //      /* Verify valid root distance */
1343 //      if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
1344 //              return;                 /* invalid header values */
1345
1346         p->lastpkt_leap = msg.m_status;
1347         p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
1348         p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
1349         p->lastpkt_refid = msg.m_refid;
1350
1351         /*
1352          * From RFC 2030 (with a correction to the delay math):
1353          *
1354          * Timestamp Name          ID   When Generated
1355          * ------------------------------------------------------------
1356          * Originate Timestamp     T1   time request sent by client
1357          * Receive Timestamp       T2   time request received by server
1358          * Transmit Timestamp      T3   time reply sent by server
1359          * Destination Timestamp   T4   time reply received by client
1360          *
1361          * The roundtrip delay and local clock offset are defined as
1362          *
1363          * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
1364          */
1365         T1 = p->p_xmttime;
1366         T2 = lfp_to_d(msg.m_rectime);
1367         T3 = lfp_to_d(msg.m_xmttime);
1368         T4 = gettime1900d();
1369
1370         p->lastpkt_recv_time = T4;
1371
1372         VERB5 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
1373         p->datapoint_idx = p->p_reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
1374         datapoint = &p->filter_datapoint[p->datapoint_idx];
1375         datapoint->d_recv_time = T4;
1376         datapoint->d_offset    = ((T2 - T1) + (T3 - T4)) / 2;
1377         /* The delay calculation is a special case. In cases where the
1378          * server and client clocks are running at different rates and
1379          * with very fast networks, the delay can appear negative. In
1380          * order to avoid violating the Principle of Least Astonishment,
1381          * the delay is clamped not less than the system precision.
1382          */
1383         p->lastpkt_delay = (T4 - T1) - (T3 - T2);
1384         datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
1385         if (!p->p_reachable_bits) {
1386                 /* 1st datapoint ever - replicate offset in every element */
1387                 int i;
1388                 for (i = 1; i < NUM_DATAPOINTS; i++) {
1389                         p->filter_datapoint[i].d_offset = datapoint->d_offset;
1390                 }
1391         }
1392
1393         p->p_reachable_bits |= 1;
1394         VERB1 {
1395                 bb_error_msg("reply from %s: reach 0x%02x offset %f delay %f",
1396                         p->p_dotted,
1397                         p->p_reachable_bits,
1398                         datapoint->d_offset, p->lastpkt_delay);
1399         }
1400
1401         /* Muck with statictics and update the clock */
1402         filter_datapoints(p, T4);
1403         q = select_and_cluster(T4);
1404         rc = -1;
1405         if (q)
1406                 rc = update_local_clock(q, T4);
1407
1408         if (rc != 0) {
1409                 /* Adjust the poll interval by comparing the current offset
1410                  * with the clock jitter. If the offset is less than
1411                  * the clock jitter times a constant, then the averaging interval
1412                  * is increased, otherwise it is decreased. A bit of hysteresis
1413                  * helps calm the dance. Works best using burst mode.
1414                  */
1415                 VERB4 if (rc > 0) {
1416                         bb_error_msg("offset:%f POLLADJ_GATE*discipline_jitter:%f poll:%s",
1417                                 q->filter_offset, POLLADJ_GATE * G.discipline_jitter,
1418                                 fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter
1419                                         ? "grows" : "falls"
1420                         );
1421                 }
1422                 if (rc > 0 && fabs(q->filter_offset) < POLLADJ_GATE * G.discipline_jitter) {
1423                         G.polladj_count += G.poll_exp;
1424                         if (G.polladj_count > POLLADJ_LIMIT) {
1425                                 G.polladj_count = 0;
1426                                 if (G.poll_exp < MAXPOLL) {
1427                                         G.poll_exp++;
1428                                         VERB3 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1429                                                         G.discipline_jitter, G.poll_exp);
1430                                 }
1431                         } else {
1432                                 VERB3 bb_error_msg("polladj: incr:%d", G.polladj_count);
1433                         }
1434                 } else {
1435                         G.polladj_count -= G.poll_exp * 2;
1436                         if (G.polladj_count < -POLLADJ_LIMIT) {
1437                                 G.polladj_count = 0;
1438                                 if (G.poll_exp > MINPOLL) {
1439                                         G.poll_exp--;
1440                                         VERB3 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
1441                                                         G.discipline_jitter, G.poll_exp);
1442                                 }
1443                         } else {
1444                                 VERB3 bb_error_msg("polladj: decr:%d", G.polladj_count);
1445                         }
1446                 }
1447         }
1448
1449         /* Decide when to send new query for this peer */
1450         interval = poll_interval(0);
1451         set_next(p, interval);
1452
1453  close_sock:
1454         /* We do not expect any more packets from this peer for now.
1455          * Closing the socket informs kernel about it.
1456          * We open a new socket when we send a new query.
1457          */
1458         close(p->p_fd);
1459         p->p_fd = -1;
1460  bail:
1461         return;
1462 }
1463
1464 #if ENABLE_FEATURE_NTPD_SERVER
1465 static void
1466 recv_and_process_client_pkt(void /*int fd*/)
1467 {
1468         ssize_t          size;
1469         uint8_t          version;
1470         double           rectime;
1471         len_and_sockaddr *to;
1472         struct sockaddr  *from;
1473         msg_t            msg;
1474         uint8_t          query_status;
1475         l_fixedpt_t      query_xmttime;
1476
1477         to = get_sock_lsa(G.listen_fd);
1478         from = xzalloc(to->len);
1479
1480         size = recv_from_to(G.listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
1481         if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE) {
1482                 char *addr;
1483                 if (size < 0) {
1484                         if (errno == EAGAIN)
1485                                 goto bail;
1486                         bb_perror_msg_and_die("recv");
1487                 }
1488                 addr = xmalloc_sockaddr2dotted_noport(from);
1489                 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
1490                 free(addr);
1491                 goto bail;
1492         }
1493
1494         query_status = msg.m_status;
1495         query_xmttime = msg.m_xmttime;
1496
1497         /* Build a reply packet */
1498         memset(&msg, 0, sizeof(msg));
1499         msg.m_status = G.stratum < MAXSTRAT ? G.leap : LI_ALARM;
1500         msg.m_status |= (query_status & VERSION_MASK);
1501         msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
1502                          MODE_SERVER : MODE_SYM_PAS;
1503         msg.m_stratum = G.stratum;
1504         msg.m_ppoll = G.poll_exp;
1505         msg.m_precision_exp = G_precision_exp;
1506         rectime = gettime1900d();
1507         msg.m_xmttime = msg.m_rectime = d_to_lfp(rectime);
1508         msg.m_reftime = d_to_lfp(G.reftime);
1509         msg.m_orgtime = query_xmttime;
1510         msg.m_rootdelay = d_to_sfp(G.rootdelay);
1511 //simple code does not do this, fix simple code!
1512         msg.m_rootdisp = d_to_sfp(G.rootdisp);
1513         version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
1514         msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
1515
1516         /* We reply from the local address packet was sent to,
1517          * this makes to/from look swapped here: */
1518         do_sendto(G.listen_fd,
1519                 /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
1520                 &msg, size);
1521
1522  bail:
1523         free(to);
1524         free(from);
1525 }
1526 #endif
1527
1528 /* Upstream ntpd's options:
1529  *
1530  * -4   Force DNS resolution of host names to the IPv4 namespace.
1531  * -6   Force DNS resolution of host names to the IPv6 namespace.
1532  * -a   Require cryptographic authentication for broadcast client,
1533  *      multicast client and symmetric passive associations.
1534  *      This is the default.
1535  * -A   Do not require cryptographic authentication for broadcast client,
1536  *      multicast client and symmetric passive associations.
1537  *      This is almost never a good idea.
1538  * -b   Enable the client to synchronize to broadcast servers.
1539  * -c conffile
1540  *      Specify the name and path of the configuration file,
1541  *      default /etc/ntp.conf
1542  * -d   Specify debugging mode. This option may occur more than once,
1543  *      with each occurrence indicating greater detail of display.
1544  * -D level
1545  *      Specify debugging level directly.
1546  * -f driftfile
1547  *      Specify the name and path of the frequency file.
1548  *      This is the same operation as the "driftfile FILE"
1549  *      configuration command.
1550  * -g   Normally, ntpd exits with a message to the system log
1551  *      if the offset exceeds the panic threshold, which is 1000 s
1552  *      by default. This option allows the time to be set to any value
1553  *      without restriction; however, this can happen only once.
1554  *      If the threshold is exceeded after that, ntpd will exit
1555  *      with a message to the system log. This option can be used
1556  *      with the -q and -x options. See the tinker command for other options.
1557  * -i jaildir
1558  *      Chroot the server to the directory jaildir. This option also implies
1559  *      that the server attempts to drop root privileges at startup
1560  *      (otherwise, chroot gives very little additional security).
1561  *      You may need to also specify a -u option.
1562  * -k keyfile
1563  *      Specify the name and path of the symmetric key file,
1564  *      default /etc/ntp/keys. This is the same operation
1565  *      as the "keys FILE" configuration command.
1566  * -l logfile
1567  *      Specify the name and path of the log file. The default
1568  *      is the system log file. This is the same operation as
1569  *      the "logfile FILE" configuration command.
1570  * -L   Do not listen to virtual IPs. The default is to listen.
1571  * -n   Don't fork.
1572  * -N   To the extent permitted by the operating system,
1573  *      run the ntpd at the highest priority.
1574  * -p pidfile
1575  *      Specify the name and path of the file used to record the ntpd
1576  *      process ID. This is the same operation as the "pidfile FILE"
1577  *      configuration command.
1578  * -P priority
1579  *      To the extent permitted by the operating system,
1580  *      run the ntpd at the specified priority.
1581  * -q   Exit the ntpd just after the first time the clock is set.
1582  *      This behavior mimics that of the ntpdate program, which is
1583  *      to be retired. The -g and -x options can be used with this option.
1584  *      Note: The kernel time discipline is disabled with this option.
1585  * -r broadcastdelay
1586  *      Specify the default propagation delay from the broadcast/multicast
1587  *      server to this client. This is necessary only if the delay
1588  *      cannot be computed automatically by the protocol.
1589  * -s statsdir
1590  *      Specify the directory path for files created by the statistics
1591  *      facility. This is the same operation as the "statsdir DIR"
1592  *      configuration command.
1593  * -t key
1594  *      Add a key number to the trusted key list. This option can occur
1595  *      more than once.
1596  * -u user[:group]
1597  *      Specify a user, and optionally a group, to switch to.
1598  * -v variable
1599  * -V variable
1600  *      Add a system variable listed by default.
1601  * -x   Normally, the time is slewed if the offset is less than the step
1602  *      threshold, which is 128 ms by default, and stepped if above
1603  *      the threshold. This option sets the threshold to 600 s, which is
1604  *      well within the accuracy window to set the clock manually.
1605  *      Note: since the slew rate of typical Unix kernels is limited
1606  *      to 0.5 ms/s, each second of adjustment requires an amortization
1607  *      interval of 2000 s. Thus, an adjustment as much as 600 s
1608  *      will take almost 14 days to complete. This option can be used
1609  *      with the -g and -q options. See the tinker command for other options.
1610  *      Note: The kernel time discipline is disabled with this option.
1611  */
1612
1613 /* By doing init in a separate function we decrease stack usage
1614  * in main loop.
1615  */
1616 static NOINLINE void ntp_init(char **argv)
1617 {
1618         unsigned opts;
1619         llist_t *peers;
1620
1621         srandom(getpid());
1622
1623         if (getuid())
1624                 bb_error_msg_and_die(bb_msg_you_must_be_root);
1625
1626         /* Set some globals */
1627 #if 0
1628         /* With constant b = 100, G.precision_exp is also constant -6.
1629          * Uncomment this to verify.
1630          */
1631         {
1632                 int prec = 0;
1633                 int b;
1634 # if 0
1635                 struct timespec tp;
1636                 /* We can use sys_clock_getres but assuming 10ms tick should be fine */
1637                 clock_getres(CLOCK_REALTIME, &tp);
1638                 tp.tv_sec = 0;
1639                 tp.tv_nsec = 10000000;
1640                 b = 1000000000 / tp.tv_nsec;  /* convert to Hz */
1641 # else
1642                 b = 100; /* b = 1000000000/10000000 = 100 */
1643 # endif
1644                 while (b > 1)
1645                         prec--, b >>= 1;
1646                 /*G.precision_exp = prec;*/
1647                 /*G.precision_sec = (1.0 / (1 << (- prec)));*/
1648                 bb_error_msg("G.precision_exp:%d sec:%f", prec, G_precision_sec); /* -6 */
1649         }
1650 #endif
1651         G.stratum = MAXSTRAT;
1652         G.poll_exp = 1; /* should use MINPOLL, but 1 speeds up initial sync */
1653         G.reftime = G.last_update_recv_time = gettime1900d();
1654
1655         /* Parse options */
1656         peers = NULL;
1657         opt_complementary = "dd:p::"; /* d: counter, p: list */
1658         opts = getopt32(argv,
1659                         "nqNx" /* compat */
1660                         "p:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
1661                         "d" /* compat */
1662                         "46aAbgL", /* compat, ignored */
1663                         &peers, &G.verbose);
1664         if (!(opts & (OPT_p|OPT_l)))
1665                 bb_show_usage();
1666 //      if (opts & OPT_x) /* disable stepping, only slew is allowed */
1667 //              G.time_was_stepped = 1;
1668         while (peers)
1669                 add_peers(llist_pop(&peers));
1670         if (!(opts & OPT_n)) {
1671                 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
1672                 logmode = LOGMODE_NONE;
1673         }
1674 #if ENABLE_FEATURE_NTPD_SERVER
1675         G.listen_fd = -1;
1676         if (opts & OPT_l) {
1677                 G.listen_fd = create_and_bind_dgram_or_die(NULL, 123);
1678                 socket_want_pktinfo(G.listen_fd);
1679                 setsockopt(G.listen_fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
1680         }
1681 #endif
1682         /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
1683         if (opts & OPT_N)
1684                 setpriority(PRIO_PROCESS, 0, -15);
1685
1686         bb_signals((1 << SIGTERM) | (1 << SIGINT), record_signo);
1687         bb_signals((1 << SIGPIPE) | (1 << SIGHUP), SIG_IGN);
1688 }
1689
1690 int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
1691 int ntpd_main(int argc UNUSED_PARAM, char **argv)
1692 {
1693         struct globals g;
1694         struct pollfd *pfd;
1695         peer_t **idx2peer;
1696
1697         memset(&g, 0, sizeof(g));
1698         SET_PTR_TO_GLOBALS(&g);
1699
1700         ntp_init(argv);
1701
1702         {
1703                 /* if ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
1704                 unsigned cnt = g.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
1705                 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
1706                 pfd = xzalloc(sizeof(pfd[0]) * cnt);
1707         }
1708
1709         while (!bb_got_signal) {
1710                 llist_t *item;
1711                 unsigned i, j;
1712                 unsigned sent_cnt, trial_cnt;
1713                 int nfds, timeout;
1714                 time_t cur_time, nextaction;
1715
1716                 /* Nothing between here and poll() blocks for any significant time */
1717
1718                 cur_time = time(NULL);
1719                 nextaction = cur_time + 3600;
1720
1721                 i = 0;
1722 #if ENABLE_FEATURE_NTPD_SERVER
1723                 if (g.listen_fd != -1) {
1724                         pfd[0].fd = g.listen_fd;
1725                         pfd[0].events = POLLIN;
1726                         i++;
1727                 }
1728 #endif
1729                 /* Pass over peer list, send requests, time out on receives */
1730                 sent_cnt = trial_cnt = 0;
1731                 for (item = g.ntp_peers; item != NULL; item = item->link) {
1732                         peer_t *p = (peer_t *) item->data;
1733
1734                         /* Overflow-safe "if (p->next_action_time <= cur_time) ..." */
1735                         if ((int)(cur_time - p->next_action_time) >= 0) {
1736                                 if (p->p_fd == -1) {
1737                                         /* Time to send new req */
1738                                         trial_cnt++;
1739                                         if (send_query_to_peer(p) == 0)
1740                                                 sent_cnt++;
1741                                 } else {
1742                                         /* Timed out waiting for reply */
1743                                         close(p->p_fd);
1744                                         p->p_fd = -1;
1745                                         timeout = poll_interval(-1); /* try a bit faster */
1746                                         bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
1747                                                         p->p_dotted, p->p_reachable_bits, timeout);
1748                                         set_next(p, timeout);
1749                                 }
1750                         }
1751
1752                         if (p->next_action_time < nextaction)
1753                                 nextaction = p->next_action_time;
1754
1755                         if (p->p_fd >= 0) {
1756                                 /* Wait for reply from this peer */
1757                                 pfd[i].fd = p->p_fd;
1758                                 pfd[i].events = POLLIN;
1759                                 idx2peer[i] = p;
1760                                 i++;
1761                         }
1762                 }
1763
1764 //              if ((trial_cnt > 0 && sent_cnt == 0) || g.peer_cnt == 0) {
1765 //                      G.time_was_stepped = 1;
1766 //              }
1767
1768                 timeout = nextaction - cur_time;
1769                 if (timeout < 1)
1770                         timeout = 1;
1771
1772                 /* Here we may block */
1773                 VERB2 bb_error_msg("poll %us, sockets:%u", timeout, i);
1774                 nfds = poll(pfd, i, timeout * 1000);
1775                 if (nfds <= 0)
1776                         continue;
1777
1778                 /* Process any received packets */
1779                 j = 0;
1780 #if ENABLE_FEATURE_NTPD_SERVER
1781                 if (g.listen_fd != -1) {
1782                         if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
1783                                 nfds--;
1784                                 recv_and_process_client_pkt(/*g.listen_fd*/);
1785                         }
1786                         j = 1;
1787                 }
1788 #endif
1789                 for (; nfds != 0 && j < i; j++) {
1790                         if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
1791                                 nfds--;
1792                                 recv_and_process_peer_pkt(idx2peer[j]);
1793                         }
1794                 }
1795         } /* while (!bb_got_signal) */
1796
1797         kill_myself_with_sig(bb_got_signal);
1798 }
1799
1800
1801
1802
1803
1804
1805 /*** openntpd-4.6 uses only adjtime, not adjtimex ***/
1806
1807 /*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
1808
1809 #if 0
1810 static double
1811 direct_freq(double fp_offset)
1812 {
1813
1814 #ifdef KERNEL_PLL
1815         /*
1816          * If the kernel is enabled, we need the residual offset to
1817          * calculate the frequency correction.
1818          */
1819         if (pll_control && kern_enable) {
1820                 memset(&ntv, 0, sizeof(ntv));
1821                 ntp_adjtime(&ntv);
1822 #ifdef STA_NANO
1823                 clock_offset = ntv.offset / 1e9;
1824 #else /* STA_NANO */
1825                 clock_offset = ntv.offset / 1e6;
1826 #endif /* STA_NANO */
1827                 drift_comp = FREQTOD(ntv.freq);
1828         }
1829 #endif /* KERNEL_PLL */
1830         set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
1831         wander_resid = 0;
1832         return drift_comp;
1833 }
1834
1835 static void
1836 set_freq(double freq) /* frequency update */
1837 {
1838         char tbuf[80];
1839
1840         drift_comp = freq;
1841
1842 #ifdef KERNEL_PLL
1843         /*
1844          * If the kernel is enabled, update the kernel frequency.
1845          */
1846         if (pll_control && kern_enable) {
1847                 memset(&ntv, 0, sizeof(ntv));
1848                 ntv.modes = MOD_FREQUENCY;
1849                 ntv.freq = DTOFREQ(drift_comp);
1850                 ntp_adjtime(&ntv);
1851                 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
1852                 report_event(EVNT_FSET, NULL, tbuf);
1853         } else {
1854                 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
1855                 report_event(EVNT_FSET, NULL, tbuf);
1856         }
1857 #else /* KERNEL_PLL */
1858         snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
1859         report_event(EVNT_FSET, NULL, tbuf);
1860 #endif /* KERNEL_PLL */
1861 }
1862
1863 ...
1864 ...
1865 ...
1866
1867 #ifdef KERNEL_PLL
1868         /*
1869          * This code segment works when clock adjustments are made using
1870          * precision time kernel support and the ntp_adjtime() system
1871          * call. This support is available in Solaris 2.6 and later,
1872          * Digital Unix 4.0 and later, FreeBSD, Linux and specially
1873          * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
1874          * DECstation 5000/240 and Alpha AXP, additional kernel
1875          * modifications provide a true microsecond clock and nanosecond
1876          * clock, respectively.
1877          *
1878          * Important note: The kernel discipline is used only if the
1879          * step threshold is less than 0.5 s, as anything higher can
1880          * lead to overflow problems. This might occur if some misguided
1881          * lad set the step threshold to something ridiculous.
1882          */
1883         if (pll_control && kern_enable) {
1884
1885 #define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
1886
1887                 /*
1888                  * We initialize the structure for the ntp_adjtime()
1889                  * system call. We have to convert everything to
1890                  * microseconds or nanoseconds first. Do not update the
1891                  * system variables if the ext_enable flag is set. In
1892                  * this case, the external clock driver will update the
1893                  * variables, which will be read later by the local
1894                  * clock driver. Afterwards, remember the time and
1895                  * frequency offsets for jitter and stability values and
1896                  * to update the frequency file.
1897                  */
1898                 memset(&ntv,  0, sizeof(ntv));
1899                 if (ext_enable) {
1900                         ntv.modes = MOD_STATUS;
1901                 } else {
1902 #ifdef STA_NANO
1903                         ntv.modes = MOD_BITS | MOD_NANO;
1904 #else /* STA_NANO */
1905                         ntv.modes = MOD_BITS;
1906 #endif /* STA_NANO */
1907                         if (clock_offset < 0)
1908                                 dtemp = -.5;
1909                         else
1910                                 dtemp = .5;
1911 #ifdef STA_NANO
1912                         ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
1913                         ntv.constant = sys_poll;
1914 #else /* STA_NANO */
1915                         ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
1916                         ntv.constant = sys_poll - 4;
1917 #endif /* STA_NANO */
1918                         ntv.esterror = (u_int32)(clock_jitter * 1e6);
1919                         ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1920                         ntv.status = STA_PLL;
1921
1922                         /*
1923                          * Enable/disable the PPS if requested.
1924                          */
1925                         if (pps_enable) {
1926                                 if (!(pll_status & STA_PPSTIME))
1927                                         report_event(EVNT_KERN,
1928                                             NULL, "PPS enabled");
1929                                 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
1930                         } else {
1931                                 if (pll_status & STA_PPSTIME)
1932                                         report_event(EVNT_KERN,
1933                                             NULL, "PPS disabled");
1934                                 ntv.status &= ~(STA_PPSTIME |
1935                                     STA_PPSFREQ);
1936                         }
1937                         if (sys_leap == LEAP_ADDSECOND)
1938                                 ntv.status |= STA_INS;
1939                         else if (sys_leap == LEAP_DELSECOND)
1940                                 ntv.status |= STA_DEL;
1941                 }
1942
1943                 /*
1944                  * Pass the stuff to the kernel. If it squeals, turn off
1945                  * the pps. In any case, fetch the kernel offset,
1946                  * frequency and jitter.
1947                  */
1948                 if (ntp_adjtime(&ntv) == TIME_ERROR) {
1949                         if (!(ntv.status & STA_PPSSIGNAL))
1950                                 report_event(EVNT_KERN, NULL,
1951                                     "PPS no signal");
1952                 }
1953                 pll_status = ntv.status;
1954 #ifdef STA_NANO
1955                 clock_offset = ntv.offset / 1e9;
1956 #else /* STA_NANO */
1957                 clock_offset = ntv.offset / 1e6;
1958 #endif /* STA_NANO */
1959                 clock_frequency = FREQTOD(ntv.freq);
1960
1961                 /*
1962                  * If the kernel PPS is lit, monitor its performance.
1963                  */
1964                 if (ntv.status & STA_PPSTIME) {
1965 #ifdef STA_NANO
1966                         clock_jitter = ntv.jitter / 1e9;
1967 #else /* STA_NANO */
1968                         clock_jitter = ntv.jitter / 1e6;
1969 #endif /* STA_NANO */
1970                 }
1971
1972 #if defined(STA_NANO) && NTP_API == 4
1973                 /*
1974                  * If the TAI changes, update the kernel TAI.
1975                  */
1976                 if (loop_tai != sys_tai) {
1977                         loop_tai = sys_tai;
1978                         ntv.modes = MOD_TAI;
1979                         ntv.constant = sys_tai;
1980                         ntp_adjtime(&ntv);
1981                 }
1982 #endif /* STA_NANO */
1983         }
1984 #endif /* KERNEL_PLL */
1985 #endif