1 /*        $NetBSD: ntp.h,v 1.14 2024/10/01 20:59:51 christos Exp $    */
2 
3 /*
4  * ntp.h - NTP definitions for the masses
5  */
6 #ifndef NTP_H
7 #define NTP_H
8 
9 #include <stddef.h>
10 #include <math.h>
11 
12 #include <ntp_fp.h>
13 #include <ntp_types.h>
14 #include <ntp_lists.h>
15 #include <ntp_stdlib.h>
16 #include <ntp_crypto.h>
17 #include <ntp_random.h>
18 #include <ntp_net.h>
19 
20 #include <isc/boolean.h>
21 
22 /*
23  * Calendar arithmetic - contributed by G. Healton
24  */
25 #define YEAR_BREAK 500                  /* years < this are tm_year values:
26                                          * Break < AnyFourDigitYear && Break >
27                                          * Anytm_yearYear */
28 
29 #define YEAR_PIVOT 98                   /* 97/98: years < this are year 2000+
30                                          * FYI: official UNIX pivot year is
31                                          * 68/69 */
32 
33 /*
34  * Number of Days since 1 BC Gregorian to 1 January of given year
35  */
36 #define julian0(year)         (((year) * 365 ) + ((year) > 0 ? (((year) + 3) \
37                                   / 4 - ((year - 1) / 100) + ((year - 1) / \
38                                   400)) : 0))
39 
40 /*
41  * Number of days since start of NTP time to 1 January of given year
42  */
43 #define ntp0(year)  (julian0(year) - julian0(1900))
44 
45 /*
46  * Number of days since start of UNIX time to 1 January of given year
47  */
48 #define unix0(year) (julian0(year) - julian0(1970))
49 
50 /*
51  * LEAP YEAR test for full 4-digit years (e.g, 1999, 2010)
52  */
53 #define isleap_4(y) ((y) % 4 == 0 && !((y) % 100 == 0 && !(y % \
54                                   400 == 0)))
55 
56 /*
57  * LEAP YEAR test for tm_year (struct tm) years (e.g, 99, 110)
58  */
59 #define isleap_tm(y)          ((y) % 4 == 0 && !((y) % 100 == 0 && !(((y) \
60                                   + 1900) % 400 == 0)))
61 
62 /*
63  * to convert simple two-digit years to tm_year style years:
64  *
65  *        if (year < YEAR_PIVOT)
66  *                  year += 100;
67  *
68  * to convert either two-digit OR tm_year years to four-digit years:
69  *
70  *        if (year < YEAR_PIVOT)
71  *                  year += 100;
72  *
73  *        if (year < YEAR_BREAK)
74  *                  year += 1900;
75  */
76 
77 /*
78  * How to get signed characters.  On machines where signed char works,
79  * use it. On machines where signed char doesn't work, char had better
80  * be signed.
81  */
82 #ifdef NEED_S_CHAR_TYPEDEF
83 # if SIZEOF_SIGNED_CHAR
84 typedef signed char s_char;
85 # else
86 typedef char s_char;
87 # endif
88   /* XXX: Why is this sequent bit INSIDE this test? */
89 # ifdef sequent
90 #  undef SO_RCVBUF
91 #  undef SO_SNDBUF
92 # endif
93 #endif
94 
95 /*
96  * NTP protocol parameters.  See section 3.2.6 of the specification.
97  */
98 #define   NTP_VERSION         ((u_char)4) /* current version number */
99 #define   NTP_OLDVERSION      ((u_char)1) /* oldest credible version */
100 #define   NTP_PORT  123       /* included for non-unix machines */
101 
102 /*
103  * Poll interval parameters
104  */
105 #define NTP_UNREACH 10        /* poll unreach threshold */
106 #define   NTP_MINPOLL         3         /* log2 min poll interval (8 s) */
107 #define NTP_MINDPOLL          6         /* log2 default min poll (64 s) */
108 #define NTP_MAXDPOLL          10        /* log2 default max poll (~17 m) */
109 #define   NTP_MAXPOLL         17        /* log2 max poll interval (~36 h) */
110 #define   NTP_RETRY 3         /* max packet retries */
111 #define   NTP_MINPKT          2         /* guard time (s) */
112 
113 /*
114  * Clock filter algorithm tuning parameters
115  */
116 #define MAXDISPERSE 16.       /* max dispersion */
117 #define   NTP_SHIFT 8         /* clock filter stages */
118 #define NTP_FWEIGHT .5        /* clock filter weight */
119 
120 /*
121  * Selection algorithm tuning parameters
122  */
123 #define   NTP_MINCLOCK        3         /* min survivors */
124 #define   NTP_MAXCLOCK        10        /* max candidates */
125 #define MINDISPERSE .001      /* min distance */
126 #define MAXDISTANCE 1.5       /* max root distance (select threshold) */
127 #define CLOCK_SGATE 3.        /* popcorn spike gate */
128 #define HUFFPUFF    900       /* huff-n'-puff sample interval (s) */
129 #define MAXHOP                2         /* anti-clockhop threshold */
130 #define MAX_TTL               8         /* max ttl mapping vector size */
131 #define   BEACON              7200      /* manycast beacon interval */
132 #define NTP_MAXEXTEN          2048      /* max extension field size */
133 #define   NTP_ORPHWAIT        300       /* orphan wait (s) */
134 
135 /*
136  * Miscellaneous stuff
137  */
138 #define NTP_MAXKEY  65535     /* max authentication key number */
139 
140 /*
141  * Limits of things
142  */
143 #define   MAXFILENAME         256       /* max length of file name */
144 #define MAXHOSTNAME 512       /* max length of host/node name */
145 #define NTP_MAXSTRLEN         256       /* max string length */
146 
147 /*
148  * Operations for jitter calculations (these use doubles).
149  *
150  * Note that we carefully separate the jitter component from the
151  * dispersion component (frequency error plus precision). The frequency
152  * error component is computed as CLOCK_PHI times the difference between
153  * the epoch of the time measurement and the reference time. The
154  * precision component is computed as the square root of the mean of the
155  * squares of a zero-mean, uniform distribution of unit maximum
156  * amplitude. Whether this makes statistical sense may be arguable.
157  */
158 #define SQUARE(x) ((x) * (x))
159 #define SQRT(x) (sqrt(x))
160 #define DIFF(x, y) (SQUARE((x) - (y)))
161 #define LOGTOD(a)   ldexp(1., (int)(a)) /* log2 to double */
162 #define UNIVAR(x)   (SQUARE(.28867513 * LOGTOD(x))) /* std uniform distr */
163 #define ULOGTOD(a)  ldexp(1., (int)(a)) /* ulog2 to double */
164 
165 #define   EVENT_TIMEOUT       0         /* one second, that is */
166 
167 
168 /*
169  * The interface structure is used to hold the addresses and socket
170  * numbers of each of the local network addresses we are using.
171  * Because "interface" is a reserved word in C++ and has so many
172  * varied meanings, a change to "endpt" (via typedef) is under way.
173  * Eventually the struct tag will change from interface to endpt_tag.
174  * endpt is unrelated to the select algorithm's struct endpoint.
175  */
176 typedef struct endpt_tag endpt;
177 struct endpt_tag {
178           endpt *             elink;              /* endpt list link */
179           endpt *             mclink;             /* per-AF_* multicast list */
180           void *              ioreg_ctx;          /* IO registration context */
181           SOCKET              fd;                 /* socket descriptor */
182           SOCKET              bfd;                /* for receiving broadcasts */
183           u_int32             ifnum;              /* endpt instance count */
184           sockaddr_u          sin;                /* unicast address */
185           sockaddr_u          mask;               /* subnet mask */
186           sockaddr_u          bcast;              /* broadcast address */
187           char                name[32]; /* name of interface */
188           u_short             family;             /* AF_INET/AF_INET6 */
189           u_short             phase;              /* phase in update cycle */
190           u_int32             flags;              /* INT_ flags */
191           int                 last_ttl; /* last TTL specified */
192           u_int32             addr_refid;         /* IPv4 addr or IPv6 hash */
193 #    ifdef WORDS_BIGENDIAN
194           u_int32             old_refid;          /* byte-swapped IPv6 refid */
195 #    endif
196           int                 num_mcast;          /* mcast addrs enabled */
197           u_long              starttime;          /* current_time at creation */
198           volatile long       received; /* number of incoming packets */
199           long                sent;               /* number of outgoing packets */
200           long                notsent;  /* number of send failures */
201           u_int               ifindex;  /* for IPV6_MULTICAST_IF */
202           isc_boolean_t       ignore_packets; /* listen-read-drop this? */
203           struct peer *       peers;              /* list of peers using endpt */
204           u_int               peercnt;  /* count of same */
205 };
206 
207 /*
208  * Flags for network endpoints (interfaces or really addresses)
209  */
210 #define INT_UP                0x001     /* Interface is up */
211 #define   INT_PPP             0x002     /* Point-to-point interface */
212 #define   INT_LOOPBACK        0x004     /* ::1 or 127.0.0.1 */
213 #define   INT_BROADCAST       0x008     /* can broadcast out this interface */
214 #define INT_MULTICAST         0x010     /* can multicast out this interface */
215 #define   INT_BCASTOPEN       0x020     /* broadcast receive socket is open */
216 #define INT_MCASTOPEN         0x040     /* multicasting enabled */
217 #define INT_WILDCARD          0x080     /* wildcard interface - usually skipped */
218 #define INT_MCASTIF 0x100     /* bound directly to MCAST address */
219 #define INT_PRIVACY 0x200     /* RFC 4941 IPv6 privacy address */
220 #define INT_BCASTXMIT         0x400     /* socket setup to allow broadcasts */
221 #define INT_LL_OF_GLOB        0x800     /* IPv6 link-local duplicate of global */
222 
223 /*
224  * Define flasher bits (tests 1 through 11 in packet procedure)
225  * These reveal the state at the last grumble from the peer and are
226  * most handy for diagnosing problems, even if not strictly a state
227  * variable in the spec. These are recorded in the peer structure.
228  *
229  * Packet errors
230  */
231 #define TEST1                 0X0001    /* duplicate packet */
232 #define TEST2                 0x0002    /* bogus packet */
233 #define TEST3                 0x0004    /* protocol unsynchronized */
234 #define TEST4                 0x0008    /* access denied */
235 #define TEST5                 0x0010    /* bad authentication */
236 #define TEST6                 0x0020    /* bad synch or stratum */
237 #define TEST7                 0x0040    /* bad header */
238 #define TEST8                 0x0080  /* bad autokey */
239 #define TEST9                 0x0100    /* bad crypto */
240 #define   PKT_TEST_MASK       (TEST1 | TEST2 | TEST3 | TEST4 | TEST5 |\
241                               TEST6 | TEST7 | TEST8 | TEST9)
242 /*
243  * Peer errors
244  */
245 #define TEST10                0x0200    /* peer bad synch or stratum */
246 #define   TEST11              0x0400    /* peer distance exceeded */
247 #define TEST12                0x0800    /* peer synchronization loop */
248 #define TEST13                0x1000    /* peer unreacable */
249 #define   PEER_TEST_MASK      (TEST10 | TEST11 | TEST12 | TEST13)
250 
251 /*
252  * Unused flags
253  */
254 #define TEST14                0x2000
255 #define TEST15                0x4000
256 #define TEST16                0x8000
257 
258 /*
259  * The peer structure. Holds state information relating to the guys
260  * we are peering with. Most of this stuff is from section 3.2 of the
261  * spec.
262  */
263 struct peer {
264           struct peer *p_link;          /* link pointer in free & peer lists */
265           struct peer *adr_link;        /* link pointer in address hash */
266           struct peer *aid_link;        /* link pointer in associd hash */
267           struct peer *ilink; /* list of peers for interface */
268           sockaddr_u srcadr;  /* address of remote host */
269           char *    hostname; /* if non-NULL, remote name */
270           struct addrinfo *addrs;       /* hostname query result */
271           struct addrinfo *ai;          /* position within addrs */
272           endpt *   dstadr;             /* local address */
273           associd_t associd;  /* association ID */
274           u_char    version;  /* version number */
275           u_char    hmode;              /* local association mode */
276           u_char    hpoll;              /* local poll interval */
277           u_char    minpoll;  /* min poll interval */
278           u_char    maxpoll;  /* max poll interval */
279           u_int     flags;              /* association flags */
280           u_char    cast_flags;         /* additional flags */
281           u_char    last_event;         /* last peer error code */
282           u_char    num_events;         /* number of error events */
283           u_int32   ttl;                /* ttl/refclock mode */
284           char      *ident;             /* group identifier name */
285 
286           /*
287            * Variables used by reference clock support
288            */
289 #ifdef REFCLOCK
290           struct refclockproc *procptr; /* refclock structure pointer */
291           u_char    refclktype;         /* reference clock type */
292           u_char    refclkunit;         /* reference clock unit number */
293           u_char    sstclktype;         /* clock type for system status word */
294 #endif /* REFCLOCK */
295 
296           /*
297            * Variables set by received packet
298            */
299           u_char    leap;               /* local leap indicator */
300           u_char    pmode;              /* remote association mode */
301           u_char    stratum;  /* remote stratum */
302           u_char    ppoll;              /* remote poll interval */
303           s_char    precision;          /* remote clock precision */
304           double    rootdelay;          /* roundtrip delay to primary source */
305           double    rootdisp; /* dispersion to primary source */
306           u_int32   refid;              /* remote reference ID */
307           l_fp      reftime;  /* update epoch */
308 
309           /*
310            * Variables used by authenticated client
311            */
312           keyid_t keyid;                /* current key ID */
313 #ifdef AUTOKEY
314 #define clear_to_zero opcode
315           u_int32   opcode;             /* last request opcode */
316           associd_t assoc;    /* peer association ID */
317           u_int32   crypto;             /* peer status word */
318           EVP_PKEY *pkey;               /* public key */
319           const EVP_MD *digest;         /* message digest algorithm */
320           char      *subject; /* certificate subject name */
321           char      *issuer;  /* certificate issuer name */
322           struct cert_info *xinfo; /* issuer certificate */
323           keyid_t   pkeyid;             /* previous key ID */
324           keyid_t   hcookie;  /* host cookie */
325           keyid_t   pcookie;  /* peer cookie */
326           const struct pkey_info *ident_pkey; /* identity key */
327           BIGNUM    *iffval;  /* identity challenge (IFF, GQ, MV) */
328           const BIGNUM *grpkey;         /* identity challenge key (GQ) */
329           struct value cookval;         /* receive cookie values */
330           struct value recval;          /* receive autokey values */
331           struct exten *cmmd; /* extension pointer */
332           u_long    refresh;  /* next refresh epoch */
333 
334           /*
335            * Variables used by authenticated server
336            */
337           keyid_t   *keylist; /* session key ID list */
338           int       keynumber;          /* current key number */
339           struct value encrypt;         /* send encrypt values */
340           struct value sndval;          /* send autokey values */
341 #else     /* !AUTOKEY follows */
342 #define clear_to_zero status
343 #endif    /* !AUTOKEY */
344 
345           /*
346            * Ephemeral state variables
347            */
348           u_char    status;             /* peer status */
349           u_char    new_status;         /* under-construction status */
350           u_char    reach;              /* reachability register */
351           u_char    filter_nextpt;      /* index into filter shift register */
352           int       flash;              /* protocol error test tally bits */
353           u_long    epoch;              /* reference epoch */
354           int       burst;              /* packets remaining in burst */
355           int       retry;              /* retry counter */
356           int       flip;               /* interleave mode control */
357           double    filter_delay[NTP_SHIFT]; /* delay shift register */
358           double    filter_offset[NTP_SHIFT]; /* offset shift register */
359           double    filter_disp[NTP_SHIFT]; /* dispersion shift register */
360           u_long    filter_epoch[NTP_SHIFT]; /* epoch shift register */
361           u_char    filter_order[NTP_SHIFT]; /* filter sort index */
362           l_fp      rec;                /* receive time stamp */
363           l_fp      xmt;                /* transmit time stamp */
364           l_fp      dst;                /* destination timestamp */
365           l_fp      aorg;               /* origin timestamp */
366           l_fp      borg;               /* alternate origin timestamp */
367           l_fp      bxmt;               /* most recent broadcast transmit timestamp */
368           l_fp      nonce;              /* Value of nonce we sent as the xmt stamp */
369           double    offset;             /* peer clock offset */
370           double    delay;              /* peer roundtrip delay */
371           double    jitter;             /* peer jitter (squares) */
372           double    disp;               /* peer dispersion */
373           double    xleave;             /* interleave delay */
374           double    bias;               /* programmed offset bias */
375 
376           /*
377            * Variables used to correct for packet length and asymmetry.
378            */
379           double    t21;                /* outbound packet delay */
380           int       t21_bytes;          /* outbound packet length */
381           int       t21_last; /* last outbound packet length */
382           double    r21;                /* outbound data rate */
383           double    t34;                /* inbound packet delay */
384           int       t34_bytes;          /* inbound packet length */
385           double    r34;                /* inbound data rate */
386 
387           /*
388            * End of clear-to-zero area
389            */
390           u_long    update;             /* receive epoch */
391 #define end_clear_to_zero update
392           int       unreach;  /* watchdog counter */
393           int       throttle; /* rate control */
394           u_long    outdate;  /* send time last packet */
395           u_long    nextdate; /* send time next packet */
396 
397           /*
398            * Statistic counters
399            */
400           u_long    timereset;          /* time stat counters were reset */
401           u_long    timelastrec;        /* last packet received time, incl. trash */
402           u_long    timereceived;       /* last (clean) packet received time */
403           u_long    timereachable;      /* last reachable/unreachable time */
404 
405           u_long    sent;               /* packets sent */
406           u_long    received; /* packets received */
407           u_long    processed;          /* packets processed */
408           u_long    badauth;  /* bad authentication (TEST5) */
409           u_long    badNAK;             /* invalid crypto-NAK */
410           u_long    bogusorg; /* bogus origin (TEST2, TEST3) */
411           u_long    oldpkt;             /* old duplicate (TEST1) */
412           u_long    seldisptoolarge; /* bad header (TEST6, TEST7) */
413           u_long    selbroken;          /* KoD received */
414 };
415 
416 /*
417  * Values for peer.leap, sys_leap
418  */
419 #define   LEAP_NOWARNING      0x0       /* normal, no leap second warning */
420 #define   LEAP_ADDSECOND      0x1       /* last minute of day has 61 seconds */
421 #define   LEAP_DELSECOND      0x2       /* last minute of day has 59 seconds */
422 #define   LEAP_NOTINSYNC      0x3       /* overload, clock is free running */
423 
424 /*
425  * Values for peer mode and packet mode. Only the modes through
426  * MODE_BROADCAST and MODE_BCLIENT appear in the transition
427  * function. MODE_CONTROL and MODE_PRIVATE can appear in packets,
428  * but those never survive to the transition function.
429  */
430 #define   MODE_UNSPEC         0         /* unspecified (old version) */
431 #define   MODE_ACTIVE         1         /* symmetric active mode */
432 #define   MODE_PASSIVE        2         /* symmetric passive mode */
433 #define   MODE_CLIENT         3         /* client mode */
434 #define   MODE_SERVER         4         /* server mode */
435 #define   MODE_BROADCAST      5         /* broadcast mode */
436 /*
437  * These can appear in packets
438  */
439 #define   MODE_CONTROL        6         /* control mode */
440 #define   MODE_PRIVATE        7         /* private mode */
441 /*
442  * This is a made-up mode for broadcast client.
443  */
444 #define   MODE_BCLIENT        6         /* broadcast client mode */
445 
446 /*
447  * Values for peer.stratum, sys_stratum
448  */
449 #define   STRATUM_REFCLOCK ((u_char)0) /* default stratum */
450 /* A stratum of 0 in the packet is mapped to 16 internally */
451 #define   STRATUM_PKT_UNSPEC ((u_char)0) /* unspecified in packet */
452 #define   STRATUM_UNSPEC      ((u_char)16) /* unspecified */
453 
454 /*
455  * Values for peer.flags (u_int)
456  */
457 #define   FLAG_CONFIG         0x0001    /* association was configured */
458 #define   FLAG_PREEMPT        0x0002    /* preemptable association */
459 #define   FLAG_AUTHENTIC      0x0004    /* last message was authentic */
460 #define   FLAG_REFCLOCK       0x0008    /* this is actually a reference clock */
461 #define   FLAG_BC_VOL         0x0010    /* broadcast client volleying */
462 #define   FLAG_PREFER         0x0020    /* prefer peer */
463 #define   FLAG_BURST          0x0040    /* burst mode */
464 #define   FLAG_PPS  0x0080    /* steered by PPS */
465 #define   FLAG_IBURST         0x0100    /* initial burst mode */
466 #define   FLAG_NOSELECT       0x0200    /* never select */
467 #define   FLAG_TRUE 0x0400    /* force truechimer */
468 #define   FLAG_SKEY 0x0800  /* autokey authentication */
469 #define   FLAG_XLEAVE         0x1000    /* interleaved protocol */
470 #define   FLAG_XB             0x2000    /* interleaved broadcast */
471 #define   FLAG_XBOGUS         0x4000    /* interleaved bogus packet */
472 #ifdef    AUTOKEY
473 # define FLAG_ASSOC 0x8000    /* autokey request */
474 #endif
475 #define FLAG_TSTAMP_PPS       0x10000   /* PPS source provides absolute timestamp */
476 #define FLAG_LOOPNONCE        0x20000   /* Use a nonce for the loopback test */
477 #define FLAG_DISABLED         0x40000   /* peer is being torn down */
478 
479 /*
480  * Definitions for the clear() routine.  We use memset() to clear
481  * the parts of the peer structure which go to zero.  These are
482  * used to calculate the start address and length of the area.
483  */
484 #define   CLEAR_TO_ZERO(p)    ((char *)&((p)->clear_to_zero))
485 #define   END_CLEAR_TO_ZERO(p)          ((char *)&((p)->end_clear_to_zero))
486 #define   LEN_CLEAR_TO_ZERO(p)          (END_CLEAR_TO_ZERO(p) - CLEAR_TO_ZERO(p))
487 #define CRYPTO_TO_ZERO(p)     ((char *)&((p)->clear_to_zero))
488 #define END_CRYPTO_TO_ZERO(p) ((char *)&((p)->end_clear_to_zero))
489 #define LEN_CRYPTO_TO_ZERO    (END_CRYPTO_TO_ZERO((struct peer *)0) \
490                                             - CRYPTO_TO_ZERO((struct peer *)0))
491 
492 /*
493  * Reference clock types.  Added as necessary.
494  */
495 #define   REFCLK_NONE                   0         /* unknown or missing */
496 #define   REFCLK_LOCALCLOCK   1         /* external (e.g., lockclock) */
497 #define   REFCLK_GPS_TRAK               2         /* TRAK 8810 GPS Receiver */
498 #define   REFCLK_WWV_PST                3         /* PST/Traconex 1020 WWV/H */
499 #define   REFCLK_SPECTRACOM   4         /* Spectracom (generic) Receivers */
500 #define   REFCLK_TRUETIME               5         /* TrueTime (generic) Receivers */
501 #define REFCLK_IRIG_AUDIO     6         /* IRIG-B/W audio decoder */
502 #define   REFCLK_CHU_AUDIO    7         /* CHU audio demodulator/decoder */
503 #define REFCLK_PARSE                    8         /* generic driver (usually DCF77,GPS,MSF) */
504 #define   REFCLK_GPS_MX4200   9         /* Magnavox MX4200 GPS */
505 #define REFCLK_GPS_AS2201     10        /* Austron 2201A GPS */
506 #define   REFCLK_GPS_ARBITER  11        /* Arbiter 1088A/B/ GPS */
507 #define REFCLK_IRIG_TPRO      12        /* KSI/Odetics TPRO-S IRIG */
508 #define REFCLK_ATOM_LEITCH    13        /* Leitch CSD 5300 Master Clock */
509 #define REFCLK_MSF_EES                  14        /* EES M201 MSF Receiver */
510 #define   REFCLK_GPSTM_TRUE   15        /* OLD TrueTime GPS/TM-TMD Receiver */
511 #define REFCLK_IRIG_BANCOMM   16        /* Bancomm GPS/IRIG Interface */
512 #define REFCLK_GPS_DATUM      17        /* Datum Programmable Time System */
513 #define REFCLK_ACTS           18        /* Generic Auto Computer Time Service */
514 #define REFCLK_WWV_HEATH      19        /* Heath GC1000 WWV/WWVH Receiver */
515 #define REFCLK_GPS_NMEA                 20        /* NMEA based GPS clock */
516 #define REFCLK_GPS_VME                  21        /* TrueTime GPS-VME Interface */
517 #define REFCLK_ATOM_PPS                 22        /* 1-PPS Clock Discipline */
518 #define REFCLK_PTB_ACTS                 23        /* replaced by REFCLK_ACTS */
519 #define REFCLK_USNO           24        /* replaced by REFCLK_ACTS */
520 #define REFCLK_GPS_HP                   26        /* HP 58503A Time/Frequency Receiver */
521 #define REFCLK_ARCRON_MSF     27        /* ARCRON MSF radio clock. */
522 #define REFCLK_SHM            28        /* clock attached thru shared memory */
523 #define REFCLK_PALISADE                 29        /* Trimble Navigation Palisade GPS */
524 #define REFCLK_ONCORE                   30        /* Motorola UT Oncore GPS */
525 #define REFCLK_GPS_JUPITER    31        /* Rockwell Jupiter GPS receiver */
526 #define REFCLK_CHRONOLOG      32        /* Chrono-log K WWVB receiver */
527 #define REFCLK_DUMBCLOCK      33        /* Dumb localtime clock */
528 #define REFCLK_ULINK                    34        /* Ultralink M320 WWVB receiver */
529 #define REFCLK_PCF            35        /* Conrad parallel port radio clock */
530 #define REFCLK_WWV_AUDIO      36        /* WWV/H audio demodulator/decoder */
531 #define REFCLK_FG             37        /* Forum Graphic GPS */
532 #define REFCLK_HOPF_SERIAL    38        /* hopf DCF77/GPS serial receiver  */
533 #define REFCLK_HOPF_PCI                 39        /* hopf DCF77/GPS PCI receiver  */
534 #define REFCLK_JJY            40        /* JJY receiver  */
535 #define   REFCLK_TT560                  41        /* TrueTime 560 IRIG-B decoder */
536 #define REFCLK_ZYFER                    42        /* Zyfer GPStarplus receiver  */
537 #define REFCLK_RIPENCC                  43        /* RIPE NCC Trimble driver */
538 #define REFCLK_NEOCLOCK4X     44        /* NeoClock4X DCF77 or TDF receiver */
539 #define REFCLK_TSYNCPCI                 45        /* Spectracom TSYNC PCI timing board */
540 #define REFCLK_GPSDJSON                 46
541 #define REFCLK_MAX            46
542 
543 
544 /*
545  * NTP packet format.  The mac field is optional.  It isn't really
546  * an l_fp either, but for now declaring it that way is convenient.
547  * See Appendix A in the specification.
548  *
549  * Note that all u_fp and l_fp values arrive in network byte order
550  * and must be converted (except the mac, which isn't, really).
551  */
552 struct pkt {
553           u_char    li_vn_mode;         /* peer leap indicator */
554           u_char    stratum;  /* peer stratum */
555           u_char    ppoll;              /* peer poll interval */
556           s_char    precision;          /* peer clock precision */
557           u_fp      rootdelay;          /* roundtrip delay to primary source */
558           u_fp      rootdisp; /* dispersion to primary source*/
559           u_int32   refid;              /* reference id */
560           l_fp      reftime;  /* last update time */
561           l_fp      org;                /* originate time stamp */
562           l_fp      rec;                /* receive time stamp */
563           l_fp      xmt;                /* transmit time stamp */
564 
565 #define   MIN_V4_PKT_LEN      (12 * sizeof(u_int32))        /* min header length */
566 #define   LEN_PKT_NOMAC       (12 * sizeof(u_int32))        /* min header length */
567 #define   MIN_MAC_LEN         (1 * sizeof(u_int32))         /* crypto_NAK */
568 #define   MD5_LENGTH          16
569 #define   SHAKE128_LENGTH     16
570 #define   CMAC_LENGTH         16
571 #define   SHA1_LENGTH         20
572 #define   KEY_MAC_LEN         sizeof(u_int32)               /* key ID in MAC */
573 #define   MAX_MD5_LEN         (KEY_MAC_LEN + MD5_LENGTH)
574 #define   MAX_SHAKE128_LEN (KEY_MAC_LEN + SHAKE128_LENGTH)
575 #define   MAX_SHA1_LEN        (KEY_MAC_LEN + SHA1_LENGTH)
576 #define   MAX_MAC_LEN         (6 * sizeof(u_int32))         /* any MAC */
577 #define   MAX_MDG_LEN         (MAX_MAC_LEN-KEY_MAC_LEN) /* max. digest len */
578 
579           /*
580            * The length of the packet less MAC must be a multiple of 64
581            * with an RSA modulus and Diffie-Hellman prime of 256 octets
582            * and maximum host name of 128 octets, the maximum autokey
583            * command is 152 octets and maximum autokey response is 460
584            * octets. A packet can contain no more than one command and one
585            * response, so the maximum total extension field length is 864
586            * octets. But, to handle humungus certificates, the bank must
587            * be broke.
588            *
589            * The different definitions of the 'exten' field are here for
590            * the benefit of applications that want to send a packet from
591            * an auto variable in the stack - not using the AUTOKEY version
592            * saves 2KB of stack space. The receive buffer should ALWAYS be
593            * big enough to hold a full extended packet if the extension
594            * fields have to be parsed or skipped.
595            */
596 #ifdef AUTOKEY
597           u_int32   exten[(NTP_MAXEXTEN + MAX_MAC_LEN) / sizeof(u_int32)];
598 #else     /* !AUTOKEY follows */
599           u_int32   exten[(MAX_MAC_LEN) / sizeof(u_int32)];
600 #endif    /* !AUTOKEY */
601 };
602 
603 /*
604  * Stuff for extracting things from li_vn_mode
605  */
606 #define   PKT_MODE(li_vn_mode)          ((u_char)((li_vn_mode) & 0x7))
607 #define   PKT_VERSION(li_vn_mode)       ((u_char)(((li_vn_mode) >> 3) & 0x7))
608 #define   PKT_LEAP(li_vn_mode)          ((u_char)(((li_vn_mode) >> 6) & 0x3))
609 
610 /*
611  * Stuff for putting things back into li_vn_mode in packets and vn_mode
612  * in ntp_monitor.c's mon_entry.
613  */
614 #define VN_MODE(v, m)                   ((((v) & 7) << 3) | ((m) & 0x7))
615 #define   PKT_LI_VN_MODE(l, v, m) ((((l) & 3) << 6) | VN_MODE((v), (m)))
616 
617 
618 /*
619  * Dealing with stratum.  0 gets mapped to 16 incoming, and back to 0
620  * on output.
621  */
622 #define   PKT_TO_STRATUM(s)   ((u_char)(((s) == (STRATUM_PKT_UNSPEC)) ?\
623                                         (STRATUM_UNSPEC) : (s)))
624 
625 #define   STRATUM_TO_PKT(s)   ((u_char)(((s) == (STRATUM_UNSPEC)) ?\
626                                         (STRATUM_PKT_UNSPEC) : (s)))
627 
628 
629 /*
630  * A test to determine if the refid should be interpreted as text string.
631  * This is usually the case for a refclock, which has stratum 0 internally,
632  * which results in sys_stratum 1 if the refclock becomes system peer, or
633  * in case of a kiss-of-death (KoD) packet that has STRATUM_PKT_UNSPEC (==0)
634  * in the packet which is converted to STRATUM_UNSPEC when the packet
635  * is evaluated.
636  */
637 #define REFID_ISTEXT(s) (((s) <= 1) || ((s) >= STRATUM_UNSPEC))
638 
639 
640 /*
641  * Event codes. Used for reporting errors/events to the control module
642  */
643 #define   PEER_EVENT          0x080     /* this is a peer event */
644 #define CRPT_EVENT  0x100     /* this is a crypto event */
645 
646 /*
647  * System event codes
648  */
649 #define   EVNT_UNSPEC         0         /* unspecified */
650 #define   EVNT_NSET 1         /* freq not set */
651 #define   EVNT_FSET 2         /* freq set */
652 #define   EVNT_SPIK 3         /* spike detect */
653 #define   EVNT_FREQ 4         /* freq mode */
654 #define   EVNT_SYNC 5         /* clock sync */
655 #define   EVNT_SYSRESTART     6         /* restart */
656 #define   EVNT_SYSFAULT       7         /* panic stop */
657 #define   EVNT_NOPEER         8         /* no sys peer */
658 #define   EVNT_ARMED          9         /* leap armed */
659 #define   EVNT_DISARMED       10        /* leap disarmed */
660 #define   EVNT_LEAP 11        /* leap event */
661 #define   EVNT_CLOCKRESET     12        /* clock step */
662 #define   EVNT_KERN 13        /* kernel event */
663 #define   EVNT_TAI  14        /* TAI */
664 #define   EVNT_LEAPVAL        15        /* stale leapsecond values */
665 
666 /*
667  * Peer event codes
668  */
669 #define   PEVNT_MOBIL         (1 | PEER_EVENT) /* mobilize */
670 #define   PEVNT_DEMOBIL       (2 | PEER_EVENT) /* demobilize */
671 #define   PEVNT_UNREACH       (3 | PEER_EVENT) /* unreachable */
672 #define   PEVNT_REACH         (4 | PEER_EVENT) /* reachable */
673 #define   PEVNT_RESTART       (5 | PEER_EVENT) /* restart */
674 #define   PEVNT_REPLY         (6 | PEER_EVENT) /* no reply */
675 #define   PEVNT_RATE          (7 | PEER_EVENT) /* rate exceeded */
676 #define   PEVNT_DENY          (8 | PEER_EVENT) /* access denied */
677 #define PEVNT_ARMED (9 | PEER_EVENT) /* leap armed */
678 #define   PEVNT_NEWPEER       (10 | PEER_EVENT) /* sys peer */
679 #define   PEVNT_CLOCK         (11 | PEER_EVENT) /* clock event */
680 #define   PEVNT_AUTH          (12 | PEER_EVENT) /* bad auth */
681 #define   PEVNT_POPCORN       (13 | PEER_EVENT) /* popcorn */
682 #define   PEVNT_XLEAVE        (14 | PEER_EVENT) /* interleave mode */
683 #define   PEVNT_XERR          (15 | PEER_EVENT) /* interleave error */
684 
685 /*
686  * Clock event codes
687  */
688 #define   CEVNT_NOMINAL       0         /* unspecified */
689 #define   CEVNT_TIMEOUT       1         /* no reply */
690 #define   CEVNT_BADREPLY      2         /* bad format */
691 #define   CEVNT_FAULT         3         /* fault */
692 #define   CEVNT_PROP          4         /* bad signal */
693 #define   CEVNT_BADDATE       5         /* bad date */
694 #define   CEVNT_BADTIME       6         /* bad time */
695 #define CEVNT_MAX   CEVNT_BADTIME
696 
697 /*
698  * Very misplaced value.  Default port through which we send traps.
699  */
700 #define   TRAPPORT  18447
701 
702 
703 /*
704  * To speed lookups, peers are hashed by the low order bits of the
705  * remote IP address. These definitions relate to that.
706  */
707 #define   NTP_HASH_SIZE                 128
708 #define   NTP_HASH_MASK                 (NTP_HASH_SIZE-1)
709 #define   NTP_HASH_ADDR(src)  (sock_hash(src) & NTP_HASH_MASK)
710 
711 /*
712  * min, min3 and max.  Makes it easier to transliterate the spec without
713  * thinking about it.
714  */
715 #define   min(a,b)  (((a) < (b)) ? (a) : (b))
716 #define   max(a,b)  (((a) > (b)) ? (a) : (b))
717 #define   min3(a,b,c)         min(min((a),(b)), (c))
718 
719 /* clamp a value within a range */
720 #define CLAMP(val, minval, maxval)                                    \
721                               max((minval), min((val), (maxval)))
722 
723 
724 /*
725  * Configuration items.  These are for the protocol module (proto_config())
726  */
727 #define   PROTO_BROADCLIENT   1
728 #define   PROTO_PRECISION               2         /* (not used) */
729 #define   PROTO_AUTHENTICATE  3
730 #define   PROTO_BROADDELAY    4
731 #define   PROTO_AUTHDELAY               5         /* (not used) */
732 #define PROTO_MULTICAST_ADD   6
733 #define PROTO_MULTICAST_DEL   7
734 #define PROTO_NTP             8
735 #define PROTO_KERNEL                    9
736 #define PROTO_MONITOR                   10
737 #define PROTO_FILEGEN                   11
738 #define   PROTO_PPS           12
739 #define PROTO_CAL             13
740 #define PROTO_MINCLOCK                  14
741 #define   PROTO_MAXCLOCK                15
742 #define PROTO_MINSANE                   16
743 #define PROTO_FLOOR           17
744 #define PROTO_CEILING                   18
745 #define PROTO_COHORT                    19
746 #define PROTO_CALLDELAY                 20
747 #define PROTO_MINDISP                   21
748 #define PROTO_MAXDIST                   22
749           /* available                  23 */
750 #define   PROTO_MAXHOP                  24
751 #define   PROTO_BEACON                  25
752 #define   PROTO_ORPHAN                  26
753 #define   PROTO_ORPHWAIT                27
754 #define   PROTO_MODE7                   28
755 #define   PROTO_UECRYPTO                29
756 #define   PROTO_UECRYPTONAK   30
757 #define   PROTO_UEDIGEST                31
758 #define   PROTO_PCEDIGEST               32
759 #define   PROTO_BCPOLLBSTEP   33
760 
761 /*
762  * Configuration items for the loop filter
763  */
764 #define   LOOP_DRIFTINIT                1         /* iniitialize frequency */
765 #define   LOOP_KERN_CLEAR               2         /* set initial frequency offset */
766 #define LOOP_MAX              3         /* set both step offsets */
767 #define LOOP_MAX_BACK                   4         /* set backward-step offset */
768 #define LOOP_MAX_FWD                    5         /* set forward-step offset */
769 #define LOOP_PANIC            6         /* set panic offseet */
770 #define LOOP_PHI              7         /* set dispersion rate */
771 #define LOOP_MINSTEP                    8         /* set step timeout */
772 #define LOOP_MINPOLL                    9         /* set min poll interval (log2 s) */
773 #define LOOP_ALLAN            10        /* set minimum Allan intercept */
774 #define LOOP_HUFFPUFF                   11        /* set huff-n'-puff filter length */
775 #define LOOP_FREQ             12        /* set initial frequency */
776 #define LOOP_CODEC            13        /* set audio codec frequency */
777 #define   LOOP_LEAP           14        /* insert leap after second 23:59 */
778 #define   LOOP_TICK           15        /* sim. low precision clock */
779 #define LOOP_NOFREQ           16        /* undo a previos LOOP_FREQ */
780 
781 /*
782  * Configuration items for the stats printer
783  */
784 #define   STATS_FREQ_FILE               1         /* configure drift file */
785 #define STATS_STATSDIR                  2         /* directory prefix for stats files */
786 #define   STATS_PID_FILE                3         /* configure ntpd PID file */
787 #define   STATS_LEAP_FILE               4         /* configure ntpd leapseconds file */
788 
789 #define MJD_1900              15020     /* MJD for 1 Jan 1900 */
790 
791 /*
792  * Default parameters.  We use these in the absence of something better.
793  */
794 #define INADDR_NTP  0xe0000101          /* NTP multicast address 224.0.1.1 */
795 
796 /*
797  * Structure used optionally for monitoring when this is turned on.
798  */
799 typedef struct mon_data       mon_entry;
800 struct mon_data {
801           mon_entry *         hash_next;          /* next structure in hash list */
802           DECL_DLIST_LINK(mon_entry, mru);/* MRU list link pointers */
803           endpt *             lcladr;   /* address on which this arrived */
804           l_fp                first;              /* first time seen */
805           l_fp                last;               /* last time seen */
806           int                 leak;               /* leaky bucket accumulator */
807           int                 count;              /* total packet count */
808           u_short             flags;              /* restrict flags */
809           u_char              vn_mode;  /* packet mode & version */
810           u_char              cast_flags;         /* flags MDF_?CAST */
811           sockaddr_u          rmtadr;             /* address of remote host */
812 };
813 
814 /*
815  * Values for cast_flags in mon_entry and struct peer.  mon_entry uses
816  * only the first three, MDF_UCAST, MDF_MCAST, and MDF_BCAST.
817  */
818 #define   MDF_UCAST 0x01      /* unicast client */
819 #define   MDF_MCAST 0x02      /* multicast server */
820 #define   MDF_BCAST 0x04      /* broadcast server */
821 #define   MDF_POOL  0x08      /* pool client solicitor */
822 #define MDF_ACAST   0x10      /* manycast client solicitor */
823 #define   MDF_BCLNT 0x20      /* eph. broadcast/multicast client */
824 #define MDF_PCLNT   0x40      /* preemptible pool client */
825 /*
826  * In the context of struct peer in ntpd, three of the cast_flags bits
827  * represent configured associations which never receive packets, and
828  * whose reach is always 0: MDF_BCAST, MDF_MCAST, and MDF_ACAST.  The
829  * last can be argued as responses are received, but those responses do
830  * not affect the MDF_ACAST association's reach register, rather they
831  * (may) result in mobilizing ephemeral MDF_ACLNT associations.
832  */
833 #define MDF_TXONLY_MASK       (MDF_BCAST | MDF_MCAST | MDF_ACAST | MDF_POOL)
834 /*
835  * manycastclient-like solicitor association cast_flags bits
836  */
837 #define MDF_SOLICIT_MASK      (MDF_ACAST | MDF_POOL)
838 /*
839  * Values used with mon_enabled to indicate reason for enabling monitoring
840  */
841 #define MON_OFF               0x00                /* no monitoring */
842 #define MON_ON                0x01                /* monitoring explicitly enabled */
843 #define MON_RES               0x02                /* implicit monitoring for RES_LIMITED */
844 /*
845  * Structure used for restrictlist entries
846  */
847 typedef struct res_addr4_tag {
848           u_int32             addr;               /* IPv4 addr (host order) */
849           u_int32             mask;               /* IPv4 mask (host order) */
850 } res_addr4;
851 
852 typedef struct res_addr6_tag {
853           struct in6_addr addr;                   /* IPv6 addr (net order) */
854           struct in6_addr mask;                   /* IPv6 mask (net order) */
855 } res_addr6;
856 
857 struct restrict_info {
858           u_int32             count;              /* number of packets matched */
859           u_int32             expire;             /* valid until current_time */
860           u_int32             mflags;             /* match flags */
861           u_short             rflags;             /* restrict (accesslist) flags */
862           short               ippeerlimit;        /* limit of associations matching */
863 };
864 
865 struct restrict_4 {
866           struct restrict_4 *link;      /* link to next entry */
867           struct restrict_info ri;
868           res_addr4 v4;
869 };
870 
871 struct restrict_6 {
872           struct restrict_6 *link;      /* link to next entry */
873           struct restrict_info ri;
874           res_addr6 v6;
875 };
876 
877 /* restrictions for (4) a given address */
878 typedef struct r4addr_tag     r4addr;
879 struct r4addr_tag {
880           u_short             rflags;             /* match flags */
881           short               ippeerlimit;        /* IP peer limit */
882 };
883 
884 /*
885  * Restrict (Access) flags (rflags)
886  */
887 #define   RES_IGNORE                    0x0001    /* ignore packet */
888 #define   RES_DONTSERVE                 0x0002    /* access denied */
889 #define   RES_DONTTRUST                 0x0004    /* authentication required */
890 #define   RES_VERSION                   0x0008    /* version mismatch */
891 #define   RES_NOPEER                    0x0010    /* new association denied */
892 #define   RES_NOEPEER                   0x0020    /* new ephemeral association denied */
893 #define RES_LIMITED           0x0040    /* packet rate exceeded */
894 #define   RES_NOQUERY                   0x0080    /* mode 6/7 packet denied */
895 #define   RES_NOMODIFY                  0x0100    /* mode 6/7 modify denied */
896 #define   RES_NOTRAP                    0x0200    /* mode 6/7 set trap denied */
897 #define   RES_LPTRAP                    0x0400    /* mode 6/7 low priority trap */
898 
899 #define   RES_KOD                       0x0800    /* send kiss of death packet */
900 #define   RES_MSSNTP                    0x1000    /* enable MS-SNTP authentication */
901 #define   RES_FLAKE           0x2000    /* flakeway - drop 10% */
902 #define   RES_NOMRULIST                 0x4000    /* mode 6 mrulist denied */
903 
904 #define   RES_SRVRSPFUZ                 0x8000    /* Server response: fuzz */
905 
906 #define RES_UNUSED            0x0000    /* Unused flag bits (none left) */
907 
908 #define   RES_ALLFLAGS                  (RES_IGNORE | RES_DONTSERVE | \
909                                          RES_DONTTRUST | RES_VERSION |          \
910                                          RES_NOPEER | RES_NOEPEER |   \
911                                          RES_LIMITED | RES_NOQUERY |  \
912                                          RES_NOMODIFY | RES_NOTRAP |  \
913                                          RES_LPTRAP | RES_KOD |                 \
914                                          RES_MSSNTP | RES_FLAKE |     \
915                                          RES_NOMRULIST | RES_SRVRSPFUZ )
916 
917 /*
918  * Match flags (mflags)
919  */
920 #define   RESM_INTERFACE                0x1000    /* this is an interface */
921 #define   RESM_NTPONLY                  0x2000    /* match source port 123 */
922 #define RESM_SOURCE           0x4000    /* from "restrict source" */
923 
924 /*
925  * Restriction configuration ops
926  */
927 typedef enum
928 restrict_ops {
929           RESTRICT_FLAGS = 1, /* add rflags to restrict entry */
930           RESTRICT_UNFLAG,    /* remove rflags from restrict entry */
931           RESTRICT_REMOVE,    /* remove a restrict entry */
932           RESTRICT_REMOVEIF,  /* remove an interface restrict entry */
933 } restrict_op;
934 
935 /*
936  * Endpoint structure for the select algorithm
937  */
938 struct endpoint {
939           double    val;                          /* offset of endpoint */
940           int       type;                         /* interval entry/exit */
941 };
942 
943 /*
944  * Association matching AM[] return codes
945  */
946 #define AM_ERR                -1                  /* error */
947 #define AM_NOMATCH  0                   /* no match */
948 #define AM_PROCPKT  1                   /* server/symmetric packet */
949 #define AM_BCST               2                   /* broadcast packet */
950 #define AM_FXMIT    3                   /* client packet */
951 #define AM_MANYCAST 4                   /* manycast or pool */
952 #define AM_NEWPASS  5                   /* new passive */
953 #define AM_NEWBCL   6                   /* new broadcast */
954 #define AM_POSSBCL  7                   /* discard broadcast */
955 
956 /* NetInfo configuration locations */
957 #ifdef HAVE_NETINFO
958 #define NETINFO_CONFIG_DIR "/config/ntp"
959 #endif
960 
961 /* ntpq -c mrulist rows per request limit in ntpd */
962 #define MRU_ROW_LIMIT         256
963 /* similar datagrams per response limit for ntpd */
964 #define MRU_FRAGS_LIMIT       128
965 
966 /* found on POSIX systems in sysexit.h */
967 #ifndef EX_SOFTWARE
968 # define EX_SOFTWARE          70        /* internal software error */
969 #endif
970 
971 #define BYTESWAP32(u32)                                                                   \
972                               (((u_int32)(u32) & 0xff000000) >> 24 |            \
973                                ((u_int32)(u32) &   0xff0000) >>  8 |            \
974                                ((u_int32)(u32) &     0xff00) <<  8 |            \
975                                ((u_int32)(u32) &       0xff) << 24)
976 #endif /* NTP_H */
977