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