busybox/networking/ntpd.c
<<
>>
Prefs
   1/*
   2 * NTP client/server, based on OpenNTPD 3.9p1
   3 *
   4 * Busybox port author: Adam Tkac (C) 2009 <vonsch@gmail.com>
   5 *
   6 * OpenNTPd 3.9p1 copyright holders:
   7 *   Copyright (c) 2003, 2004 Henning Brauer <henning@openbsd.org>
   8 *   Copyright (c) 2004 Alexander Guy <alexander.guy@andern.org>
   9 *
  10 * OpenNTPd code is licensed under ISC-style licence:
  11 *
  12 * Permission to use, copy, modify, and distribute this software for any
  13 * purpose with or without fee is hereby granted, provided that the above
  14 * copyright notice and this permission notice appear in all copies.
  15 *
  16 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  17 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  18 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  19 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  20 * WHATSOEVER RESULTING FROM LOSS OF MIND, USE, DATA OR PROFITS, WHETHER
  21 * IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING
  22 * OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  23 ***********************************************************************
  24 *
  25 * Parts of OpenNTPD clock syncronization code is replaced by
  26 * code which is based on ntp-4.2.6, which carries the following
  27 * copyright notice:
  28 *
  29 * Copyright (c) University of Delaware 1992-2009
  30 *
  31 * Permission to use, copy, modify, and distribute this software and
  32 * its documentation for any purpose with or without fee is hereby
  33 * granted, provided that the above copyright notice appears in all
  34 * copies and that both the copyright notice and this permission
  35 * notice appear in supporting documentation, and that the name
  36 * University of Delaware not be used in advertising or publicity
  37 * pertaining to distribution of the software without specific,
  38 * written prior permission. The University of Delaware makes no
  39 * representations about the suitability this software for any
  40 * purpose. It is provided "as is" without express or implied warranty.
  41 ***********************************************************************
  42 */
  43//config:config NTPD
  44//config:       bool "ntpd (22 kb)"
  45//config:       default y
  46//config:       help
  47//config:       The NTP client/server daemon.
  48//config:
  49//config:config FEATURE_NTPD_SERVER
  50//config:       bool "Make ntpd usable as a NTP server"
  51//config:       default y
  52//config:       depends on NTPD
  53//config:       help
  54//config:       Make ntpd usable as a NTP server. If you disable this option
  55//config:       ntpd will be usable only as a NTP client.
  56//config:
  57//config:config FEATURE_NTPD_CONF
  58//config:       bool "Make ntpd understand /etc/ntp.conf"
  59//config:       default y
  60//config:       depends on NTPD
  61//config:       help
  62//config:       Make ntpd look in /etc/ntp.conf for peers. Only "server address"
  63//config:       is supported.
  64//config:
  65//config:config FEATURE_NTP_AUTH
  66//config:       bool "Support md5/sha1 message authentication codes"
  67//config:       default y
  68//config:       depends on NTPD
  69
  70//applet:IF_NTPD(APPLET(ntpd, BB_DIR_USR_SBIN, BB_SUID_DROP))
  71
  72//kbuild:lib-$(CONFIG_NTPD) += ntpd.o
  73
  74//usage:#define ntpd_trivial_usage
  75//usage:        "[-dnqNw"IF_FEATURE_NTPD_SERVER("l] [-I IFACE")"] [-S PROG]"
  76//usage:        IF_NOT_FEATURE_NTP_AUTH(" [-p PEER]...")
  77//usage:        IF_FEATURE_NTP_AUTH(" [-k KEYFILE] [-p [keyno:N:]PEER]...")
  78//usage:#define ntpd_full_usage "\n\n"
  79//usage:       "NTP client/server\n"
  80//usage:     "\n        -d[d]   Verbose"
  81//usage:     "\n        -n      Do not daemonize"
  82//usage:     "\n        -q      Quit after clock is set"
  83//usage:     "\n        -N      Run at high priority"
  84//usage:     "\n        -w      Do not set time (only query peers), implies -n"
  85//usage:     "\n        -S PROG Run PROG after stepping time, stratum change, and every 11 min"
  86//usage:        IF_NOT_FEATURE_NTP_AUTH(
  87//usage:     "\n        -p PEER Obtain time from PEER (may be repeated)"
  88//usage:        )
  89//usage:        IF_FEATURE_NTP_AUTH(
  90//usage:     "\n        -k FILE Key file (ntp.keys compatible)"
  91//usage:     "\n        -p [keyno:NUM:]PEER"
  92//usage:     "\n                Obtain time from PEER (may be repeated)"
  93//usage:     "\n                Use key NUM for authentication"
  94//usage:        )
  95//usage:        IF_FEATURE_NTPD_CONF(
  96//usage:     "\n                If -p is not given, 'server HOST' lines"
  97//usage:     "\n                from /etc/ntp.conf are used"
  98//usage:        )
  99//usage:        IF_FEATURE_NTPD_SERVER(
 100//usage:     "\n        -l      Also run as server on port 123"
 101//usage:     "\n        -I IFACE Bind server to IFACE, implies -l"
 102//usage:        )
 103
 104// -l and -p options are not compatible with "standard" ntpd:
 105// it has them as "-l logfile" and "-p pidfile".
 106// -S and -w are not compat either, "standard" ntpd has no such opts.
 107
 108#include "libbb.h"
 109#include <math.h>
 110#include <netinet/ip.h> /* For IPTOS_DSCP_AF21 definition */
 111#include <sys/timex.h>
 112#ifndef IPTOS_DSCP_AF21
 113# define IPTOS_DSCP_AF21 0x48
 114#endif
 115
 116
 117/* Verbosity control (max level of -dddd options accepted).
 118 * max 6 is very talkative (and bloated). 3 is non-bloated,
 119 * production level setting.
 120 */
 121#define MAX_VERBOSE     3
 122
 123
 124/* High-level description of the algorithm:
 125 *
 126 * We start running with very small poll_exp, BURSTPOLL,
 127 * in order to quickly accumulate INITIAL_SAMPLES datapoints
 128 * for each peer. Then, time is stepped if the offset is larger
 129 * than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
 130 * poll_exp to MINPOLL and enter frequency measurement step:
 131 * we collect new datapoints but ignore them for WATCH_THRESHOLD
 132 * seconds. After WATCH_THRESHOLD seconds we look at accumulated
 133 * offset and estimate frequency drift.
 134 *
 135 * (frequency measurement step seems to not be strictly needed,
 136 * it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
 137 * define set to 0)
 138 *
 139 * After this, we enter "steady state": we collect a datapoint,
 140 * we select the best peer, if this datapoint is not a new one
 141 * (IOW: if this datapoint isn't for selected peer), sleep
 142 * and collect another one; otherwise, use its offset to update
 143 * frequency drift, if offset is somewhat large, reduce poll_exp,
 144 * otherwise increase poll_exp.
 145 *
 146 * If offset is larger than STEP_THRESHOLD, which shouldn't normally
 147 * happen, we assume that something "bad" happened (computer
 148 * was hibernated, someone set totally wrong date, etc),
 149 * then the time is stepped, all datapoints are discarded,
 150 * and we go back to steady state.
 151 *
 152 * Made some changes to speed up re-syncing after our clock goes bad
 153 * (tested with suspending my laptop):
 154 * - if largish offset (>= STEP_THRESHOLD == 1 sec) is seen
 155 *   from a peer, schedule next query for this peer soon
 156 *   without drastically lowering poll interval for everybody.
 157 *   This makes us collect enough data for step much faster:
 158 *   e.g. at poll = 10 (1024 secs), step was done within 5 minutes
 159 *   after first reply which indicated that our clock is 14 seconds off.
 160 * - on step, do not discard d_dispersion data of the existing datapoints,
 161 *   do not clear reachable_bits. This prevents discarding first ~8
 162 *   datapoints after the step.
 163 */
 164
 165#define INITIAL_SAMPLES    4    /* how many samples do we want for init */
 166#define MIN_FREQHOLD      10    /* adjust offset, but not freq in this many first adjustments */
 167#define BAD_DELAY_GROWTH   4    /* drop packet if its delay grew by more than this factor */
 168
 169#define RETRY_INTERVAL    32    /* on send/recv error, retry in N secs (need to be power of 2) */
 170#define NOREPLY_INTERVAL 512    /* sent, but got no reply: cap next query by this many seconds */
 171#define RESPONSE_INTERVAL 16    /* wait for reply up to N secs */
 172#define HOSTNAME_INTERVAL  4    /* hostname lookup failed. Wait N * peer->dns_errors secs for next try */
 173#define DNS_ERRORS_CAP  0x3f    /* peer->dns_errors is in [0..63] */
 174
 175/* Step threshold (sec). std ntpd uses 0.128.
 176 */
 177#define STEP_THRESHOLD     1
 178/* Slew threshold (sec): adjtimex() won't accept offsets larger than this.
 179 * Using exact power of 2 (1/8, 1/2 etc) results in smaller code
 180 */
 181#define SLEW_THRESHOLD   0.5
 182// ^^^^ used to be 0.125.
 183// Since Linux 2.6.26 (circa 2006), kernel accepts (-0.5s, +0.5s) range
 184
 185/* Stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
 186//UNUSED: #define WATCH_THRESHOLD  128
 187/* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
 188//UNUSED: #define PANIC_THRESHOLD 1000    /* panic threshold (sec) */
 189
 190/*
 191 * If we got |offset| > BIGOFF from a peer, cap next query interval
 192 * for this peer by this many seconds:
 193 */
 194#define BIGOFF          STEP_THRESHOLD
 195#define BIGOFF_INTERVAL (1 << 7) /* 128 s */
 196
 197#define FREQ_TOLERANCE  0.000015 /* frequency tolerance (15 PPM) */
 198#define BURSTPOLL       0       /* initial poll */
 199#define MINPOLL         5       /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
 200/*
 201 * If offset > discipline_jitter * POLLADJ_GATE, and poll interval is > 2^BIGPOLL,
 202 * then it is decreased _at once_. (If <= 2^BIGPOLL, it will be decreased _eventually_).
 203 */
 204#define BIGPOLL         9       /* 2^9 sec ~= 8.5 min */
 205#define MAXPOLL         12      /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
 206/*
 207 * Actively lower poll when we see such big offsets.
 208 * With SLEW_THRESHOLD = 0.125, it means we try to sync more aggressively
 209 * if offset increases over ~0.04 sec
 210 */
 211//#define POLLDOWN_OFFSET (SLEW_THRESHOLD / 3)
 212#define MINDISP         0.01    /* minimum dispersion (sec) */
 213#define MAXDISP         16      /* maximum dispersion (sec) */
 214#define MAXSTRAT        16      /* maximum stratum (infinity metric) */
 215#define MAXDIST         1       /* distance threshold (sec) */
 216#define MIN_SELECTED    1       /* minimum intersection survivors */
 217#define MIN_CLUSTERED   3       /* minimum cluster survivors */
 218
 219#define MAXDRIFT        0.000500 /* frequency drift we can correct (500 PPM) */
 220
 221/* Poll-adjust threshold.
 222 * When we see that offset is small enough compared to discipline jitter,
 223 * we grow a counter: += MINPOLL. When counter goes over POLLADJ_LIMIT,
 224 * we poll_exp++. If offset isn't small, counter -= poll_exp*2,
 225 * and when it goes below -POLLADJ_LIMIT, we poll_exp--.
 226 * (Bumped from 30 to 40 since otherwise I often see poll_exp going *2* steps down)
 227 */
 228#define POLLADJ_LIMIT   40
 229/* If offset < discipline_jitter * POLLADJ_GATE, then we decide to increase
 230 * poll interval (we think we can't improve timekeeping
 231 * by staying at smaller poll).
 232 */
 233#define POLLADJ_GATE    4
 234#define TIMECONST_HACK_GATE 2
 235/* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
 236#define ALLAN           512
 237/* PLL loop gain */
 238#define PLL             65536
 239/* FLL loop gain [why it depends on MAXPOLL??] */
 240#define FLL             (MAXPOLL + 1)
 241/* Parameter averaging constant */
 242#define AVG             4
 243
 244#define MAX_KEY_NUMBER  65535
 245#define KEYID_SIZE      sizeof(uint32_t)
 246
 247enum {
 248        NTP_VERSION     = 4,
 249        NTP_MAXSTRATUM  = 15,
 250
 251        NTP_MD5_DIGESTSIZE    = 16,
 252        NTP_MSGSIZE_NOAUTH    = 48,
 253        NTP_MSGSIZE_MD5_AUTH  = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_MD5_DIGESTSIZE,
 254        NTP_SHA1_DIGESTSIZE   = 20,
 255        NTP_MSGSIZE_SHA1_AUTH = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_SHA1_DIGESTSIZE,
 256
 257        /* Status Masks */
 258        MODE_MASK       = (7 << 0),
 259        VERSION_MASK    = (7 << 3),
 260        VERSION_SHIFT   = 3,
 261        LI_MASK         = (3 << 6),
 262
 263        /* Leap Second Codes (high order two bits of m_status) */
 264        LI_NOWARNING    = (0 << 6),    /* no warning */
 265        LI_PLUSSEC      = (1 << 6),    /* add a second (61 seconds) */
 266        LI_MINUSSEC     = (2 << 6),    /* minus a second (59 seconds) */
 267        LI_ALARM        = (3 << 6),    /* alarm condition */
 268
 269        /* Mode values */
 270        MODE_RES0       = 0,    /* reserved */
 271        MODE_SYM_ACT    = 1,    /* symmetric active */
 272        MODE_SYM_PAS    = 2,    /* symmetric passive */
 273        MODE_CLIENT     = 3,    /* client */
 274        MODE_SERVER     = 4,    /* server */
 275        MODE_BROADCAST  = 5,    /* broadcast */
 276        MODE_RES1       = 6,    /* reserved for NTP control message */
 277        MODE_RES2       = 7,    /* reserved for private use */
 278};
 279
 280//TODO: better base selection
 281#define OFFSET_1900_1970 2208988800UL  /* 1970 - 1900 in seconds */
 282
 283#define NUM_DATAPOINTS  8
 284
 285typedef struct {
 286        uint32_t int_partl;
 287        uint32_t fractionl;
 288} l_fixedpt_t;
 289
 290typedef struct {
 291        uint16_t int_parts;
 292        uint16_t fractions;
 293} s_fixedpt_t;
 294
 295typedef struct {
 296        uint8_t     m_status;     /* status of local clock and leap info */
 297        uint8_t     m_stratum;
 298        uint8_t     m_ppoll;      /* poll value */
 299        int8_t      m_precision_exp;
 300        s_fixedpt_t m_rootdelay;
 301        s_fixedpt_t m_rootdisp;
 302        uint32_t    m_refid;
 303        l_fixedpt_t m_reftime;
 304        l_fixedpt_t m_orgtime;
 305        l_fixedpt_t m_rectime;
 306        l_fixedpt_t m_xmttime;
 307        uint32_t    m_keyid;
 308        uint8_t     m_digest[ENABLE_FEATURE_NTP_AUTH ? NTP_SHA1_DIGESTSIZE : NTP_MD5_DIGESTSIZE];
 309} msg_t;
 310
 311typedef struct {
 312        double d_offset;
 313        double d_recv_time;
 314        double d_dispersion;
 315} datapoint_t;
 316
 317#if ENABLE_FEATURE_NTP_AUTH
 318enum {
 319        HASH_MD5,
 320        HASH_SHA1,
 321};
 322typedef struct {
 323        unsigned id; //try uint16_t?
 324        smalluint type;
 325        smalluint msg_size;
 326        smalluint key_length;
 327        char key[0];
 328} key_entry_t;
 329#endif
 330
 331typedef struct {
 332        len_and_sockaddr *p_lsa;
 333        char             *p_dotted;
 334#if ENABLE_FEATURE_NTP_AUTH
 335        key_entry_t      *key_entry;
 336#endif
 337        int              p_fd;
 338        int              datapoint_idx;
 339#if ENABLE_FEATURE_NTPD_SERVER
 340        uint32_t         p_refid;
 341#endif
 342        uint32_t         lastpkt_refid;
 343        uint8_t          lastpkt_status;
 344        uint8_t          lastpkt_stratum;
 345        uint8_t          reachable_bits;
 346        uint8_t          dns_errors;
 347        /* when to send new query (if p_fd == -1)
 348         * or when receive times out (if p_fd >= 0): */
 349        double           next_action_time;
 350        double           p_xmttime;
 351        double           p_raw_delay;
 352        /* p_raw_delay is set even by "high delay" packets */
 353        /* lastpkt_delay isn't */
 354        double           lastpkt_recv_time;
 355        double           lastpkt_delay;
 356        double           lastpkt_rootdelay;
 357        double           lastpkt_rootdisp;
 358        /* produced by filter algorithm: */
 359        double           filter_offset;
 360        double           filter_dispersion;
 361        double           filter_jitter;
 362        datapoint_t      filter_datapoint[NUM_DATAPOINTS];
 363        /* last sent packet: */
 364        msg_t            p_xmt_msg;
 365        char             p_hostname[1];
 366} peer_t;
 367
 368
 369#define USING_KERNEL_PLL_LOOP          1
 370#define USING_INITIAL_FREQ_ESTIMATION  0
 371
 372enum {
 373        OPT_n = (1 << 0),
 374        OPT_q = (1 << 1),
 375        OPT_N = (1 << 2),
 376        OPT_x = (1 << 3),
 377        OPT_k = (1 << 4) * ENABLE_FEATURE_NTP_AUTH,
 378        /* Insert new options above this line. */
 379        /* Non-compat options: */
 380        OPT_w = (1 << (4+ENABLE_FEATURE_NTP_AUTH)),
 381        OPT_p = (1 << (5+ENABLE_FEATURE_NTP_AUTH)),
 382        OPT_S = (1 << (6+ENABLE_FEATURE_NTP_AUTH)),
 383        OPT_l = (1 << (7+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
 384        OPT_I = (1 << (8+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
 385        /* We hijack some bits for other purposes */
 386        OPT_qq = (1 << 31),
 387};
 388
 389struct globals {
 390        double   cur_time;
 391        /* total round trip delay to currently selected reference clock */
 392        double   rootdelay;
 393        /* reference timestamp: time when the system clock was last set or corrected */
 394        double   reftime;
 395        /* total dispersion to currently selected reference clock */
 396        double   rootdisp;
 397
 398        double   last_script_run;
 399        char     *script_name;
 400        llist_t  *ntp_peers;
 401#if ENABLE_FEATURE_NTPD_SERVER
 402        int      listen_fd;
 403        char     *if_name;
 404# define G_listen_fd (G.listen_fd)
 405#else
 406# define G_listen_fd (-1)
 407#endif
 408        unsigned verbose;
 409        unsigned peer_cnt;
 410        /* refid: 32-bit code identifying the particular server or reference clock
 411         * in stratum 0 packets this is a four-character ASCII string,
 412         * called the kiss code, used for debugging and monitoring
 413         * in stratum 1 packets this is a four-character ASCII string
 414         * assigned to the reference clock by IANA. Example: "GPS "
 415         * in stratum 2+ packets, it's IPv4 address or 4 first bytes
 416         * of MD5 hash of IPv6
 417         */
 418#if ENABLE_FEATURE_NTPD_SERVER
 419        uint32_t refid;
 420#endif
 421        uint8_t  ntp_status;
 422        /* precision is defined as the larger of the resolution and time to
 423         * read the clock, in log2 units.  For instance, the precision of a
 424         * mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
 425         * system clock hardware representation is to the nanosecond.
 426         *
 427         * Delays, jitters of various kinds are clamped down to precision.
 428         *
 429         * If precision_sec is too large, discipline_jitter gets clamped to it
 430         * and if offset is smaller than discipline_jitter * POLLADJ_GATE, poll
 431         * interval grows even though we really can benefit from staying at
 432         * smaller one, collecting non-lagged datapoits and correcting offset.
 433         * (Lagged datapoits exist when poll_exp is large but we still have
 434         * systematic offset error - the time distance between datapoints
 435         * is significant and older datapoints have smaller offsets.
 436         * This makes our offset estimation a bit smaller than reality)
 437         * Due to this effect, setting G_precision_sec close to
 438         * STEP_THRESHOLD isn't such a good idea - offsets may grow
 439         * too big and we will step. I observed it with -6.
 440         *
 441         * OTOH, setting precision_sec far too small would result in futile
 442         * attempts to synchronize to an unachievable precision.
 443         *
 444         * -6 is 1/64 sec, -7 is 1/128 sec and so on.
 445         * -8 is 1/256 ~= 0.003906 (worked well for me --vda)
 446         * -9 is 1/512 ~= 0.001953 (let's try this for some time)
 447         */
 448#define G_precision_exp  -9
 449        /*
 450         * G_precision_exp is used only for construction outgoing packets.
 451         * It's ok to set G_precision_sec to a slightly different value
 452         * (One which is "nicer looking" in logs).
 453         * Exact value would be (1.0 / (1 << (- G_precision_exp))):
 454         */
 455#define G_precision_sec  0.002
 456        uint8_t  stratum;
 457
 458#define STATE_NSET      0       /* initial state, "nothing is set" */
 459//#define STATE_FSET    1       /* frequency set from file */
 460//#define STATE_SPIK    2       /* spike detected */
 461//#define STATE_FREQ    3       /* initial frequency */
 462#define STATE_SYNC      4       /* clock synchronized (normal operation) */
 463        uint8_t  discipline_state;      // doc calls it c.state
 464        uint8_t  poll_exp;              // s.poll
 465        int      polladj_count;         // c.count
 466        int      FREQHOLD_cnt;
 467        long     kernel_freq_drift;
 468        peer_t   *last_update_peer;
 469        double   last_update_offset;    // c.last
 470        double   last_update_recv_time; // s.t
 471        double   discipline_jitter;     // c.jitter
 472        /* Since we only compare it with ints, can simplify code
 473         * by not making this variable floating point:
 474         */
 475        unsigned offset_to_jitter_ratio;
 476        //double   cluster_offset;        // s.offset
 477        //double   cluster_jitter;        // s.jitter
 478#if !USING_KERNEL_PLL_LOOP
 479        double   discipline_freq_drift; // c.freq
 480        /* Maybe conditionally calculate wander? it's used only for logging */
 481        double   discipline_wander;     // c.wander
 482#endif
 483};
 484#define G (*ptr_to_globals)
 485
 486
 487#define VERB1 if (MAX_VERBOSE && G.verbose)
 488#define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
 489#define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
 490#define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
 491#define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
 492#define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
 493
 494
 495static double LOG2D(int a)
 496{
 497        if (a < 0)
 498                return 1.0 / (1UL << -a);
 499        return 1UL << a;
 500}
 501static ALWAYS_INLINE double SQUARE(double x)
 502{
 503        return x * x;
 504}
 505static ALWAYS_INLINE double MAXD(double a, double b)
 506{
 507        if (a > b)
 508                return a;
 509        return b;
 510}
 511#if !USING_KERNEL_PLL_LOOP
 512static ALWAYS_INLINE double MIND(double a, double b)
 513{
 514        if (a < b)
 515                return a;
 516        return b;
 517}
 518#endif
 519static NOINLINE double my_SQRT(double X)
 520{
 521        union {
 522                float   f;
 523                int32_t i;
 524        } v;
 525        double invsqrt;
 526        double Xhalf = X * 0.5;
 527
 528        /* Fast and good approximation to 1/sqrt(X), black magic */
 529        v.f = X;
 530        /*v.i = 0x5f3759df - (v.i >> 1);*/
 531        v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
 532        invsqrt = v.f; /* better than 0.2% accuracy */
 533
 534        /* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
 535         * f(x) = 1/(x*x) - X  (f==0 when x = 1/sqrt(X))
 536         * f'(x) = -2/(x*x*x)
 537         * f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
 538         * x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
 539         */
 540        invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
 541        /* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
 542        /* With 4 iterations, more than half results will be exact,
 543         * at 6th iterations result stabilizes with about 72% results exact.
 544         * We are well satisfied with 0.05% accuracy.
 545         */
 546
 547        return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
 548}
 549static ALWAYS_INLINE double SQRT(double X)
 550{
 551        /* If this arch doesn't use IEEE 754 floats, fall back to using libm */
 552        if (sizeof(float) != 4)
 553                return sqrt(X);
 554
 555        /* This avoids needing libm, saves about 0.5k on x86-32 */
 556        return my_SQRT(X);
 557}
 558
 559static double
 560gettime1900d(void)
 561{
 562        struct timeval tv;
 563        gettimeofday(&tv, NULL); /* never fails */
 564        G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
 565        return G.cur_time;
 566}
 567
 568static void
 569d_to_tv(double d, struct timeval *tv)
 570{
 571        tv->tv_sec = (long)d;
 572        tv->tv_usec = (d - tv->tv_sec) * 1000000;
 573}
 574
 575static double
 576lfp_to_d(l_fixedpt_t lfp)
 577{
 578        double ret;
 579        lfp.int_partl = ntohl(lfp.int_partl);
 580        lfp.fractionl = ntohl(lfp.fractionl);
 581        ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
 582        return ret;
 583}
 584static double
 585sfp_to_d(s_fixedpt_t sfp)
 586{
 587        double ret;
 588        sfp.int_parts = ntohs(sfp.int_parts);
 589        sfp.fractions = ntohs(sfp.fractions);
 590        ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
 591        return ret;
 592}
 593#if ENABLE_FEATURE_NTPD_SERVER
 594static l_fixedpt_t
 595d_to_lfp(double d)
 596{
 597        l_fixedpt_t lfp;
 598        lfp.int_partl = (uint32_t)d;
 599        lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
 600        lfp.int_partl = htonl(lfp.int_partl);
 601        lfp.fractionl = htonl(lfp.fractionl);
 602        return lfp;
 603}
 604static s_fixedpt_t
 605d_to_sfp(double d)
 606{
 607        s_fixedpt_t sfp;
 608        sfp.int_parts = (uint16_t)d;
 609        sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
 610        sfp.int_parts = htons(sfp.int_parts);
 611        sfp.fractions = htons(sfp.fractions);
 612        return sfp;
 613}
 614#endif
 615
 616static double
 617dispersion(const datapoint_t *dp)
 618{
 619        return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
 620}
 621
 622static double
 623root_distance(peer_t *p)
 624{
 625        /* The root synchronization distance is the maximum error due to
 626         * all causes of the local clock relative to the primary server.
 627         * It is defined as half the total delay plus total dispersion
 628         * plus peer jitter.
 629         */
 630        return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
 631                + p->lastpkt_rootdisp
 632                + p->filter_dispersion
 633                + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
 634                + p->filter_jitter;
 635}
 636
 637static void
 638set_next(peer_t *p, unsigned t)
 639{
 640        p->next_action_time = G.cur_time + t;
 641}
 642
 643/*
 644 * Peer clock filter and its helpers
 645 */
 646static void
 647filter_datapoints(peer_t *p)
 648{
 649        int i, idx;
 650        double sum, wavg;
 651        datapoint_t *fdp;
 652
 653#if 0
 654/* Simulations have shown that use of *averaged* offset for p->filter_offset
 655 * is in fact worse than simply using last received one: with large poll intervals
 656 * (>= 2048) averaging code uses offset values which are outdated by hours,
 657 * and time/frequency correction goes totally wrong when fed essentially bogus offsets.
 658 */
 659        int got_newest;
 660        double minoff, maxoff, w;
 661        double x = x; /* for compiler */
 662        double oldest_off = oldest_off;
 663        double oldest_age = oldest_age;
 664        double newest_off = newest_off;
 665        double newest_age = newest_age;
 666
 667        fdp = p->filter_datapoint;
 668
 669        minoff = maxoff = fdp[0].d_offset;
 670        for (i = 1; i < NUM_DATAPOINTS; i++) {
 671                if (minoff > fdp[i].d_offset)
 672                        minoff = fdp[i].d_offset;
 673                if (maxoff < fdp[i].d_offset)
 674                        maxoff = fdp[i].d_offset;
 675        }
 676
 677        idx = p->datapoint_idx; /* most recent datapoint's index */
 678        /* Average offset:
 679         * Drop two outliers and take weighted average of the rest:
 680         * most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
 681         * we use older6/32, not older6/64 since sum of weights should be 1:
 682         * 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
 683         */
 684        wavg = 0;
 685        w = 0.5;
 686        /*                     n-1
 687         *                     ---    dispersion(i)
 688         * filter_dispersion =  \     -------------
 689         *                      /       (i+1)
 690         *                     ---     2
 691         *                     i=0
 692         */
 693        got_newest = 0;
 694        sum = 0;
 695        for (i = 0; i < NUM_DATAPOINTS; i++) {
 696                VERB5 {
 697                        bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
 698                                i,
 699                                fdp[idx].d_offset,
 700                                fdp[idx].d_dispersion, dispersion(&fdp[idx]),
 701                                G.cur_time - fdp[idx].d_recv_time,
 702                                (minoff == fdp[idx].d_offset || maxoff == fdp[idx].d_offset)
 703                                        ? " (outlier by offset)" : ""
 704                        );
 705                }
 706
 707                sum += dispersion(&fdp[idx]) / (2 << i);
 708
 709                if (minoff == fdp[idx].d_offset) {
 710                        minoff -= 1; /* so that we don't match it ever again */
 711                } else
 712                if (maxoff == fdp[idx].d_offset) {
 713                        maxoff += 1;
 714                } else {
 715                        oldest_off = fdp[idx].d_offset;
 716                        oldest_age = G.cur_time - fdp[idx].d_recv_time;
 717                        if (!got_newest) {
 718                                got_newest = 1;
 719                                newest_off = oldest_off;
 720                                newest_age = oldest_age;
 721                        }
 722                        x = oldest_off * w;
 723                        wavg += x;
 724                        w /= 2;
 725                }
 726
 727                idx = (idx - 1) & (NUM_DATAPOINTS - 1);
 728        }
 729        p->filter_dispersion = sum;
 730        wavg += x; /* add another older6/64 to form older6/32 */
 731        /* Fix systematic underestimation with large poll intervals.
 732         * Imagine that we still have a bit of uncorrected drift,
 733         * and poll interval is big (say, 100 sec). Offsets form a progression:
 734         * 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
 735         * The algorithm above drops 0.0 and 0.7 as outliers,
 736         * and then we have this estimation, ~25% off from 0.7:
 737         * 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
 738         */
 739        x = oldest_age - newest_age;
 740        if (x != 0) {
 741                x = newest_age / x; /* in above example, 100 / (600 - 100) */
 742                if (x < 1) { /* paranoia check */
 743                        x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
 744                        wavg += x;
 745                }
 746        }
 747        p->filter_offset = wavg;
 748
 749#else
 750
 751        fdp = p->filter_datapoint;
 752        idx = p->datapoint_idx; /* most recent datapoint's index */
 753
 754        /* filter_offset: simply use the most recent value */
 755        p->filter_offset = fdp[idx].d_offset;
 756
 757        /*                     n-1
 758         *                     ---    dispersion(i)
 759         * filter_dispersion =  \     -------------
 760         *                      /       (i+1)
 761         *                     ---     2
 762         *                     i=0
 763         */
 764        wavg = 0;
 765        sum = 0;
 766        for (i = 0; i < NUM_DATAPOINTS; i++) {
 767                sum += dispersion(&fdp[idx]) / (2 << i);
 768                wavg += fdp[idx].d_offset;
 769                idx = (idx - 1) & (NUM_DATAPOINTS - 1);
 770        }
 771        wavg /= NUM_DATAPOINTS;
 772        p->filter_dispersion = sum;
 773#endif
 774
 775        /*                  +-----                 -----+ ^ 1/2
 776         *                  |       n-1                 |
 777         *                  |       ---                 |
 778         *                  |  1    \                2  |
 779         * filter_jitter =  | --- * /  (avg-offset_j)   |
 780         *                  |  n    ---                 |
 781         *                  |       j=0                 |
 782         *                  +-----                 -----+
 783         * where n is the number of valid datapoints in the filter (n > 1);
 784         * if filter_jitter < precision then filter_jitter = precision
 785         */
 786        sum = 0;
 787        for (i = 0; i < NUM_DATAPOINTS; i++) {
 788                sum += SQUARE(wavg - fdp[i].d_offset);
 789        }
 790        sum = SQRT(sum / NUM_DATAPOINTS);
 791        p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
 792
 793        VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
 794                        p->filter_offset,
 795                        p->filter_dispersion,
 796                        p->filter_jitter);
 797}
 798
 799static void
 800reset_peer_stats(peer_t *p, double offset)
 801{
 802        int i;
 803        bool small_ofs = fabs(offset) < STEP_THRESHOLD;
 804
 805        /* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
 806         * and clear reachable bits, but this proved to be too aggressive:
 807         * after step (tested with suspending laptop for ~30 secs),
 808         * this caused all previous data to be considered invalid,
 809         * making us needing to collect full ~8 datapoints per peer
 810         * after step in order to start trusting them.
 811         * In turn, this was making poll interval decrease even after
 812         * step was done. (Poll interval decreases already before step
 813         * in this scenario, because we see large offsets and end up with
 814         * no good peer to select).
 815         */
 816
 817        for (i = 0; i < NUM_DATAPOINTS; i++) {
 818                if (small_ofs) {
 819                        p->filter_datapoint[i].d_recv_time += offset;
 820                        if (p->filter_datapoint[i].d_offset != 0) {
 821                                p->filter_datapoint[i].d_offset -= offset;
 822                                //bb_error_msg("p->filter_datapoint[%d].d_offset %f -> %f",
 823                                //      i,
 824                                //      p->filter_datapoint[i].d_offset + offset,
 825                                //      p->filter_datapoint[i].d_offset);
 826                        }
 827                } else {
 828                        p->filter_datapoint[i].d_recv_time  = G.cur_time;
 829                        p->filter_datapoint[i].d_offset     = 0;
 830                        /*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
 831                }
 832        }
 833        if (small_ofs) {
 834                p->lastpkt_recv_time += offset;
 835        } else {
 836                /*p->reachable_bits = 0;*/
 837                p->lastpkt_recv_time = G.cur_time;
 838        }
 839        filter_datapoints(p); /* recalc p->filter_xxx */
 840        VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
 841}
 842
 843#if ENABLE_FEATURE_NTPD_SERVER
 844static uint32_t calculate_refid(len_and_sockaddr *lsa)
 845{
 846# if ENABLE_FEATURE_IPV6
 847        if (lsa->u.sa.sa_family == AF_INET6) {
 848                md5_ctx_t md5;
 849                uint32_t res[MD5_OUTSIZE / 4];
 850
 851                md5_begin(&md5);
 852                md5_hash(&md5, &lsa->u.sin6.sin6_addr, sizeof(lsa->u.sin6.sin6_addr));
 853                md5_end(&md5, res);
 854                return res[0];
 855        }
 856# endif
 857        return lsa->u.sin.sin_addr.s_addr;
 858}
 859#endif
 860
 861static len_and_sockaddr*
 862resolve_peer_hostname(peer_t *p)
 863{
 864        len_and_sockaddr *lsa = host2sockaddr(p->p_hostname, 123);
 865        if (lsa) {
 866                free(p->p_lsa);
 867                free(p->p_dotted);
 868                p->p_lsa = lsa;
 869                p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
 870                VERB1 if (strcmp(p->p_hostname, p->p_dotted) != 0)
 871                        bb_error_msg("'%s' is %s", p->p_hostname, p->p_dotted);
 872#if ENABLE_FEATURE_NTPD_SERVER
 873                p->p_refid = calculate_refid(p->p_lsa);
 874#endif
 875                p->dns_errors = 0;
 876                return lsa;
 877        }
 878        p->dns_errors = ((p->dns_errors << 1) | 1) & DNS_ERRORS_CAP;
 879        return lsa;
 880}
 881
 882#if !ENABLE_FEATURE_NTP_AUTH
 883#define add_peers(s, key_entry) \
 884        add_peers(s)
 885#endif
 886static void
 887add_peers(const char *s, key_entry_t *key_entry)
 888{
 889        llist_t *item;
 890        peer_t *p;
 891
 892        p = xzalloc(sizeof(*p) + strlen(s));
 893        strcpy(p->p_hostname, s);
 894        p->p_fd = -1;
 895        p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
 896        p->next_action_time = G.cur_time; /* = set_next(p, 0); */
 897        reset_peer_stats(p, STEP_THRESHOLD);
 898
 899        /* Names like N.<country2chars>.pool.ntp.org are randomly resolved
 900         * to a pool of machines. Sometimes different N's resolve to the same IP.
 901         * It is not useful to have two peers with same IP. We skip duplicates.
 902         */
 903        if (resolve_peer_hostname(p)) {
 904                for (item = G.ntp_peers; item != NULL; item = item->link) {
 905                        peer_t *pp = (peer_t *) item->data;
 906                        if (pp->p_dotted && strcmp(p->p_dotted, pp->p_dotted) == 0) {
 907                                bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
 908                                free(p->p_lsa);
 909                                free(p->p_dotted);
 910                                free(p);
 911                                return;
 912                        }
 913                }
 914        }
 915
 916        IF_FEATURE_NTP_AUTH(p->key_entry = key_entry;)
 917        llist_add_to(&G.ntp_peers, p);
 918        G.peer_cnt++;
 919}
 920
 921static int
 922do_sendto(int fd,
 923                const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
 924                msg_t *msg, ssize_t len)
 925{
 926        ssize_t ret;
 927
 928        errno = 0;
 929        if (!from) {
 930                ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
 931        } else {
 932                ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
 933        }
 934        if (ret != len) {
 935                bb_simple_perror_msg("send failed");
 936                return -1;
 937        }
 938        return 0;
 939}
 940
 941#if ENABLE_FEATURE_NTP_AUTH
 942static void
 943hash(key_entry_t *key_entry, const msg_t *msg, uint8_t *output)
 944{
 945        union {
 946                md5_ctx_t m;
 947                sha1_ctx_t s;
 948        } ctx;
 949        unsigned hash_size = sizeof(*msg) - sizeof(msg->m_keyid) - sizeof(msg->m_digest);
 950
 951        switch (key_entry->type) {
 952        case HASH_MD5:
 953                md5_begin(&ctx.m);
 954                md5_hash(&ctx.m, key_entry->key, key_entry->key_length);
 955                md5_hash(&ctx.m, msg, hash_size);
 956                md5_end(&ctx.m, output);
 957                break;
 958        default: /* it's HASH_SHA1 */
 959                sha1_begin(&ctx.s);
 960                sha1_hash(&ctx.s, key_entry->key, key_entry->key_length);
 961                sha1_hash(&ctx.s, msg, hash_size);
 962                sha1_end(&ctx.s, output);
 963                break;
 964        }
 965}
 966
 967static void
 968hash_peer(peer_t *p)
 969{
 970        p->p_xmt_msg.m_keyid = htonl(p->key_entry->id);
 971        hash(p->key_entry, &p->p_xmt_msg, p->p_xmt_msg.m_digest);
 972}
 973
 974static int
 975hashes_differ(peer_t *p, const msg_t *msg)
 976{
 977        uint8_t digest[NTP_SHA1_DIGESTSIZE];
 978        hash(p->key_entry, msg, digest);
 979        return memcmp(digest, msg->m_digest, p->key_entry->msg_size - NTP_MSGSIZE_NOAUTH - KEYID_SIZE);
 980}
 981#endif
 982
 983static void
 984send_query_to_peer(peer_t *p)
 985{
 986        if (!p->p_lsa)
 987                return;
 988
 989        /* Why do we need to bind()?
 990         * See what happens when we don't bind:
 991         *
 992         * socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
 993         * setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
 994         * gettimeofday({1259071266, 327885}, NULL) = 0
 995         * sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
 996         * ^^^ we sent it from some source port picked by kernel.
 997         * time(NULL)              = 1259071266
 998         * write(2, "ntpd: entering poll 15 secs\n", 28) = 28
 999         * poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
1000         * recv(3, "yyy", 68, MSG_DONTWAIT) = 48
1001         * ^^^ this recv will receive packets to any local port!
1002         *
1003         * Uncomment this and use strace to see it in action:
1004         */
1005#define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
1006
1007        if (p->p_fd == -1) {
1008                int fd, family;
1009                len_and_sockaddr *local_lsa;
1010
1011                family = p->p_lsa->u.sa.sa_family;
1012                p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
1013                /* local_lsa has "null" address and port 0 now.
1014                 * bind() ensures we have a *particular port* selected by kernel
1015                 * and remembered in p->p_fd, thus later recv(p->p_fd)
1016                 * receives only packets sent to this port.
1017                 */
1018                PROBE_LOCAL_ADDR
1019                xbind(fd, &local_lsa->u.sa, local_lsa->len);
1020                PROBE_LOCAL_ADDR
1021#if ENABLE_FEATURE_IPV6
1022                if (family == AF_INET)
1023#endif
1024                        setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
1025                free(local_lsa);
1026        }
1027
1028        /* Emit message _before_ attempted send. Think of a very short
1029         * roundtrip networks: we need to go back to recv loop ASAP,
1030         * to reduce delay. Printing messages after send works against that.
1031         */
1032        VERB1 bb_error_msg("sending query to %s", p->p_dotted);
1033
1034        /*
1035         * Send out a random 64-bit number as our transmit time.  The NTP
1036         * server will copy said number into the originate field on the
1037         * response that it sends us.  This is totally legal per the SNTP spec.
1038         *
1039         * The impact of this is two fold: we no longer send out the current
1040         * system time for the world to see (which may aid an attacker), and
1041         * it gives us a (not very secure) way of knowing that we're not
1042         * getting spoofed by an attacker that can't capture our traffic
1043         * but can spoof packets from the NTP server we're communicating with.
1044         *
1045         * Save the real transmit timestamp locally.
1046         */
1047        p->p_xmt_msg.m_xmttime.int_partl = rand();
1048        p->p_xmt_msg.m_xmttime.fractionl = rand();
1049        p->p_xmttime = gettime1900d();
1050
1051        /* Were doing it only if sendto worked, but
1052         * loss of sync detection needs reachable_bits updated
1053         * even if sending fails *locally*:
1054         * "network is unreachable" because cable was pulled?
1055         * We still need to declare "unsync" if this condition persists.
1056         */
1057        p->reachable_bits <<= 1;
1058
1059#if ENABLE_FEATURE_NTP_AUTH
1060        if (p->key_entry)
1061                hash_peer(p);
1062        if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
1063                &p->p_xmt_msg, !p->key_entry ? NTP_MSGSIZE_NOAUTH : p->key_entry->msg_size) == -1
1064        )
1065#else
1066        if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
1067                &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
1068        )
1069#endif
1070        {
1071                close(p->p_fd);
1072                p->p_fd = -1;
1073                /*
1074                 * We know that we sent nothing.
1075                 * We can retry *soon* without fearing
1076                 * that we are flooding the peer.
1077                 */
1078                set_next(p, RETRY_INTERVAL);
1079                return;
1080        }
1081
1082        set_next(p, RESPONSE_INTERVAL);
1083}
1084
1085
1086/* Note that there is no provision to prevent several run_scripts
1087 * to be started in quick succession. In fact, it happens rather often
1088 * if initial syncronization results in a step.
1089 * You will see "step" and then "stratum" script runs, sometimes
1090 * as close as only 0.002 seconds apart.
1091 * Script should be ready to deal with this.
1092 */
1093static void run_script(const char *action, double offset)
1094{
1095        char *argv[3];
1096        char *env1, *env2, *env3, *env4;
1097
1098        G.last_script_run = G.cur_time;
1099
1100        if (!G.script_name)
1101                return;
1102
1103        argv[0] = (char*) G.script_name;
1104        argv[1] = (char*) action;
1105        argv[2] = NULL;
1106
1107        VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
1108
1109        env1 = xasprintf("%s=%u", "stratum", G.stratum);
1110        putenv(env1);
1111        env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
1112        putenv(env2);
1113        env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
1114        putenv(env3);
1115        env4 = xasprintf("%s=%f", "offset", offset);
1116        putenv(env4);
1117        /* Other items of potential interest: selected peer,
1118         * rootdelay, reftime, rootdisp, refid, ntp_status,
1119         * last_update_offset, last_update_recv_time, discipline_jitter,
1120         * how many peers have reachable_bits = 0?
1121         */
1122
1123        /* Don't want to wait: it may run hwclock --systohc, and that
1124         * may take some time (seconds): */
1125        /*spawn_and_wait(argv);*/
1126        spawn(argv);
1127
1128        unsetenv("stratum");
1129        unsetenv("freq_drift_ppm");
1130        unsetenv("poll_interval");
1131        unsetenv("offset");
1132        free(env1);
1133        free(env2);
1134        free(env3);
1135        free(env4);
1136}
1137
1138static NOINLINE void
1139step_time(double offset)
1140{
1141        llist_t *item;
1142        double dtime;
1143        struct timeval tvc, tvn;
1144        char buf[sizeof("yyyy-mm-dd hh:mm:ss") + /*paranoia:*/ 4];
1145        time_t tval;
1146
1147        gettimeofday(&tvc, NULL); /* never fails */
1148        dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
1149        d_to_tv(dtime, &tvn);
1150        xsettimeofday(&tvn);
1151
1152        VERB2 {
1153                tval = tvc.tv_sec;
1154                strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1155                bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
1156        }
1157        tval = tvn.tv_sec;
1158        strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1159        bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
1160        //maybe? G.FREQHOLD_cnt = 0;
1161
1162        /* Correct various fields which contain time-relative values: */
1163
1164        /* Globals: */
1165        G.cur_time += offset;
1166        G.last_update_recv_time += offset;
1167        G.last_script_run += offset;
1168
1169        /* p->lastpkt_recv_time, p->next_action_time and such: */
1170        for (item = G.ntp_peers; item != NULL; item = item->link) {
1171                peer_t *pp = (peer_t *) item->data;
1172                reset_peer_stats(pp, offset);
1173                //bb_error_msg("offset:%+f pp->next_action_time:%f -> %f",
1174                //      offset, pp->next_action_time, pp->next_action_time + offset);
1175                pp->next_action_time += offset;
1176                if (pp->p_fd >= 0) {
1177                        /* We wait for reply from this peer too.
1178                         * But due to step we are doing, reply's data is no longer
1179                         * useful (in fact, it'll be bogus). Stop waiting for it.
1180                         */
1181                        close(pp->p_fd);
1182                        pp->p_fd = -1;
1183                        set_next(pp, RETRY_INTERVAL);
1184                }
1185        }
1186}
1187
1188static void clamp_pollexp_and_set_MAXSTRAT(void)
1189{
1190        if (G.poll_exp < MINPOLL)
1191                G.poll_exp = MINPOLL;
1192        if (G.poll_exp > BIGPOLL)
1193                G.poll_exp = BIGPOLL;
1194        G.polladj_count = 0;
1195        G.stratum = MAXSTRAT;
1196}
1197
1198
1199/*
1200 * Selection and clustering, and their helpers
1201 */
1202typedef struct {
1203        peer_t *p;
1204        int    type;
1205        double edge;
1206        double opt_rd; /* optimization */
1207} point_t;
1208static int
1209compare_point_edge(const void *aa, const void *bb)
1210{
1211        const point_t *a = aa;
1212        const point_t *b = bb;
1213        if (a->edge < b->edge) {
1214                return -1;
1215        }
1216        return (a->edge > b->edge);
1217}
1218typedef struct {
1219        peer_t *p;
1220        double metric;
1221} survivor_t;
1222static int
1223compare_survivor_metric(const void *aa, const void *bb)
1224{
1225        const survivor_t *a = aa;
1226        const survivor_t *b = bb;
1227        if (a->metric < b->metric) {
1228                return -1;
1229        }
1230        return (a->metric > b->metric);
1231}
1232static int
1233fit(peer_t *p, double rd)
1234{
1235        if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
1236                /* One or zero bits in reachable_bits */
1237                VERB4 bb_error_msg("peer %s unfit for selection: "
1238                                "unreachable", p->p_dotted);
1239                return 0;
1240        }
1241#if 0 /* we filter out such packets earlier */
1242        if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
1243         || p->lastpkt_stratum >= MAXSTRAT
1244        ) {
1245                VERB4 bb_error_msg("peer %s unfit for selection: "
1246                                "bad status/stratum", p->p_dotted);
1247                return 0;
1248        }
1249#endif
1250        /* rd is root_distance(p) */
1251        if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
1252                VERB3 bb_error_msg("peer %s unfit for selection: "
1253                        "root distance %f too high, jitter:%f",
1254                        p->p_dotted, rd, p->filter_jitter
1255                );
1256                return 0;
1257        }
1258//TODO
1259//      /* Do we have a loop? */
1260//      if (p->refid == p->dstaddr || p->refid == s.refid)
1261//              return 0;
1262        return 1;
1263}
1264static peer_t*
1265select_and_cluster(void)
1266{
1267        peer_t     *p;
1268        llist_t    *item;
1269        int        i, j;
1270        int        size = 3 * G.peer_cnt;
1271        /* for selection algorithm */
1272        point_t    point[size];
1273        unsigned   num_points, num_candidates;
1274        double     low, high;
1275        unsigned   num_falsetickers;
1276        /* for cluster algorithm */
1277        survivor_t survivor[size];
1278        unsigned   num_survivors;
1279
1280        /* Selection */
1281
1282        num_points = 0;
1283        item = G.ntp_peers;
1284        while (item != NULL) {
1285                double rd, offset;
1286
1287                p = (peer_t *) item->data;
1288                rd = root_distance(p);
1289                offset = p->filter_offset;
1290                if (!fit(p, rd)) {
1291                        item = item->link;
1292                        continue;
1293                }
1294
1295                VERB5 bb_error_msg("interval: [%f %f %f] %s",
1296                                offset - rd,
1297                                offset,
1298                                offset + rd,
1299                                p->p_dotted
1300                );
1301                point[num_points].p = p;
1302                point[num_points].type = -1;
1303                point[num_points].edge = offset - rd;
1304                point[num_points].opt_rd = rd;
1305                num_points++;
1306                point[num_points].p = p;
1307                point[num_points].type = 0;
1308                point[num_points].edge = offset;
1309                point[num_points].opt_rd = rd;
1310                num_points++;
1311                point[num_points].p = p;
1312                point[num_points].type = 1;
1313                point[num_points].edge = offset + rd;
1314                point[num_points].opt_rd = rd;
1315                num_points++;
1316                item = item->link;
1317        }
1318        num_candidates = num_points / 3;
1319        if (num_candidates == 0) {
1320                VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
1321                return NULL;
1322        }
1323//TODO: sorting does not seem to be done in reference code
1324        qsort(point, num_points, sizeof(point[0]), compare_point_edge);
1325
1326        /* Start with the assumption that there are no falsetickers.
1327         * Attempt to find a nonempty intersection interval containing
1328         * the midpoints of all truechimers.
1329         * If a nonempty interval cannot be found, increase the number
1330         * of assumed falsetickers by one and try again.
1331         * If a nonempty interval is found and the number of falsetickers
1332         * is less than the number of truechimers, a majority has been found
1333         * and the midpoint of each truechimer represents
1334         * the candidates available to the cluster algorithm.
1335         */
1336        num_falsetickers = 0;
1337        while (1) {
1338                int c;
1339                unsigned num_midpoints = 0;
1340
1341                low = 1 << 9;
1342                high = - (1 << 9);
1343                c = 0;
1344                for (i = 0; i < num_points; i++) {
1345                        /* We want to do:
1346                         * if (point[i].type == -1) c++;
1347                         * if (point[i].type == 1) c--;
1348                         * and it's simpler to do it this way:
1349                         */
1350                        c -= point[i].type;
1351                        if (c >= num_candidates - num_falsetickers) {
1352                                /* If it was c++ and it got big enough... */
1353                                low = point[i].edge;
1354                                break;
1355                        }
1356                        if (point[i].type == 0)
1357                                num_midpoints++;
1358                }
1359                c = 0;
1360                for (i = num_points-1; i >= 0; i--) {
1361                        c += point[i].type;
1362                        if (c >= num_candidates - num_falsetickers) {
1363                                high = point[i].edge;
1364                                break;
1365                        }
1366                        if (point[i].type == 0)
1367                                num_midpoints++;
1368                }
1369                /* If the number of midpoints is greater than the number
1370                 * of allowed falsetickers, the intersection contains at
1371                 * least one truechimer with no midpoint - bad.
1372                 * Also, interval should be nonempty.
1373                 */
1374                if (num_midpoints <= num_falsetickers && low < high)
1375                        break;
1376                num_falsetickers++;
1377                if (num_falsetickers * 2 >= num_candidates) {
1378                        VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
1379                                        num_falsetickers, num_candidates,
1380                                        ", no peer selected");
1381                        return NULL;
1382                }
1383        }
1384        VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
1385                        low, high, num_candidates, num_falsetickers);
1386
1387        /* Clustering */
1388
1389        /* Construct a list of survivors (p, metric)
1390         * from the chime list, where metric is dominated
1391         * first by stratum and then by root distance.
1392         * All other things being equal, this is the order of preference.
1393         */
1394        num_survivors = 0;
1395        for (i = 0; i < num_points; i++) {
1396                if (point[i].edge < low || point[i].edge > high)
1397                        continue;
1398                p = point[i].p;
1399                survivor[num_survivors].p = p;
1400                /* x.opt_rd == root_distance(p); */
1401                survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
1402                VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
1403                        num_survivors, survivor[num_survivors].metric, p->p_dotted);
1404                num_survivors++;
1405        }
1406        /* There must be at least MIN_SELECTED survivors to satisfy the
1407         * correctness assertions. Ordinarily, the Byzantine criteria
1408         * require four survivors, but for the demonstration here, one
1409         * is acceptable.
1410         */
1411        if (num_survivors < MIN_SELECTED) {
1412                VERB3 bb_error_msg("survivors:%d%s",
1413                                num_survivors,
1414                                ", no peer selected");
1415                return NULL;
1416        }
1417
1418//looks like this is ONLY used by the fact that later we pick survivor[0].
1419//we can avoid sorting then, just find the minimum once!
1420        qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1421
1422        /* For each association p in turn, calculate the selection
1423         * jitter p->sjitter as the square root of the sum of squares
1424         * (p->offset - q->offset) over all q associations. The idea is
1425         * to repeatedly discard the survivor with maximum selection
1426         * jitter until a termination condition is met.
1427         */
1428        while (1) {
1429                unsigned max_idx = max_idx;
1430                double max_selection_jitter = max_selection_jitter;
1431                double min_jitter = min_jitter;
1432
1433                if (num_survivors <= MIN_CLUSTERED) {
1434                        VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
1435                                        num_survivors, MIN_CLUSTERED);
1436                        break;
1437                }
1438
1439                /* To make sure a few survivors are left
1440                 * for the clustering algorithm to chew on,
1441                 * we stop if the number of survivors
1442                 * is less than or equal to MIN_CLUSTERED (3).
1443                 */
1444                for (i = 0; i < num_survivors; i++) {
1445                        double selection_jitter_sq;
1446
1447                        p = survivor[i].p;
1448                        if (i == 0 || p->filter_jitter < min_jitter)
1449                                min_jitter = p->filter_jitter;
1450
1451                        selection_jitter_sq = 0;
1452                        for (j = 0; j < num_survivors; j++) {
1453                                peer_t *q = survivor[j].p;
1454                                selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1455                        }
1456                        if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1457                                max_selection_jitter = selection_jitter_sq;
1458                                max_idx = i;
1459                        }
1460                        VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
1461                                        i, selection_jitter_sq);
1462                }
1463                max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
1464                VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1465                                max_idx, max_selection_jitter, min_jitter);
1466
1467                /* If the maximum selection jitter is less than the
1468                 * minimum peer jitter, then tossing out more survivors
1469                 * will not lower the minimum peer jitter, so we might
1470                 * as well stop.
1471                 */
1472                if (max_selection_jitter < min_jitter) {
1473                        VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1474                                        max_selection_jitter, min_jitter, num_survivors);
1475                        break;
1476                }
1477
1478                /* Delete survivor[max_idx] from the list
1479                 * and go around again.
1480                 */
1481                VERB6 bb_error_msg("dropping survivor %d", max_idx);
1482                num_survivors--;
1483                while (max_idx < num_survivors) {
1484                        survivor[max_idx] = survivor[max_idx + 1];
1485                        max_idx++;
1486                }
1487        }
1488
1489        if (0) {
1490                /* Combine the offsets of the clustering algorithm survivors
1491                 * using a weighted average with weight determined by the root
1492                 * distance. Compute the selection jitter as the weighted RMS
1493                 * difference between the first survivor and the remaining
1494                 * survivors. In some cases the inherent clock jitter can be
1495                 * reduced by not using this algorithm, especially when frequent
1496                 * clockhopping is involved. bbox: thus we don't do it.
1497                 */
1498                double x, y, z, w;
1499                y = z = w = 0;
1500                for (i = 0; i < num_survivors; i++) {
1501                        p = survivor[i].p;
1502                        x = root_distance(p);
1503                        y += 1 / x;
1504                        z += p->filter_offset / x;
1505                        w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1506                }
1507                //G.cluster_offset = z / y;
1508                //G.cluster_jitter = SQRT(w / y);
1509        }
1510
1511        /* Pick the best clock. If the old system peer is on the list
1512         * and at the same stratum as the first survivor on the list,
1513         * then don't do a clock hop. Otherwise, select the first
1514         * survivor on the list as the new system peer.
1515         */
1516        p = survivor[0].p;
1517        if (G.last_update_peer
1518         && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1519        ) {
1520                /* Starting from 1 is ok here */
1521                for (i = 1; i < num_survivors; i++) {
1522                        if (G.last_update_peer == survivor[i].p) {
1523                                VERB5 bb_simple_error_msg("keeping old synced peer");
1524                                p = G.last_update_peer;
1525                                goto keep_old;
1526                        }
1527                }
1528        }
1529        G.last_update_peer = p;
1530 keep_old:
1531        VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
1532                        p->p_dotted,
1533                        p->filter_offset,
1534                        G.cur_time - p->lastpkt_recv_time
1535        );
1536        return p;
1537}
1538
1539
1540/*
1541 * Local clock discipline and its helpers
1542 */
1543static void
1544set_new_values(int disc_state, double offset, double recv_time)
1545{
1546        /* Enter new state and set state variables. Note we use the time
1547         * of the last clock filter sample, which must be earlier than
1548         * the current time.
1549         */
1550        VERB4 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
1551                        disc_state, offset, recv_time);
1552        G.discipline_state = disc_state;
1553        G.last_update_offset = offset;
1554        G.last_update_recv_time = recv_time;
1555}
1556/* Return: -1: decrease poll interval, 0: leave as is, 1: increase */
1557static NOINLINE int
1558update_local_clock(peer_t *p)
1559{
1560        int rc;
1561        struct timex tmx;
1562        /* Note: can use G.cluster_offset instead: */
1563        double offset = p->filter_offset;
1564        double recv_time = p->lastpkt_recv_time;
1565        double abs_offset;
1566#if !USING_KERNEL_PLL_LOOP
1567        double freq_drift;
1568#endif
1569#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1570        double since_last_update;
1571#endif
1572        double etemp, dtemp;
1573
1574        abs_offset = fabs(offset);
1575
1576#if 0
1577        /* If needed, -S script can do it by looking at $offset
1578         * env var and killing parent */
1579        /* If the offset is too large, give up and go home */
1580        if (abs_offset > PANIC_THRESHOLD) {
1581                bb_error_msg_and_die("offset %f far too big, exiting", offset);
1582        }
1583#endif
1584
1585        /* If this is an old update, for instance as the result
1586         * of a system peer change, avoid it. We never use
1587         * an old sample or the same sample twice.
1588         */
1589        if (recv_time <= G.last_update_recv_time) {
1590                VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
1591                        p->p_dotted);
1592                return 0; /* "leave poll interval as is" */
1593        }
1594
1595        /* Clock state machine transition function. This is where the
1596         * action is and defines how the system reacts to large time
1597         * and frequency errors.
1598         */
1599#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1600        since_last_update = recv_time - G.reftime;
1601#endif
1602#if !USING_KERNEL_PLL_LOOP
1603        freq_drift = 0;
1604#endif
1605#if USING_INITIAL_FREQ_ESTIMATION
1606        if (G.discipline_state == STATE_FREQ) {
1607                /* Ignore updates until the stepout threshold */
1608                if (since_last_update < WATCH_THRESHOLD) {
1609                        VERB4 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1610                                        WATCH_THRESHOLD - since_last_update);
1611                        return 0; /* "leave poll interval as is" */
1612                }
1613# if !USING_KERNEL_PLL_LOOP
1614                freq_drift = (offset - G.last_update_offset) / since_last_update;
1615# endif
1616        }
1617#endif
1618
1619        /* There are two main regimes: when the
1620         * offset exceeds the step threshold and when it does not.
1621         */
1622        if (abs_offset > STEP_THRESHOLD) {
1623#if 0
1624                double remains;
1625
1626// This "spike state" seems to be useless, peer selection already drops
1627// occassional "bad" datapoints. If we are here, there were _many_
1628// large offsets. When a few first large offsets are seen,
1629// we end up in "no valid datapoints, no peer selected" state.
1630// Only when enough of them are seen (which means it's not a fluke),
1631// we end up here. Looks like _our_ clock is off.
1632                switch (G.discipline_state) {
1633                case STATE_SYNC:
1634                        /* The first outlyer: ignore it, switch to SPIK state */
1635                        VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1636                                p->p_dotted, offset,
1637                                "");
1638                        G.discipline_state = STATE_SPIK;
1639                        return -1; /* "decrease poll interval" */
1640
1641                case STATE_SPIK:
1642                        /* Ignore succeeding outlyers until either an inlyer
1643                         * is found or the stepout threshold is exceeded.
1644                         */
1645                        remains = WATCH_THRESHOLD - since_last_update;
1646                        if (remains > 0) {
1647                                VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1648                                        p->p_dotted, offset,
1649                                        ", datapoint ignored");
1650                                return -1; /* "decrease poll interval" */
1651                        }
1652                        /* fall through: we need to step */
1653                } /* switch */
1654#endif
1655
1656                /* Step the time and clamp down the poll interval.
1657                 *
1658                 * In NSET state an initial frequency correction is
1659                 * not available, usually because the frequency file has
1660                 * not yet been written. Since the time is outside the
1661                 * capture range, the clock is stepped. The frequency
1662                 * will be set directly following the stepout interval.
1663                 *
1664                 * In FSET state the initial frequency has been set
1665                 * from the frequency file. Since the time is outside
1666                 * the capture range, the clock is stepped immediately,
1667                 * rather than after the stepout interval. Guys get
1668                 * nervous if it takes 17 minutes to set the clock for
1669                 * the first time.
1670                 *
1671                 * In SPIK state the stepout threshold has expired and
1672                 * the phase is still above the step threshold. Note
1673                 * that a single spike greater than the step threshold
1674                 * is always suppressed, even at the longer poll
1675                 * intervals.
1676                 */
1677                VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
1678                step_time(offset);
1679                if (option_mask32 & OPT_q) {
1680                        /* We were only asked to set time once. Done. */
1681                        exit(0);
1682                }
1683
1684                clamp_pollexp_and_set_MAXSTRAT();
1685
1686                run_script("step", offset);
1687
1688                recv_time += offset;
1689
1690#if USING_INITIAL_FREQ_ESTIMATION
1691                if (G.discipline_state == STATE_NSET) {
1692                        set_new_values(STATE_FREQ, /*offset:*/ 0, recv_time);
1693                        return 1; /* "ok to increase poll interval" */
1694                }
1695#endif
1696                abs_offset = offset = 0;
1697                set_new_values(STATE_SYNC, offset, recv_time);
1698        } else { /* abs_offset <= STEP_THRESHOLD */
1699
1700                /* The ratio is calculated before jitter is updated to make
1701                 * poll adjust code more sensitive to large offsets.
1702                 */
1703                G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
1704
1705                /* Compute the clock jitter as the RMS of exponentially
1706                 * weighted offset differences. Used by the poll adjust code.
1707                 */
1708                etemp = SQUARE(G.discipline_jitter);
1709                dtemp = SQUARE(offset - G.last_update_offset);
1710                G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1711                if (G.discipline_jitter < G_precision_sec)
1712                        G.discipline_jitter = G_precision_sec;
1713
1714                switch (G.discipline_state) {
1715                case STATE_NSET:
1716                        if (option_mask32 & OPT_q) {
1717                                /* We were only asked to set time once.
1718                                 * The clock is precise enough, no need to step.
1719                                 */
1720                                exit(0);
1721                        }
1722#if USING_INITIAL_FREQ_ESTIMATION
1723                        /* This is the first update received and the frequency
1724                         * has not been initialized. The first thing to do
1725                         * is directly measure the oscillator frequency.
1726                         */
1727                        set_new_values(STATE_FREQ, offset, recv_time);
1728#else
1729                        set_new_values(STATE_SYNC, offset, recv_time);
1730#endif
1731                        VERB4 bb_simple_error_msg("transitioning to FREQ, datapoint ignored");
1732                        return 0; /* "leave poll interval as is" */
1733
1734#if 0 /* this is dead code for now */
1735                case STATE_FSET:
1736                        /* This is the first update and the frequency
1737                         * has been initialized. Adjust the phase, but
1738                         * don't adjust the frequency until the next update.
1739                         */
1740                        set_new_values(STATE_SYNC, offset, recv_time);
1741                        /* freq_drift remains 0 */
1742                        break;
1743#endif
1744
1745#if USING_INITIAL_FREQ_ESTIMATION
1746                case STATE_FREQ:
1747                        /* since_last_update >= WATCH_THRESHOLD, we waited enough.
1748                         * Correct the phase and frequency and switch to SYNC state.
1749                         * freq_drift was already estimated (see code above)
1750                         */
1751                        set_new_values(STATE_SYNC, offset, recv_time);
1752                        break;
1753#endif
1754
1755                default:
1756#if !USING_KERNEL_PLL_LOOP
1757                        /* Compute freq_drift due to PLL and FLL contributions.
1758                         *
1759                         * The FLL and PLL frequency gain constants
1760                         * depend on the poll interval and Allan
1761                         * intercept. The FLL is not used below one-half
1762                         * the Allan intercept. Above that the loop gain
1763                         * increases in steps to 1 / AVG.
1764                         */
1765                        if ((1 << G.poll_exp) > ALLAN / 2) {
1766                                etemp = FLL - G.poll_exp;
1767                                if (etemp < AVG)
1768                                        etemp = AVG;
1769                                freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1770                        }
1771                        /* For the PLL the integration interval
1772                         * (numerator) is the minimum of the update
1773                         * interval and poll interval. This allows
1774                         * oversampling, but not undersampling.
1775                         */
1776                        etemp = MIND(since_last_update, (1 << G.poll_exp));
1777                        dtemp = (4 * PLL) << G.poll_exp;
1778                        freq_drift += offset * etemp / SQUARE(dtemp);
1779#endif
1780                        set_new_values(STATE_SYNC, offset, recv_time);
1781                        break;
1782                }
1783                if (G.stratum != p->lastpkt_stratum + 1) {
1784                        G.stratum = p->lastpkt_stratum + 1;
1785                        run_script("stratum", offset);
1786                }
1787        }
1788
1789        G.reftime = G.cur_time;
1790        G.ntp_status = p->lastpkt_status;
1791#if ENABLE_FEATURE_NTPD_SERVER
1792        /* Our current refid is the IPv4 (or md5-hashed IPv6) address of the peer we took time from: */
1793        G.refid = p->p_refid;
1794#endif
1795        G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1796        dtemp = p->filter_jitter; // SQRT(SQUARE(p->filter_jitter) + SQUARE(G.cluster_jitter));
1797        dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
1798        G.rootdisp = p->lastpkt_rootdisp + dtemp;
1799        VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1800
1801        /* We are in STATE_SYNC now, but did not do adjtimex yet.
1802         * (Any other state does not reach this, they all return earlier)
1803         * By this time, freq_drift and offset are set
1804         * to values suitable for adjtimex.
1805         */
1806#if !USING_KERNEL_PLL_LOOP
1807        /* Calculate the new frequency drift and frequency stability (wander).
1808         * Compute the clock wander as the RMS of exponentially weighted
1809         * frequency differences. This is not used directly, but can,
1810         * along with the jitter, be a highly useful monitoring and
1811         * debugging tool.
1812         */
1813        dtemp = G.discipline_freq_drift + freq_drift;
1814        G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1815        etemp = SQUARE(G.discipline_wander);
1816        dtemp = SQUARE(dtemp);
1817        G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1818
1819        VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1820                        G.discipline_freq_drift,
1821                        (long)(G.discipline_freq_drift * 65536e6),
1822                        freq_drift,
1823                        G.discipline_wander);
1824#endif
1825        VERB4 {
1826                memset(&tmx, 0, sizeof(tmx));
1827                if (adjtimex(&tmx) < 0)
1828                        bb_simple_perror_msg_and_die("adjtimex");
1829                bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
1830                                tmx.freq, tmx.offset, tmx.status, tmx.constant);
1831        }
1832
1833        memset(&tmx, 0, sizeof(tmx));
1834#if 0
1835//doesn't work, offset remains 0 (!) in kernel:
1836//ntpd:  set adjtimex freq:1786097 tmx.offset:77487
1837//ntpd: prev adjtimex freq:1786097 tmx.offset:0
1838//ntpd:  cur adjtimex freq:1786097 tmx.offset:0
1839        tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1840        /* 65536 is one ppm */
1841        tmx.freq = G.discipline_freq_drift * 65536e6;
1842#endif
1843        tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;// | ADJ_MAXERROR | ADJ_ESTERROR;
1844
1845        tmx.offset = (long)(offset * 1000000); /* usec */
1846        if (SLEW_THRESHOLD < STEP_THRESHOLD) {
1847                if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
1848                        tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
1849                }
1850                if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
1851                        tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
1852                }
1853        }
1854
1855        tmx.status = STA_PLL;
1856        if (G.FREQHOLD_cnt != 0) {
1857                /* man adjtimex on STA_FREQHOLD:
1858                 * "Normally adjustments made via ADJ_OFFSET result in dampened
1859                 * frequency adjustments also being made.
1860                 * This flag prevents the small frequency adjustment from being
1861                 * made when correcting for an ADJ_OFFSET value."
1862                 *
1863                 * Use this flag for a few first adjustments at the beginning
1864                 * of ntpd execution, otherwise even relatively small initial
1865                 * offset tend to cause largish changes to in-kernel tmx.freq.
1866                 * If ntpd was restarted due to e.g. switch to another network,
1867                 * this destroys already well-established tmx.freq value.
1868                 */
1869                if (G.FREQHOLD_cnt < 0) {
1870                        /* Initialize it */
1871// Example: a laptop whose clock runs slower when hibernated,
1872// after wake up it still has good tmx.freq, but accumulated ~0.5 sec offset:
1873// Run with code where initial G.FREQHOLD_cnt was always 8:
1874//15:17:52.947 no valid datapoints, no peer selected
1875//15:17:56.515 update from:<IP> offset:+0.485133 delay:0.157762 jitter:0.209310 clock drift:-1.393ppm tc:4
1876//15:17:57.719 update from:<IP> offset:+0.483825 delay:0.158070 jitter:0.181159 clock drift:-1.393ppm tc:4
1877//15:17:59.925 update from:<IP> offset:+0.479504 delay:0.158147 jitter:0.156657 clock drift:-1.393ppm tc:4
1878//15:18:33.322 update from:<IP> offset:+0.428119 delay:0.158317 jitter:0.138071 clock drift:-1.393ppm tc:4
1879//15:19:06.718 update from:<IP> offset:+0.376932 delay:0.158276 jitter:0.122075 clock drift:-1.393ppm tc:4
1880//15:19:39.114 update from:<IP> offset:+0.327022 delay:0.158384 jitter:0.108538 clock drift:-1.393ppm tc:4
1881//15:20:12.715 update from:<IP> offset:+0.275596 delay:0.158297 jitter:0.097292 clock drift:-1.393ppm tc:4
1882//15:20:45.111 update from:<IP> offset:+0.225715 delay:0.158271 jitter:0.087841 clock drift:-1.393ppm tc:4
1883// If allowed to continue, it would start increasing tmx.freq now.
1884// Instead, it was ^Ced, and started anew:
1885//15:21:15.043 no valid datapoints, no peer selected
1886//15:21:17.408 update from:<IP> offset:+0.175910 delay:0.158314 jitter:0.076683 clock drift:-1.393ppm tc:4
1887//15:21:19.774 update from:<IP> offset:+0.171784 delay:0.158401 jitter:0.066436 clock drift:-1.393ppm tc:4
1888//15:21:22.140 update from:<IP> offset:+0.171660 delay:0.158592 jitter:0.057536 clock drift:-1.393ppm tc:4
1889//15:21:22.140 update from:<IP> offset:+0.167126 delay:0.158507 jitter:0.049792 clock drift:-1.393ppm tc:4
1890//15:21:55.696 update from:<IP> offset:+0.115223 delay:0.158277 jitter:0.050240 clock drift:-1.393ppm tc:4
1891//15:22:29.093 update from:<IP> offset:+0.068051 delay:0.158243 jitter:0.049405 clock drift:-1.393ppm tc:5
1892//15:23:02.490 update from:<IP> offset:+0.051632 delay:0.158215 jitter:0.043545 clock drift:-1.393ppm tc:5
1893//15:23:34.726 update from:<IP> offset:+0.039984 delay:0.158157 jitter:0.038106 clock drift:-1.393ppm tc:5
1894// STA_FREQHOLD no longer set, started increasing tmx.freq now:
1895//15:24:06.961 update from:<IP> offset:+0.030968 delay:0.158190 jitter:0.033306 clock drift:+2.387ppm tc:5
1896//15:24:40.357 update from:<IP> offset:+0.023648 delay:0.158211 jitter:0.029072 clock drift:+5.454ppm tc:5
1897//15:25:13.774 update from:<IP> offset:+0.018068 delay:0.157660 jitter:0.025288 clock drift:+7.728ppm tc:5
1898//15:26:19.173 update from:<IP> offset:+0.010057 delay:0.157969 jitter:0.022255 clock drift:+8.361ppm tc:6
1899//15:27:26.602 update from:<IP> offset:+0.006737 delay:0.158103 jitter:0.019316 clock drift:+8.792ppm tc:6
1900//15:28:33.030 update from:<IP> offset:+0.004513 delay:0.158294 jitter:0.016765 clock drift:+9.080ppm tc:6
1901//15:29:40.617 update from:<IP> offset:+0.002787 delay:0.157745 jitter:0.014543 clock drift:+9.258ppm tc:6
1902//15:30:47.045 update from:<IP> offset:+0.001324 delay:0.157709 jitter:0.012594 clock drift:+9.342ppm tc:6
1903//15:31:53.473 update from:<IP> offset:+0.000007 delay:0.158142 jitter:0.010922 clock drift:+9.343ppm tc:6
1904//15:32:58.902 update from:<IP> offset:-0.000728 delay:0.158222 jitter:0.009454 clock drift:+9.298ppm tc:6
1905                        /*
1906                         * This expression would choose MIN_FREQHOLD + 14 in the above example
1907                         * (off_032 is +1 for each 0.032768 seconds of offset).
1908                         */
1909                        unsigned off_032 = abs((int)(tmx.offset >> 15));
1910                        G.FREQHOLD_cnt = 1 + MIN_FREQHOLD + off_032;
1911                }
1912                G.FREQHOLD_cnt--;
1913                tmx.status |= STA_FREQHOLD;
1914        }
1915        if (G.ntp_status & LI_PLUSSEC)
1916                tmx.status |= STA_INS;
1917        if (G.ntp_status & LI_MINUSSEC)
1918                tmx.status |= STA_DEL;
1919
1920        tmx.constant = (int)G.poll_exp - 4;
1921        /* EXPERIMENTAL.
1922         * The below if statement should be unnecessary, but...
1923         * It looks like Linux kernel's PLL is far too gentle in changing
1924         * tmx.freq in response to clock offset. Offset keeps growing
1925         * and eventually we fall back to smaller poll intervals.
1926         * We can make correction more aggressive (about x2) by supplying
1927         * PLL time constant which is one less than the real one.
1928         * To be on a safe side, let's do it only if offset is significantly
1929         * larger than jitter.
1930         */
1931        if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
1932                tmx.constant--;
1933        if (tmx.constant < 0)
1934                tmx.constant = 0;
1935
1936        //tmx.esterror = (uint32_t)(clock_jitter * 1e6);
1937        //tmx.maxerror = (uint32_t)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
1938        rc = adjtimex(&tmx);
1939        if (rc < 0)
1940                bb_simple_perror_msg_and_die("adjtimex");
1941        /* NB: here kernel returns constant == G.poll_exp, not == G.poll_exp - 4.
1942         * Not sure why. Perhaps it is normal.
1943         */
1944        VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
1945                                rc, tmx.freq, tmx.offset, tmx.status);
1946        G.kernel_freq_drift = tmx.freq / 65536;
1947        VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
1948                        p->p_dotted,
1949                        offset,
1950                        p->p_raw_delay,
1951                        G.discipline_jitter,
1952                        (double)tmx.freq / 65536,
1953                        (int)tmx.constant
1954        );
1955
1956        return 1; /* "ok to increase poll interval" */
1957}
1958
1959
1960/*
1961 * We've got a new reply packet from a peer, process it
1962 * (helpers first)
1963 */
1964static unsigned
1965poll_interval(int upper_bound)
1966{
1967        unsigned interval, r, mask;
1968        interval = 1 << G.poll_exp;
1969        if (interval > upper_bound)
1970                interval = upper_bound;
1971        mask = ((interval-1) >> 4) | 1;
1972        r = rand();
1973        interval += r & mask; /* ~ random(0..1) * interval/16 */
1974        VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
1975        return interval;
1976}
1977static void
1978adjust_poll(int count)
1979{
1980        G.polladj_count += count;
1981        if (G.polladj_count > POLLADJ_LIMIT) {
1982                G.polladj_count = 0;
1983                if (G.poll_exp < MAXPOLL) {
1984                        G.poll_exp++;
1985                        VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1986                                        G.discipline_jitter, G.poll_exp);
1987                }
1988        } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
1989                G.polladj_count = 0;
1990                if (G.poll_exp > MINPOLL) {
1991                        llist_t *item;
1992
1993                        G.poll_exp--;
1994                        /* Correct p->next_action_time in each peer
1995                         * which waits for sending, so that they send earlier.
1996                         * Old pp->next_action_time are on the order
1997                         * of t + (1 << old_poll_exp) + small_random,
1998                         * we simply need to subtract ~half of that.
1999                         */
2000                        for (item = G.ntp_peers; item != NULL; item = item->link) {
2001                                peer_t *pp = (peer_t *) item->data;
2002                                if (pp->p_fd < 0)
2003                                        pp->next_action_time -= (1 << G.poll_exp);
2004                        }
2005                        VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
2006                                        G.discipline_jitter, G.poll_exp);
2007                }
2008        } else {
2009                VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
2010        }
2011}
2012static NOINLINE void
2013recv_and_process_peer_pkt(peer_t *p)
2014{
2015        int         rc;
2016        ssize_t     size;
2017        msg_t       msg;
2018        double      T1, T2, T3, T4;
2019        double      offset;
2020        double      prev_delay, delay;
2021        unsigned    interval;
2022        datapoint_t *datapoint;
2023        peer_t      *q;
2024
2025        offset = 0;
2026
2027        /* The below can happen as follows:
2028         * = we receive two peer rsponses at once.
2029         * = recv_and_process_peer_pkt(PEER1) -> update_local_clock()
2030         *   -> step_time() and it closes all other fds, sets all ->fd to -1.
2031         * = recv_and_process_peer_pkt(PEER2) sees PEER2->fd == -1
2032         */
2033        if (p->p_fd < 0)
2034                return;
2035
2036        /* We can recvfrom here and check from.IP, but some multihomed
2037         * ntp servers reply from their *other IP*.
2038         * TODO: maybe we should check at least what we can: from.port == 123?
2039         */
2040 recv_again:
2041        size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
2042        if (size < 0) {
2043                if (errno == EINTR)
2044                        /* Signal caught */
2045                        goto recv_again;
2046                if (errno == EAGAIN)
2047                        /* There was no packet after all
2048                         * (poll() returning POLLIN for a fd
2049                         * is not a ironclad guarantee that data is there)
2050                         */
2051                        return;
2052                /*
2053                 * If you need a different handling for a specific
2054                 * errno, always explain it in comment.
2055                 */
2056                bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
2057        }
2058
2059#if ENABLE_FEATURE_NTP_AUTH
2060        if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH) {
2061                bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
2062                return;
2063        }
2064        if (p->key_entry && hashes_differ(p, &msg)) {
2065                bb_error_msg("invalid cryptographic hash received from %s", p->p_dotted);
2066                return;
2067        }
2068#else
2069        if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH) {
2070                bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
2071                return;
2072        }
2073#endif
2074
2075        if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
2076         || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
2077        ) {
2078                /* Somebody else's packet */
2079                return;
2080        }
2081
2082        /* We do not expect any more packets from this peer for now.
2083         * Closing the socket informs kernel about it.
2084         * We open a new socket when we send a new query.
2085         */
2086        close(p->p_fd);
2087        p->p_fd = -1;
2088
2089        if ((msg.m_status & LI_ALARM) == LI_ALARM
2090         || msg.m_stratum == 0
2091         || msg.m_stratum > NTP_MAXSTRATUM
2092        ) {
2093                bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
2094                /*
2095                 * Stratum 0 responses may have commands in 32-bit m_refid field:
2096                 * "DENY", "RSTR" - peer does not like us at all,
2097                 * "RATE" - peer is overloaded, reduce polling freq.
2098                 * If poll interval is small, increase it.
2099                 */
2100                if (G.poll_exp < BIGPOLL)
2101                        goto increase_interval;
2102                goto pick_normal_interval;
2103        }
2104
2105//      /* Verify valid root distance */
2106//      if (msg.m_rootdelay / 2 + msg.m_rootdisp >= MAXDISP || p->lastpkt_reftime > msg.m_xmt)
2107//              return;                 /* invalid header values */
2108
2109        /*
2110         * From RFC 2030 (with a correction to the delay math):
2111         *
2112         * Timestamp Name          ID   When Generated
2113         * ------------------------------------------------------------
2114         * Originate Timestamp     T1   time request sent by client
2115         * Receive Timestamp       T2   time request received by server
2116         * Transmit Timestamp      T3   time reply sent by server
2117         * Destination Timestamp   T4   time reply received by client
2118         *
2119         * The roundtrip delay and local clock offset are defined as
2120         *
2121         * delay = (T4 - T1) - (T3 - T2); offset = ((T2 - T1) + (T3 - T4)) / 2
2122         */
2123        T1 = p->p_xmttime;
2124        T2 = lfp_to_d(msg.m_rectime);
2125        T3 = lfp_to_d(msg.m_xmttime);
2126        T4 = G.cur_time;
2127        delay = (T4 - T1) - (T3 - T2);
2128
2129        /*
2130         * If this packet's delay is much bigger than the last one,
2131         * it's better to just ignore it than use its much less precise value.
2132         */
2133        prev_delay = p->p_raw_delay;
2134        p->p_raw_delay = (delay < 0 ? 0.0 : delay);
2135        if (p->reachable_bits
2136         && delay > prev_delay * BAD_DELAY_GROWTH
2137         && delay > 1.0 / (8 * 1024) /* larger than ~0.000122 */
2138        ) {
2139                bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
2140                goto pick_normal_interval;
2141        }
2142
2143        /* The delay calculation is a special case. In cases where the
2144         * server and client clocks are running at different rates and
2145         * with very fast networks, the delay can appear negative. In
2146         * order to avoid violating the Principle of Least Astonishment,
2147         * the delay is clamped not less than the system precision.
2148         */
2149        if (delay < G_precision_sec)
2150                delay = G_precision_sec;
2151        p->lastpkt_delay = delay;
2152        p->lastpkt_recv_time = T4;
2153        VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
2154        p->lastpkt_status = msg.m_status;
2155        p->lastpkt_stratum = msg.m_stratum;
2156        p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
2157        p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
2158        p->lastpkt_refid = msg.m_refid;
2159
2160        p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
2161        datapoint = &p->filter_datapoint[p->datapoint_idx];
2162        datapoint->d_recv_time = T4;
2163        datapoint->d_offset    = offset = ((T2 - T1) + (T3 - T4)) / 2;
2164        datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
2165        if (!p->reachable_bits) {
2166                /* 1st datapoint ever - replicate offset in every element */
2167                int i;
2168                for (i = 0; i < NUM_DATAPOINTS; i++) {
2169                        p->filter_datapoint[i].d_offset = offset;
2170                }
2171        }
2172
2173        p->reachable_bits |= 1;
2174        if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
2175                bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
2176                        p->p_dotted,
2177                        offset,
2178                        p->p_raw_delay,
2179                        p->lastpkt_status,
2180                        p->lastpkt_stratum,
2181                        p->lastpkt_refid,
2182                        p->lastpkt_rootdelay,
2183                        p->reachable_bits
2184                        /* not shown: m_ppoll, m_precision_exp, m_rootdisp,
2185                         * m_reftime, m_orgtime, m_rectime, m_xmttime
2186                         */
2187                );
2188        }
2189
2190        /* Muck with statictics and update the clock */
2191        filter_datapoints(p);
2192        q = select_and_cluster();
2193        rc = 0;
2194        if (q) {
2195                if (!(option_mask32 & OPT_w)) {
2196                        rc = update_local_clock(q);
2197#if 0
2198//Disabled this because there is a case where largish offsets
2199//are unavoidable: if network round-trip delay is, say, ~0.6s,
2200//error in offset estimation would be ~delay/2 ~= 0.3s.
2201//Thus, offsets will be usually in -0.3...0.3s range.
2202//In this case, this code would keep poll interval small,
2203//but it won't be helping.
2204//BIGOFF check below deals with a case of seeing multi-second offsets.
2205
2206                        /* If drift is dangerously large, immediately
2207                         * drop poll interval one step down.
2208                         */
2209                        if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
2210                                VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
2211                                adjust_poll(-POLLADJ_LIMIT * 3);
2212                                rc = 0;
2213                        }
2214#endif
2215                }
2216        } else {
2217                /* No peer selected.
2218                 * If poll interval is small, increase it.
2219                 */
2220                if (G.poll_exp < BIGPOLL)
2221                        goto increase_interval;
2222        }
2223
2224        if (rc != 0) {
2225                /* Adjust the poll interval by comparing the current offset
2226                 * with the clock jitter. If the offset is less than
2227                 * the clock jitter times a constant, then the averaging interval
2228                 * is increased, otherwise it is decreased. A bit of hysteresis
2229                 * helps calm the dance. Works best using burst mode.
2230                 */
2231                if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
2232                        /* was += G.poll_exp but it is a bit
2233                         * too optimistic for my taste at high poll_exp's */
2234 increase_interval:
2235                        adjust_poll(MINPOLL);
2236                } else {
2237                        VERB3 if (rc > 0)
2238                                bb_error_msg("want smaller interval: offset/jitter = %u",
2239                                        G.offset_to_jitter_ratio);
2240                        adjust_poll(-G.poll_exp * 2);
2241                }
2242        }
2243
2244        /* Decide when to send new query for this peer */
2245 pick_normal_interval:
2246        interval = poll_interval(INT_MAX);
2247        if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
2248                /* If we are synced, offsets are less than SLEW_THRESHOLD,
2249                 * or at the very least not much larger than it.
2250                 * Now we see a largish one.
2251                 * Either this peer is feeling bad, or packet got corrupted,
2252                 * or _our_ clock is wrong now and _all_ peers will show similar
2253                 * largish offsets too.
2254                 * I observed this with laptop suspend stopping clock.
2255                 * In any case, it makes sense to make next request soonish:
2256                 * cases 1 and 2: get a better datapoint,
2257                 * case 3: allows to resync faster.
2258                 */
2259                interval = BIGOFF_INTERVAL;
2260        }
2261
2262        set_next(p, interval);
2263}
2264
2265#if ENABLE_FEATURE_NTPD_SERVER
2266static NOINLINE void
2267recv_and_process_client_pkt(void /*int fd*/)
2268{
2269        ssize_t          size;
2270        //uint8_t          version;
2271        len_and_sockaddr *to;
2272        struct sockaddr  *from;
2273        msg_t            msg;
2274        uint8_t          query_status;
2275        l_fixedpt_t      query_xmttime;
2276
2277        to = get_sock_lsa(G_listen_fd);
2278        from = xzalloc(to->len);
2279
2280        size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
2281
2282        /* "ntpq -p" (4.2.8p13) sends a 12-byte NTPv2 request:
2283         * m_status is 0x16: leap:0 version:2 mode:6(reserved1)
2284         *  https://docs.ntpsec.org/latest/mode6.html
2285         * We don't support this.
2286         */
2287
2288# if ENABLE_FEATURE_NTP_AUTH
2289        if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH)
2290# else
2291        if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH)
2292# endif
2293        {
2294                char *addr;
2295                if (size < 0) {
2296                        if (errno == EAGAIN)
2297                                goto bail;
2298                        bb_simple_perror_msg_and_die("recv");
2299                }
2300                addr = xmalloc_sockaddr2dotted_noport(from);
2301                bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
2302                free(addr);
2303                goto bail;
2304        }
2305
2306        /* Respond only to client and symmetric active packets */
2307        if ((msg.m_status & MODE_MASK) != MODE_CLIENT
2308         && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
2309        ) {
2310                goto bail;
2311        }
2312
2313        query_status = msg.m_status;
2314        query_xmttime = msg.m_xmttime;
2315
2316        /* Build a reply packet */
2317        memset(&msg, 0, sizeof(msg));
2318        msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
2319        msg.m_status |= (query_status & VERSION_MASK);
2320        msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
2321                        MODE_SERVER : MODE_SYM_PAS;
2322        msg.m_stratum = G.stratum;
2323        msg.m_ppoll = G.poll_exp;
2324        msg.m_precision_exp = G_precision_exp;
2325        /* this time was obtained between poll() and recv() */
2326        msg.m_rectime = d_to_lfp(G.cur_time);
2327        msg.m_xmttime = d_to_lfp(gettime1900d()); /* this instant */
2328        if (G.peer_cnt == 0) {
2329                /* we have no peers: "stratum 1 server" mode. reftime = our own time */
2330                G.reftime = G.cur_time;
2331        }
2332        msg.m_reftime = d_to_lfp(G.reftime);
2333        msg.m_orgtime = query_xmttime;
2334        msg.m_rootdelay = d_to_sfp(G.rootdelay);
2335//simple code does not do this, fix simple code!
2336        msg.m_rootdisp = d_to_sfp(G.rootdisp);
2337        //version = (query_status & VERSION_MASK); /* ... >> VERSION_SHIFT - done below instead */
2338        msg.m_refid = G.refid; // (version > (3 << VERSION_SHIFT)) ? G.refid : G.refid3;
2339
2340        /* We reply from the local address packet was sent to,
2341         * this makes to/from look swapped here: */
2342        do_sendto(G_listen_fd,
2343                /*from:*/ &to->u.sa, /*to:*/ from, /*addrlen:*/ to->len,
2344                &msg, size);
2345
2346 bail:
2347        free(to);
2348        free(from);
2349}
2350#endif
2351
2352/* Upstream ntpd's options:
2353 *
2354 * -4   Force DNS resolution of host names to the IPv4 namespace.
2355 * -6   Force DNS resolution of host names to the IPv6 namespace.
2356 * -a   Require cryptographic authentication for broadcast client,
2357 *      multicast client and symmetric passive associations.
2358 *      This is the default.
2359 * -A   Do not require cryptographic authentication for broadcast client,
2360 *      multicast client and symmetric passive associations.
2361 *      This is almost never a good idea.
2362 * -b   Enable the client to synchronize to broadcast servers.
2363 * -c conffile
2364 *      Specify the name and path of the configuration file,
2365 *      default /etc/ntp.conf
2366 * -d   Specify debugging mode. This option may occur more than once,
2367 *      with each occurrence indicating greater detail of display.
2368 * -D level
2369 *      Specify debugging level directly.
2370 * -f driftfile
2371 *      Specify the name and path of the frequency file.
2372 *      This is the same operation as the "driftfile FILE"
2373 *      configuration command.
2374 * -g   Normally, ntpd exits with a message to the system log
2375 *      if the offset exceeds the panic threshold, which is 1000 s
2376 *      by default. This option allows the time to be set to any value
2377 *      without restriction; however, this can happen only once.
2378 *      If the threshold is exceeded after that, ntpd will exit
2379 *      with a message to the system log. This option can be used
2380 *      with the -q and -x options. See the tinker command for other options.
2381 * -i jaildir
2382 *      Chroot the server to the directory jaildir. This option also implies
2383 *      that the server attempts to drop root privileges at startup
2384 *      (otherwise, chroot gives very little additional security).
2385 *      You may need to also specify a -u option.
2386 * -k keyfile
2387 *      Specify the name and path of the symmetric key file,
2388 *      default /etc/ntp/keys. This is the same operation
2389 *      as the "keys FILE" configuration command.
2390 * -l logfile
2391 *      Specify the name and path of the log file. The default
2392 *      is the system log file. This is the same operation as
2393 *      the "logfile FILE" configuration command.
2394 * -L   Do not listen to virtual IPs. The default is to listen.
2395 * -n   Don't fork.
2396 * -N   To the extent permitted by the operating system,
2397 *      run the ntpd at the highest priority.
2398 * -p pidfile
2399 *      Specify the name and path of the file used to record the ntpd
2400 *      process ID. This is the same operation as the "pidfile FILE"
2401 *      configuration command.
2402 * -P priority
2403 *      To the extent permitted by the operating system,
2404 *      run the ntpd at the specified priority.
2405 * -q   Exit the ntpd just after the first time the clock is set.
2406 *      This behavior mimics that of the ntpdate program, which is
2407 *      to be retired. The -g and -x options can be used with this option.
2408 *      Note: The kernel time discipline is disabled with this option.
2409 * -r broadcastdelay
2410 *      Specify the default propagation delay from the broadcast/multicast
2411 *      server to this client. This is necessary only if the delay
2412 *      cannot be computed automatically by the protocol.
2413 * -s statsdir
2414 *      Specify the directory path for files created by the statistics
2415 *      facility. This is the same operation as the "statsdir DIR"
2416 *      configuration command.
2417 * -t key
2418 *      Add a key number to the trusted key list. This option can occur
2419 *      more than once.
2420 * -u user[:group]
2421 *      Specify a user, and optionally a group, to switch to.
2422 * -v variable
2423 * -V variable
2424 *      Add a system variable listed by default.
2425 * -x   Normally, the time is slewed if the offset is less than the step
2426 *      threshold, which is 128 ms by default, and stepped if above
2427 *      the threshold. This option sets the threshold to 600 s, which is
2428 *      well within the accuracy window to set the clock manually.
2429 *      Note: since the slew rate of typical Unix kernels is limited
2430 *      to 0.5 ms/s, each second of adjustment requires an amortization
2431 *      interval of 2000 s. Thus, an adjustment as much as 600 s
2432 *      will take almost 14 days to complete. This option can be used
2433 *      with the -g and -q options. See the tinker command for other options.
2434 *      Note: The kernel time discipline is disabled with this option.
2435 */
2436#if ENABLE_FEATURE_NTP_AUTH
2437static key_entry_t *
2438find_key_entry(llist_t *key_entries, unsigned id)
2439{
2440        while (key_entries) {
2441                key_entry_t *cur = (key_entry_t*) key_entries->data;
2442                if (cur->id == id)
2443                        return cur;
2444                key_entries = key_entries->link;
2445        }
2446        bb_error_msg_and_die("key %u is not defined", id);
2447}
2448#endif
2449
2450/* By doing init in a separate function we decrease stack usage
2451 * in main loop.
2452 */
2453static NOINLINE void ntp_init(char **argv)
2454{
2455        unsigned opts;
2456        llist_t *peers;
2457#if ENABLE_FEATURE_NTP_AUTH
2458        llist_t *key_entries;
2459        char *key_file_path;
2460#endif
2461
2462        srand(getpid());
2463
2464        /* Set some globals */
2465        G.discipline_jitter = G_precision_sec;
2466        G.stratum = MAXSTRAT;
2467        if (BURSTPOLL != 0)
2468                G.poll_exp = BURSTPOLL; /* speeds up initial sync */
2469        G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d(); /* sets G.cur_time too */
2470        G.FREQHOLD_cnt = -1;
2471
2472        /* Parse options */
2473        peers = NULL;
2474        IF_FEATURE_NTP_AUTH(key_entries = NULL;)
2475        opts = getopt32(argv, "^"
2476                        "nqNx" /* compat */
2477                        IF_FEATURE_NTP_AUTH("k:")  /* compat */
2478                        "wp:*S:"IF_FEATURE_NTPD_SERVER("l") /* NOT compat */
2479                        IF_FEATURE_NTPD_SERVER("I:") /* compat */
2480                        "d" /* compat */
2481                        "46aAbgL" /* compat, ignored */
2482                                "\0"
2483                                "=0"      /* should have no arguments */
2484                                ":dd:wn"  /* -d: counter; -p: list; -w implies -n */
2485                                IF_FEATURE_NTPD_SERVER(":Il") /* -I implies -l */
2486                        IF_FEATURE_NTP_AUTH(, &key_file_path)
2487                        , &peers, &G.script_name
2488                        IF_FEATURE_NTPD_SERVER(, &G.if_name)
2489                        , &G.verbose
2490        );
2491
2492//      if (opts & OPT_x) /* disable stepping, only slew is allowed */
2493//              G.time_was_stepped = 1;
2494
2495#if ENABLE_FEATURE_NTPD_SERVER
2496        G_listen_fd = -1;
2497        if (opts & OPT_l) {
2498                G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
2499                if (G.if_name) {
2500                        if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
2501                                xfunc_die();
2502                }
2503                socket_want_pktinfo(G_listen_fd);
2504                setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
2505        }
2506#endif
2507        /* I hesitate to set -20 prio. -15 should be high enough for timekeeping */
2508        if (opts & OPT_N)
2509                setpriority(PRIO_PROCESS, 0, -15);
2510
2511        if (!(opts & OPT_n)) {
2512                bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
2513                logmode = LOGMODE_NONE;
2514        }
2515
2516#if ENABLE_FEATURE_NTP_AUTH
2517        if (opts & OPT_k) {
2518                char *tokens[4];
2519                parser_t *parser;
2520
2521                parser = config_open(key_file_path);
2522                while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL | PARSE_MIN_DIE) == 3) {
2523                        key_entry_t *key_entry;
2524                        char buffer[40];
2525                        smalluint hash_type;
2526                        smalluint msg_size;
2527                        smalluint key_length;
2528                        char *key;
2529
2530                        if ((tokens[1][0] | 0x20) == 'm')
2531                                /* supports 'M' and 'md5' formats */
2532                                hash_type = HASH_MD5;
2533                        else
2534                        if (strncasecmp(tokens[1], "sha", 3) == 0)
2535                                /* supports 'sha' and 'sha1' formats */
2536                                hash_type = HASH_SHA1;
2537                        else
2538                                bb_simple_error_msg_and_die("only MD5 and SHA1 keys supported");
2539/* man ntp.keys:
2540 *  MD5    The key is 1 to 16 printable characters terminated by an EOL,
2541 *         whitespace, or a # (which is the "start of comment" character).
2542 *  SHA
2543 *  SHA1
2544 *  RMD160 The key is a hex-encoded ASCII string of 40 characters, which
2545 *         is truncated as necessary.
2546 */
2547                        key_length = strnlen(tokens[2], sizeof(buffer)+1);
2548                        if (key_length >= sizeof(buffer)+1) {
2549 err:
2550                                bb_error_msg_and_die("malformed key at line %u", parser->lineno);
2551                        }
2552                        if (hash_type == HASH_MD5) {
2553                                key = tokens[2];
2554                                msg_size = NTP_MSGSIZE_MD5_AUTH;
2555                        } else /* it's hash_type == HASH_SHA1 */
2556                        if (!(key_length & 1)) {
2557                                key_length >>= 1;
2558                                if (!hex2bin(buffer, tokens[2], key_length))
2559                                        goto err;
2560                                key = buffer;
2561                                msg_size = NTP_MSGSIZE_SHA1_AUTH;
2562                        } else {
2563                                goto err;
2564                        }
2565                        key_entry = xzalloc(sizeof(*key_entry) + key_length);
2566                        key_entry->type = hash_type;
2567                        key_entry->msg_size = msg_size;
2568                        key_entry->key_length = key_length;
2569                        memcpy(key_entry->key, key, key_length);
2570                        key_entry->id = xatou_range(tokens[0], 1, MAX_KEY_NUMBER);
2571                        llist_add_to(&key_entries, key_entry);
2572                }
2573                config_close(parser);
2574        }
2575#endif
2576        if (peers) {
2577#if ENABLE_FEATURE_NTP_AUTH
2578                while (peers) {
2579                        char *peer = llist_pop(&peers);
2580                        key_entry_t *key_entry = NULL;
2581                        if (strncmp(peer, "keyno:", 6) == 0) {
2582                                char *end;
2583                                int key_id;
2584                                peer += 6;
2585                                end = strchr(peer, ':');
2586                                if (!end) bb_show_usage();
2587                                *end = '\0';
2588                                key_id = xatou_range(peer, 1, MAX_KEY_NUMBER);
2589                                *end = ':';
2590                                key_entry = find_key_entry(key_entries, key_id);
2591                                peer = end + 1;
2592                        }
2593                        add_peers(peer, key_entry);
2594                }
2595#else
2596                while (peers)
2597                        add_peers(llist_pop(&peers), NULL);
2598#endif
2599        }
2600#if ENABLE_FEATURE_NTPD_CONF
2601        else {
2602                parser_t *parser;
2603                char *token[3 + 2*ENABLE_FEATURE_NTP_AUTH];
2604
2605                parser = config_open("/etc/ntp.conf");
2606                while (config_read(parser, token, 3 + 2*ENABLE_FEATURE_NTP_AUTH, 1, "# \t", PARSE_NORMAL)) {
2607                        if (strcmp(token[0], "server") == 0 && token[1]) {
2608# if ENABLE_FEATURE_NTP_AUTH
2609                                key_entry_t *key_entry = NULL;
2610                                if (token[2] && token[3] && strcmp(token[2], "key") == 0) {
2611                                        unsigned key_id = xatou_range(token[3], 1, MAX_KEY_NUMBER);
2612                                        key_entry = find_key_entry(key_entries, key_id);
2613                                }
2614                                add_peers(token[1], key_entry);
2615# else
2616                                add_peers(token[1], NULL);
2617# endif
2618                                continue;
2619                        }
2620                        bb_error_msg("skipping %s:%u: unimplemented command '%s'",
2621                                "/etc/ntp.conf", parser->lineno, token[0]
2622                        );
2623                }
2624                config_close(parser);
2625        }
2626#endif
2627        if (G.peer_cnt == 0) {
2628                if (!(opts & OPT_l))
2629                        bb_show_usage();
2630                /* -l but no peers: "stratum 1 server" mode */
2631                G.stratum = 1;
2632        }
2633
2634        if (!(opts & OPT_n)) /* only if backgrounded: */
2635                write_pidfile_std_path_and_ext("ntpd");
2636
2637        /* If network is up, syncronization occurs in ~10 seconds.
2638         * We give "ntpd -q" 10 seconds to get first reply,
2639         * then another 50 seconds to finish syncing.
2640         *
2641         * I tested ntpd 4.2.6p1 and apparently it never exits
2642         * (will try forever), but it does not feel right.
2643         * The goal of -q is to act like ntpdate: set time
2644         * after a reasonably small period of polling, or fail.
2645         */
2646        if (opts & OPT_q) {
2647                option_mask32 |= OPT_qq;
2648                alarm(10);
2649        }
2650
2651        bb_signals(0
2652                | (1 << SIGTERM)
2653                | (1 << SIGINT)
2654                | (1 << SIGALRM)
2655                , record_signo
2656        );
2657        bb_signals(0
2658                | (1 << SIGPIPE)
2659                | (1 << SIGCHLD)
2660                , SIG_IGN
2661        );
2662//TODO: free unused elements of key_entries?
2663}
2664
2665int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
2666int ntpd_main(int argc UNUSED_PARAM, char **argv)
2667{
2668#undef G
2669        struct globals G;
2670        struct pollfd *pfd;
2671        peer_t **idx2peer;
2672        unsigned cnt;
2673
2674        memset(&G, 0, sizeof(G));
2675        SET_PTR_TO_GLOBALS(&G);
2676
2677        ntp_init(argv);
2678
2679        /* If ENABLE_FEATURE_NTPD_SERVER, + 1 for listen_fd: */
2680        cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
2681        idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
2682        pfd = xzalloc(sizeof(pfd[0]) * cnt);
2683
2684        /* Countdown: we never sync before we sent INITIAL_SAMPLES+1
2685         * packets to each peer.
2686         * NB: if some peer is not responding, we may end up sending
2687         * fewer packets to it and more to other peers.
2688         * NB2: sync usually happens using INITIAL_SAMPLES packets,
2689         * since last reply does not come back instantaneously.
2690         */
2691        cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
2692
2693        while (!bb_got_signal) {
2694                llist_t *item;
2695                unsigned i, j;
2696                int nfds, timeout;
2697                double nextaction;
2698
2699                /* Nothing between here and poll() blocks for any significant time */
2700
2701                nextaction = G.last_script_run + (11*60);
2702                if (nextaction < G.cur_time + 1)
2703                        nextaction = G.cur_time + 1;
2704
2705                i = 0;
2706#if ENABLE_FEATURE_NTPD_SERVER
2707                if (G_listen_fd != -1) {
2708                        pfd[0].fd = G_listen_fd;
2709                        pfd[0].events = POLLIN;
2710                        i++;
2711                }
2712#endif
2713                /* Pass over peer list, send requests, time out on receives */
2714                for (item = G.ntp_peers; item != NULL; item = item->link) {
2715                        peer_t *p = (peer_t *) item->data;
2716
2717                        if (p->next_action_time <= G.cur_time) {
2718                                if (p->p_fd == -1) {
2719                                        /* Time to send new req */
2720                                        if (--cnt == 0) {
2721                                                VERB4 bb_simple_error_msg("disabling burst mode");
2722                                                G.polladj_count = 0;
2723                                                G.poll_exp = MINPOLL;
2724                                        }
2725                                        send_query_to_peer(p);
2726                                } else {
2727                                        /* Timed out waiting for reply */
2728                                        close(p->p_fd);
2729                                        p->p_fd = -1;
2730                                        /* If poll interval is small, increase it */
2731                                        if (G.poll_exp < BIGPOLL)
2732                                                adjust_poll(MINPOLL);
2733                                        timeout = poll_interval(NOREPLY_INTERVAL);
2734                                        bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
2735                                                        p->p_dotted, p->reachable_bits, timeout);
2736
2737                                        /* What if don't see it because it changed its IP? */
2738                                        if (p->reachable_bits == 0)
2739                                                resolve_peer_hostname(p);
2740
2741                                        set_next(p, timeout);
2742                                }
2743                        }
2744
2745                        if (p->next_action_time < nextaction)
2746                                nextaction = p->next_action_time;
2747
2748                        if (p->p_fd >= 0) {
2749                                /* Wait for reply from this peer */
2750                                pfd[i].fd = p->p_fd;
2751                                pfd[i].events = POLLIN;
2752                                idx2peer[i] = p;
2753                                i++;
2754                        }
2755                }
2756
2757                timeout = nextaction - G.cur_time;
2758                if (timeout < 0)
2759                        timeout = 0;
2760                timeout++; /* (nextaction - G.cur_time) rounds down, compensating */
2761
2762                /* Here we may block */
2763                VERB2 {
2764                        if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
2765                                /* We wait for at least one reply.
2766                                 * Poll for it, without wasting time for message.
2767                                 * Since replies often come under 1 second, this also
2768                                 * reduces clutter in logs.
2769                                 */
2770                                nfds = poll(pfd, i, 1000);
2771                                if (nfds != 0)
2772                                        goto did_poll;
2773                                if (--timeout <= 0)
2774                                        goto did_poll;
2775                        }
2776                        bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
2777                }
2778                nfds = poll(pfd, i, timeout * 1000);
2779 did_poll:
2780                gettime1900d(); /* sets G.cur_time */
2781                if (nfds <= 0) {
2782                        double ct;
2783                        int dns_error;
2784
2785                        if (bb_got_signal)
2786                                break; /* poll was interrupted by a signal */
2787
2788                        if (G.cur_time - G.last_script_run > 11*60) {
2789                                /* Useful for updating battery-backed RTC and such */
2790                                run_script("periodic", G.last_update_offset);
2791                                gettime1900d(); /* sets G.cur_time */
2792                        }
2793
2794                        /* Resolve peer names to IPs, if not resolved yet.
2795                         * We do it only when poll timed out:
2796                         * this way, we almost never overlap DNS resolution with
2797                         * "request-reply" packet round trip.
2798                         */
2799                        dns_error = 0;
2800                        ct = G.cur_time;
2801                        for (item = G.ntp_peers; item != NULL; item = item->link) {
2802                                peer_t *p = (peer_t *) item->data;
2803                                if (p->next_action_time <= ct && !p->p_lsa) {
2804                                        /* This can take up to ~10 sec per each DNS query */
2805                                        dns_error |= (!resolve_peer_hostname(p));
2806                                }
2807                        }
2808                        if (!dns_error)
2809                                goto check_unsync;
2810                        /* Set next time for those which are still not resolved */
2811                        gettime1900d(); /* sets G.cur_time (needed for set_next()) */
2812                        for (item = G.ntp_peers; item != NULL; item = item->link) {
2813                                peer_t *p = (peer_t *) item->data;
2814                                if (p->next_action_time <= ct && !p->p_lsa) {
2815                                        set_next(p, HOSTNAME_INTERVAL * p->dns_errors);
2816                                }
2817                        }
2818                        goto check_unsync;
2819                }
2820
2821                /* Process any received packets */
2822                j = 0;
2823#if ENABLE_FEATURE_NTPD_SERVER
2824                if (G.listen_fd != -1) {
2825                        if (pfd[0].revents /* & (POLLIN|POLLERR)*/) {
2826                                nfds--;
2827                                recv_and_process_client_pkt(/*G.listen_fd*/);
2828                                gettime1900d(); /* sets G.cur_time */
2829                        }
2830                        j = 1;
2831                }
2832#endif
2833                for (; nfds != 0 && j < i; j++) {
2834                        if (pfd[j].revents /* & (POLLIN|POLLERR)*/) {
2835                                /*
2836                                 * At init, alarm was set to 10 sec.
2837                                 * Now we did get a reply.
2838                                 * Increase timeout to 50 seconds to finish syncing.
2839                                 */
2840                                if (option_mask32 & OPT_qq) {
2841                                        option_mask32 &= ~OPT_qq;
2842                                        alarm(50);
2843                                }
2844                                nfds--;
2845                                recv_and_process_peer_pkt(idx2peer[j]);
2846                                gettime1900d(); /* sets G.cur_time */
2847                        }
2848                }
2849
2850 check_unsync:
2851                if (G.ntp_peers && G.stratum != MAXSTRAT) {
2852                        for (item = G.ntp_peers; item != NULL; item = item->link) {
2853                                peer_t *p = (peer_t *) item->data;
2854                                if (p->reachable_bits)
2855                                        goto have_reachable_peer;
2856                        }
2857                        /* No peer responded for last 8 packets, panic */
2858                        clamp_pollexp_and_set_MAXSTRAT();
2859                        run_script("unsync", 0.0);
2860 have_reachable_peer: ;
2861                }
2862        } /* while (!bb_got_signal) */
2863
2864        remove_pidfile_std_path_and_ext("ntpd");
2865        kill_myself_with_sig(bb_got_signal);
2866}
2867
2868
2869
2870
2871
2872
2873/*** openntpd-4.6 uses only adjtime, not adjtimex ***/
2874
2875/*** ntp-4.2.6/ntpd/ntp_loopfilter.c - adjtimex usage ***/
2876
2877#if 0
2878static double
2879direct_freq(double fp_offset)
2880{
2881#ifdef KERNEL_PLL
2882        /*
2883         * If the kernel is enabled, we need the residual offset to
2884         * calculate the frequency correction.
2885         */
2886        if (pll_control && kern_enable) {
2887                memset(&ntv, 0, sizeof(ntv));
2888                ntp_adjtime(&ntv);
2889#ifdef STA_NANO
2890                clock_offset = ntv.offset / 1e9;
2891#else /* STA_NANO */
2892                clock_offset = ntv.offset / 1e6;
2893#endif /* STA_NANO */
2894                drift_comp = FREQTOD(ntv.freq);
2895        }
2896#endif /* KERNEL_PLL */
2897        set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2898        wander_resid = 0;
2899        return drift_comp;
2900}
2901
2902static void
2903set_freq(double freq) /* frequency update */
2904{
2905        char tbuf[80];
2906
2907        drift_comp = freq;
2908
2909#ifdef KERNEL_PLL
2910        /*
2911         * If the kernel is enabled, update the kernel frequency.
2912         */
2913        if (pll_control && kern_enable) {
2914                memset(&ntv, 0, sizeof(ntv));
2915                ntv.modes = MOD_FREQUENCY;
2916                ntv.freq = DTOFREQ(drift_comp);
2917                ntp_adjtime(&ntv);
2918                snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2919                report_event(EVNT_FSET, NULL, tbuf);
2920        } else {
2921                snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2922                report_event(EVNT_FSET, NULL, tbuf);
2923        }
2924#else /* KERNEL_PLL */
2925        snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2926        report_event(EVNT_FSET, NULL, tbuf);
2927#endif /* KERNEL_PLL */
2928}
2929
2930...
2931...
2932...
2933
2934#ifdef KERNEL_PLL
2935        /*
2936         * This code segment works when clock adjustments are made using
2937         * precision time kernel support and the ntp_adjtime() system
2938         * call. This support is available in Solaris 2.6 and later,
2939         * Digital Unix 4.0 and later, FreeBSD, Linux and specially
2940         * modified kernels for HP-UX 9 and Ultrix 4. In the case of the
2941         * DECstation 5000/240 and Alpha AXP, additional kernel
2942         * modifications provide a true microsecond clock and nanosecond
2943         * clock, respectively.
2944         *
2945         * Important note: The kernel discipline is used only if the
2946         * step threshold is less than 0.5 s, as anything higher can
2947         * lead to overflow problems. This might occur if some misguided
2948         * lad set the step threshold to something ridiculous.
2949         */
2950        if (pll_control && kern_enable) {
2951
2952#define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2953
2954                /*
2955                 * We initialize the structure for the ntp_adjtime()
2956                 * system call. We have to convert everything to
2957                 * microseconds or nanoseconds first. Do not update the
2958                 * system variables if the ext_enable flag is set. In
2959                 * this case, the external clock driver will update the
2960                 * variables, which will be read later by the local
2961                 * clock driver. Afterwards, remember the time and
2962                 * frequency offsets for jitter and stability values and
2963                 * to update the frequency file.
2964                 */
2965                memset(&ntv,  0, sizeof(ntv));
2966                if (ext_enable) {
2967                        ntv.modes = MOD_STATUS;
2968                } else {
2969#ifdef STA_NANO
2970                        ntv.modes = MOD_BITS | MOD_NANO;
2971#else /* STA_NANO */
2972                        ntv.modes = MOD_BITS;
2973#endif /* STA_NANO */
2974                        if (clock_offset < 0)
2975                                dtemp = -.5;
2976                        else
2977                                dtemp = .5;
2978#ifdef STA_NANO
2979                        ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2980                        ntv.constant = sys_poll;
2981#else /* STA_NANO */
2982                        ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2983                        ntv.constant = sys_poll - 4;
2984#endif /* STA_NANO */
2985                        ntv.esterror = (u_int32)(clock_jitter * 1e6);
2986                        ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2987                        ntv.status = STA_PLL;
2988
2989                        /*
2990                         * Enable/disable the PPS if requested.
2991                         */
2992                        if (pps_enable) {
2993                                if (!(pll_status & STA_PPSTIME))
2994                                        report_event(EVNT_KERN,
2995                                                NULL, "PPS enabled");
2996                                ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2997                        } else {
2998                                if (pll_status & STA_PPSTIME)
2999                                        report_event(EVNT_KERN,
3000                                                NULL, "PPS disabled");
3001                                ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
3002                        }
3003                        if (sys_leap == LEAP_ADDSECOND)
3004                                ntv.status |= STA_INS;
3005                        else if (sys_leap == LEAP_DELSECOND)
3006                                ntv.status |= STA_DEL;
3007                }
3008
3009                /*
3010                 * Pass the stuff to the kernel. If it squeals, turn off
3011                 * the pps. In any case, fetch the kernel offset,
3012                 * frequency and jitter.
3013                 */
3014                if (ntp_adjtime(&ntv) == TIME_ERROR) {
3015                        if (!(ntv.status & STA_PPSSIGNAL))
3016                                report_event(EVNT_KERN, NULL,
3017                                                "PPS no signal");
3018                }
3019                pll_status = ntv.status;
3020#ifdef STA_NANO
3021                clock_offset = ntv.offset / 1e9;
3022#else /* STA_NANO */
3023                clock_offset = ntv.offset / 1e6;
3024#endif /* STA_NANO */
3025                clock_frequency = FREQTOD(ntv.freq);
3026
3027                /*
3028                 * If the kernel PPS is lit, monitor its performance.
3029                 */
3030                if (ntv.status & STA_PPSTIME) {
3031#ifdef STA_NANO
3032                        clock_jitter = ntv.jitter / 1e9;
3033#else /* STA_NANO */
3034                        clock_jitter = ntv.jitter / 1e6;
3035#endif /* STA_NANO */
3036                }
3037
3038#if defined(STA_NANO) && NTP_API == 4
3039                /*
3040                 * If the TAI changes, update the kernel TAI.
3041                 */
3042                if (loop_tai != sys_tai) {
3043                        loop_tai = sys_tai;
3044                        ntv.modes = MOD_TAI;
3045                        ntv.constant = sys_tai;
3046                        ntp_adjtime(&ntv);
3047                }
3048#endif /* STA_NANO */
3049        }
3050#endif /* KERNEL_PLL */
3051#endif
3052