Fix a serious bug in the NTPD loopfilter. Basically what happens is that
[dragonfly.git] / contrib / ntp / include / ntp.h
1 /*
2  * ntp.h - NTP definitions for the masses
3  */
4
5 #ifndef NTP_H
6 #define NTP_H
7
8 #include "ntp_types.h"
9 #include <math.h>
10
11 /*
12  * Calendar arithmetic - contributed by G. Healton
13  */
14 #define YEAR_BREAK 500          /* years < this are tm_year values:
15                                  * Break < AnyFourDigitYear && Break >
16                                  * Anytm_yearYear */
17
18 #define YEAR_PIVOT 98           /* 97/98: years < this are year 2000+
19                                  * FYI: official UNIX pivot year is
20                                  * 68/69 */
21
22 /*
23  * Number of Days since 1 BC Gregorian to 1 January of given year
24  */
25 #define julian0(year)   (((year) * 365 ) + ((year) > 0 ? (((year) + 3) \
26                             / 4 - ((year - 1) / 100) + ((year - 1) / \
27                             400)) : 0))
28
29 /*
30  * Number of days since start of NTP time to 1 January of given year
31  */
32 #define ntp0(year)      (julian0(year) - julian0(1900))
33
34 /*
35  * Number of days since start of UNIX time to 1 January of given year
36  */
37 #define unix0(year)     (julian0(year) - julian0(1970))
38
39 /*
40  * LEAP YEAR test for full 4-digit years (e.g, 1999, 2010)
41  */
42 #define isleap_4(y)     ((y) % 4 == 0 && !((y) % 100 == 0 && !(y % \
43                             400 == 0)))
44
45 /*
46  * LEAP YEAR test for tm_year (struct tm) years (e.g, 99, 110)
47  */
48 #define isleap_tm(y)    ((y) % 4 == 0 && !((y) % 100 == 0 && !(((y) \
49                             + 1900) % 400 == 0)))
50
51 /*
52  * to convert simple two-digit years to tm_year style years:
53  *
54  *      if (year < YEAR_PIVOT)
55  *              year += 100;
56  *
57  * to convert either two-digit OR tm_year years to four-digit years:
58  *
59  *      if (year < YEAR_PIVOT)
60  *              year += 100;
61  *
62  *      if (year < YEAR_BREAK)
63  *              year += 1900;
64  */
65
66 /*
67  * How to get signed characters.  On machines where signed char works,
68  * use it. On machines where signed char doesn't work, char had better
69  * be signed.
70  */
71 #ifdef NEED_S_CHAR_TYPEDEF
72 # if SIZEOF_SIGNED_CHAR
73 typedef signed char s_char;
74 # else
75 typedef char s_char;
76 # endif
77   /* XXX: Why is this sequent bit INSIDE this test? */
78 # ifdef sequent
79 #  undef SO_RCVBUF
80 #  undef SO_SNDBUF
81 # endif
82 #endif
83 #ifndef TRUE
84 # define TRUE 1
85 #endif /* TRUE */
86 #ifndef FALSE
87 # define FALSE 0
88 #endif /* FALSE */
89
90 /*
91  * NTP protocol parameters.  See section 3.2.6 of the specification.
92  */
93 #define NTP_VERSION     ((u_char)4) /* current version number */
94 #define NTP_OLDVERSION  ((u_char)1) /* oldest credible version */
95 #define NTP_PORT        123     /* included for sake of non-unix machines */
96 #define NTP_UNREACH     16      /* poll interval backoff count */
97 #define NTP_MINDPOLL    6       /* log2 default min poll interval (64 s) */
98 #define NTP_MAXDPOLL    10      /* log2 default max poll interval (~17 m) */
99 #define NTP_MINPOLL     4       /* log2 min poll interval (16 s) */
100 #define NTP_MAXPOLL     17      /* log2 max poll interval (~4.5 h) */
101 #define NTP_MINCLOCK    3       /* minimum survivors */
102 #define NTP_MAXCLOCK    10      /* maximum candidates */
103 #define NTP_SHIFT       8       /* 8 suitable for crystal time base */
104 #define NTP_MAXKEY      65535   /* maximum authentication key number */
105 #define NTP_MAXSESSION  100     /* maximum session key list entries */
106 #define NTP_AUTOMAX     13      /* log2 default max session key lifetime */
107 #define KEY_REVOKE      16      /* log2 default key revoke timeout */
108 #define NTP_FWEIGHT     .5      /* clock filter weight */
109 #define CLOCK_SGATE     4.      /* popcorn spike gate */
110 #define BURST_INTERVAL1 4       /* first interburst interval (log2) */
111 #define BURST_INTERVAL2 1       /* succeeding interburst intervals (log2) */
112 #define HUFFPUFF        900     /* huff-n'-puff sample interval (s) */
113
114 /*
115  * Operations for jitter calculations (these use doubles).
116  *
117  * Note that we carefully separate the jitter component from the
118  * dispersion component (frequency error plus precision). The frequency
119  * error component is computed as CLOCK_PHI times the difference between
120  * the epoch of the time measurement and the reference time. The
121  * precision componen is computed as the square root of the mean of the
122  * squares of a zero-mean, uniform distribution of unit maximum
123  * amplitude. Whether this makes statistical sense may be arguable.
124  */
125 #define SQUARE(x) ((x) * (x))
126 #define SQRT(x) (sqrt(x))
127 #define DIFF(x, y) (SQUARE((x) - (y)))
128 #define LOGTOD(a)       ((a) < 0 ? 1. / (1L << -(a)) : \
129                             1L << (int)(a)) /* log2 to double */
130 #define UNIVAR(x)       (SQUARE(.28867513 * LOGTOD(x))) /* std uniform distr */
131 #define ULOGTOD(a)      (1L << (int)(a)) /* ulog2 to double */
132 #define MAXDISPERSE     16.     /* max dispersion (square) */
133 #define MINDISPERSE     .01     /* min dispersion */
134 #define MAXDISTANCE     1.      /* max root distance */
135
136 #define EVENT_TIMEOUT   0       /* one second, that is */
137
138 #ifdef AUTOKEY
139 /*
140  * The following structures are used in the autokey protocol.
141  *
142  * The autokey structure holds the values used to authenticate key IDs.
143  */
144 struct autokey {                /* network byte order */
145         tstamp_t tstamp;        /* timestamp */
146         keyid_t key;            /* key ID */
147         int32   seq;            /* key number */
148         u_int32 siglen;         /* signature length */
149         u_int32 pkt[1];         /* start of signature field */
150         u_char  *sig;           /* signature */
151 };
152
153 /*
154  * The cookie structure holds the current private value used to
155  * construct session keys.
156  */
157 struct cookie {                 /* network byte order */
158         tstamp_t tstamp;        /* timestamp */
159         keyid_t key;            /* key ID */
160         u_int32 siglen;         /* signature length */
161         u_int32 pkt[1];         /* start of signature field */
162         u_char  *sig;           /* signature */
163 };
164
165 /*
166  * The value structure holds variable length data such as public
167  * key, agreement parameters, public valule and leapsecond table.
168  */
169 struct value {                  /* network byte order */
170         tstamp_t tstamp;        /* timestamp */
171         tstamp_t fstamp;        /* filestamp */
172         u_int32 vallen;         /* value length */
173         u_int32 pkt[1];         /* start of value field */
174         u_char  *ptr;           /* data pointer */
175         u_int32 siglen;         /* signature length */
176         u_char  *sig;           /* signature */
177 };
178 #endif /* AUTOKEY */
179
180 /*
181  * The interface structure is used to hold the addresses and socket
182  * numbers of each of the interfaces we are using.
183  */
184 struct interface {
185         int fd;                 /* socket this is opened on */
186         int bfd;                /* socket for receiving broadcasts */
187         struct sockaddr_in sin; /* interface address */
188         struct sockaddr_in bcast; /* broadcast address */
189         struct sockaddr_in mask; /* interface mask */
190         char name[8];           /* name of interface */
191         int flags;              /* interface flags */
192         int last_ttl;           /* last TTL specified */
193         volatile long received; /* number of incoming packets */
194         long sent;              /* number of outgoing packets */
195         long notsent;           /* number of send failures */
196 };
197
198 /*
199  * Flags for interfaces
200  */
201 #define INT_BROADCAST   1       /* can broadcast out this interface */
202 #define INT_BCASTOPEN   2       /* broadcast socket is open */
203 #define INT_LOOPBACK    4       /* the loopback interface */
204 #define INT_MULTICAST   8       /* multicasting enabled */
205
206 /*
207  * Define flasher bits (tests 1 through 11 in packet procedure)
208  * These reveal the state at the last grumble from the peer and are
209  * most handy for diagnosing problems, even if not strictly a state
210  * variable in the spec. These are recorded in the peer structure.
211  */
212 #define TEST1           0x0001  /* duplicate packet received */
213 #define TEST2           0x0002  /* bogus packet received */
214 #define TEST3           0x0004  /* protocol unsynchronized */
215 #define TEST4           0x0008  /* access denied */
216 #define TEST5           0x0010  /* authentication failed */
217 #define TEST6           0x0020  /* peer clock unsynchronized */
218 #define TEST7           0x0040  /* peer stratum out of bounds */
219 #define TEST8           0x0080  /* root delay/dispersion bounds check */
220 #define TEST9           0x0100  /* peer delay/dispersion bounds check */
221 #define TEST10          0x0200  /* autokey failed */
222 #define TEST11          0x0400  /* proventic not confirmed */
223
224 /*
225  * The peer structure. Holds state information relating to the guys
226  * we are peering with. Most of this stuff is from section 3.2 of the
227  * spec.
228  */
229 struct peer {
230         struct peer *next;      /* pointer to next association */
231         struct peer *ass_next;  /* link pointer in associd hash */
232         struct sockaddr_in srcadr; /* address of remote host */
233         struct interface *dstadr; /* pointer to address on local host */
234         associd_t associd;      /* association ID */
235         u_char  version;        /* version number */
236         u_char  hmode;          /* local association mode */
237         u_char  hpoll;          /* local poll interval */
238         u_char  kpoll;          /* last poll interval */
239         u_char  minpoll;        /* min poll interval */
240         u_char  maxpoll;        /* max poll interval */
241         u_char  burst;          /* packets remaining in burst */
242         u_int   flags;          /* association flags */
243         u_char  cast_flags;     /* additional flags */
244         u_int   flash;          /* protocol error test tally bits */
245         u_char  last_event;     /* last peer error code */
246         u_char  num_events;     /* number of error events */
247         u_char  ttlmax;         /* max ttl/refclock mode */
248
249         /*
250          * Variables used by reference clock support
251          */
252         struct refclockproc *procptr; /* refclock structure pointer */
253         u_char  refclktype;     /* reference clock type */
254         u_char  refclkunit;     /* reference clock unit number */
255         u_char  sstclktype;     /* clock type for system status word */
256
257         /*
258          * Variables set by received packet
259          */
260         u_char  leap;           /* local leap indicator */
261         u_char  pmode;          /* remote association mode */
262         u_char  stratum;        /* remote stratum */
263         s_char  precision;      /* remote clock precision */
264         u_char  ppoll;          /* remote poll interval */
265         u_int32 refid;          /* remote reference ID */
266         l_fp    reftime;        /* update epoch */
267
268         /*
269          * Variables used by authenticated client
270          */
271         keyid_t keyid;          /* current key ID */
272 #ifdef AUTOKEY
273 #define clear_to_zero assoc
274         associd_t assoc;        /* peer association ID */
275         u_int32 crypto;         /* peer status word */
276 #ifdef PUBKEY
277         struct  value pubkey;   /* public key */
278         struct  value certif;   /* certificate */
279         u_char  *keystr;        /* host name */
280 #endif /* PUBKEY */
281         keyid_t pkeyid;         /* previous key ID */
282         keyid_t hcookie;        /* host cookie */
283         struct cookie pcookie;  /* peer cookie */
284         struct autokey recauto; /* autokey */
285         u_int32 cmmd;           /* peer command */
286         /*
287          * Variables used by authenticated server
288          */
289         keyid_t *keylist;       /* session key ID list */
290         int     keynumber;      /* current key number */
291         struct autokey sndauto; /* autokey */
292 #else /* AUTOKEY */
293 #define clear_to_zero status
294 #endif /* AUTOKEY */
295
296         /*
297          * Ephemeral state variables
298          */
299         u_char  status;         /* peer status */
300         u_char  pollsw;         /* what it says */
301         u_char  ttl;            /* ttl for manycast mode */
302         u_char  reach;          /* reachability register */
303         u_char  unreach;        /* unreachable count */
304         u_long  epoch;          /* reference epoch */
305         u_short filter_nextpt;  /* index into filter shift register */
306         double  filter_delay[NTP_SHIFT]; /* delay shift register */
307         double  filter_offset[NTP_SHIFT]; /* offset shift register */
308         double  filter_disp[NTP_SHIFT]; /* dispersion shift register */
309         u_long  filter_epoch[NTP_SHIFT]; /* epoch shift register */
310         u_char  filter_order[NTP_SHIFT]; /* filter sort index */
311         l_fp    org;            /* originate time stamp */
312         l_fp    rec;            /* receive time stamp */
313         l_fp    xmt;            /* transmit time stamp */
314         double  offset;         /* peer clock offset */
315         double  delay;          /* peer roundtrip delay */
316         double  jitter;         /* peer jitter (squares) */
317         double  disp;           /* peer dispersion */
318         double  estbdelay;      /* clock offset to broadcast server */
319
320         /*
321          * Variables set by received packet
322          */
323         double  rootdelay;      /* roundtrip delay to primary clock */
324         double  rootdispersion; /* dispersion to primary clock */
325
326         /*
327          * End of clear-to-zero area
328          */
329         u_long  update;         /* receive epoch */
330 #define end_clear_to_zero update
331         u_long  outdate;        /* send time last packet */
332         u_long  nextdate;       /* send time next packet */
333         u_long  nextaction;     /* peer local activity timeout (refclocks mainly) */
334         void (*action) P((struct peer *)); /* action timeout function */
335         /*
336          * Statistic counters
337          */
338         u_long  timereset;      /* time stat counters were reset */
339         u_long  timereceived;   /* last packet received time */
340         u_long  timereachable;  /* last reachable/unreachable time */
341
342         u_long  sent;           /* packets sent */
343         u_long  received;       /* packets received */
344         u_long  processed;      /* packets processed by the protocol */
345         u_long  badauth;        /* packets cryptosum failed */
346         u_long  bogusorg;       /* packets bogus origin */
347         u_long  oldpkt;         /* packets duplicate packet */
348         u_long  seldisptoolarge; /* packets dispersion to large*/
349         u_long  selbroken;      /* not used */
350 };
351
352 /*
353  * Values for peer.leap, sys_leap
354  */
355 #define LEAP_NOWARNING  0x0     /* normal, no leap second warning */
356 #define LEAP_ADDSECOND  0x1     /* last minute of day has 61 seconds */
357 #define LEAP_DELSECOND  0x2     /* last minute of day has 59 seconds */
358 #define LEAP_NOTINSYNC  0x3     /* overload, clock is free running */
359
360 /*
361  * Values for peer.mode
362  */
363 #define MODE_UNSPEC     0       /* unspecified (probably old NTP version) */
364 #define MODE_ACTIVE     1       /* symmetric active */
365 #define MODE_PASSIVE    2       /* symmetric passive */
366 #define MODE_CLIENT     3       /* client mode */
367 #define MODE_SERVER     4       /* server mode */
368 #define MODE_BROADCAST  5       /* broadcast mode */
369 #define MODE_CONTROL    6       /* control mode packet */
370 #define MODE_PRIVATE    7       /* implementation defined function */
371 #define MODE_BCLIENT    8       /* broadcast client mode */
372
373 /*
374  * Values for peer.stratum, sys_stratum
375  */
376 #define STRATUM_REFCLOCK ((u_char)0) /* stratum claimed by primary clock */
377 /* A stratum of 0 in the packet is mapped to 16 internally */
378 #define STRATUM_PKT_UNSPEC ((u_char)0) /* unspecified in packet */
379 #define STRATUM_UNSPEC  ((u_char)16) /* unspecified */
380
381 /*
382  * Values for peer.flags
383  */
384 #define FLAG_CONFIG     0x0001  /* association was configured */
385 #define FLAG_AUTHENABLE 0x0002  /* authentication required */
386 #define FLAG_AUTHENTIC  0x0004  /* last message was authentic */
387 #define FLAG_SKEY       0x0008  /* autokey authentication */
388 #define FLAG_MCAST      0x0010  /* multicast client mode */
389 #define FLAG_REFCLOCK   0x0020  /* this is actually a reference clock */
390 #define FLAG_SYSPEER    0x0040  /* this is one of the selected peers */
391 #define FLAG_PREFER     0x0080  /* this is the preferred peer */
392 #define FLAG_BURST      0x0100  /* burst mode */
393 #define FLAG_IBURST     0x0200  /* initial burst mode */
394 #define FLAG_NOSELECT   0x0400  /* this is a "noselect" peer */
395 #define FLAG_AUTOKEY    0x0800  /* autokey confirmed */
396 #define FLAG_ASSOC      0x1000  /* autokey reqeust */
397 #define FLAG_PROVEN     0x2000  /* proventic confirmed */
398
399 /*
400  * Definitions for the clear() routine.  We use memset() to clear
401  * the parts of the peer structure which go to zero.  These are
402  * used to calculate the start address and length of the area.
403  */
404 #define CLEAR_TO_ZERO(p)        ((char *)&((p)->clear_to_zero))
405 #define END_CLEAR_TO_ZERO(p)    ((char *)&((p)->end_clear_to_zero))
406 #define LEN_CLEAR_TO_ZERO       (END_CLEAR_TO_ZERO((struct peer *)0) \
407                                     - CLEAR_TO_ZERO((struct peer *)0))
408 #define CRYPTO_TO_ZERO(p)        ((char *)&((p)->clear_to_zero))
409 #define END_CRYPTO_TO_ZERO(p)    ((char *)&((p)->end_clear_to_zero))
410 #define LEN_CRYPTO_TO_ZERO       (END_CRYPTO_TO_ZERO((struct peer *)0) \
411                                     - CRYPTO_TO_ZERO((struct peer *)0))
412
413 /*
414  * Reference clock identifiers (for pps signal)
415  */
416 #define PPSREFID (u_int32)"PPS "        /* used when pps controls stratum>1 */
417
418 /*
419  * Reference clock types.  Added as necessary.
420  */
421 #define REFCLK_NONE             0       /* unknown or missing */
422 #define REFCLK_LOCALCLOCK       1       /* external (e.g., lockclock) */
423 #define REFCLK_GPS_TRAK         2       /* TRAK 8810 GPS Receiver */
424 #define REFCLK_WWV_PST          3       /* PST/Traconex 1020 WWV/H */
425 #define REFCLK_SPECTRACOM       4       /* Spectracom (generic) Receivers */
426 #define REFCLK_TRUETIME         5       /* TrueTime (generic) Receivers */
427 #define REFCLK_IRIG_AUDIO       6       /* IRIG-B/W audio decoder */
428 #define REFCLK_CHU_AUDIO        7       /* CHU audio demodulator/decoder */
429 #define REFCLK_PARSE            8       /* generic driver (usually DCF77,GPS,MSF) */
430 #define REFCLK_GPS_MX4200       9       /* Magnavox MX4200 GPS */
431 #define REFCLK_GPS_AS2201       10      /* Austron 2201A GPS */
432 #define REFCLK_GPS_ARBITER      11      /* Arbiter 1088A/B/ GPS */
433 #define REFCLK_IRIG_TPRO        12      /* KSI/Odetics TPRO-S IRIG */
434 #define REFCLK_ATOM_LEITCH      13      /* Leitch CSD 5300 Master Clock */
435 #define REFCLK_MSF_EES          14      /* EES M201 MSF Receiver */
436 #define REFCLK_GPSTM_TRUE       15      /* OLD TrueTime GPS/TM-TMD Receiver */
437 #define REFCLK_IRIG_BANCOMM     16      /* Bancomm GPS/IRIG Interface */
438 #define REFCLK_GPS_DATUM        17      /* Datum Programmable Time System */
439 #define REFCLK_NIST_ACTS        18      /* NIST Auto Computer Time Service */
440 #define REFCLK_WWV_HEATH        19      /* Heath GC1000 WWV/WWVH Receiver */
441 #define REFCLK_GPS_NMEA         20      /* NMEA based GPS clock */
442 #define REFCLK_GPS_VME          21      /* TrueTime GPS-VME Interface */
443 #define REFCLK_ATOM_PPS         22      /* 1-PPS Clock Discipline */
444 #define REFCLK_PTB_ACTS         23      /* PTB Auto Computer Time Service */
445 #define REFCLK_USNO             24      /* Naval Observatory dialup */
446 #define REFCLK_GPS_HP           26      /* HP 58503A Time/Frequency Receiver */
447 #define REFCLK_ARCRON_MSF       27      /* ARCRON MSF radio clock. */
448 #define REFCLK_SHM              28      /* clock attached thru shared memory */
449 #define REFCLK_PALISADE         29      /* Trimble Navigation Palisade GPS */
450 #define REFCLK_ONCORE           30      /* Motorola UT Oncore GPS */
451 #define REFCLK_GPS_JUPITER      31      /* Rockwell Jupiter GPS receiver */
452 #define REFCLK_CHRONOLOG        32      /* Chrono-log K WWVB receiver */
453 #define REFCLK_DUMBCLOCK        33      /* Dumb localtime clock */
454 #define REFCLK_ULINK            34      /* Ultralink M320 WWVB receiver */
455 #define REFCLK_PCF              35      /* Conrad parallel port radio clock */
456 #define REFCLK_WWV_AUDIO        36      /* WWV/H audio demodulator/decoder */
457 #define REFCLK_FG               37      /* Forum Graphic GPS */
458 #define REFCLK_HOPF_SERIAL      38      /* hopf DCF77/GPS serial line receiver  */
459 #define REFCLK_HOPF_PCI         39      /* hopf DCF77/GPS PCI receiver  */
460 #define REFCLK_MAX              39      /* Grow as needed... */
461
462 /*
463  * We tell reference clocks from real peers by giving the reference
464  * clocks an address of the form 127.127.t.u, where t is the type and
465  * u is the unit number.  We define some of this here since we will need
466  * some sanity checks to make sure this address isn't interpretted as
467  * that of a normal peer.
468  */
469 #define REFCLOCK_ADDR   0x7f7f0000      /* 127.127.0.0 */
470 #define REFCLOCK_MASK   0xffff0000      /* 255.255.0.0 */
471
472 #define ISREFCLOCKADR(srcadr)   ((SRCADR(srcadr) & REFCLOCK_MASK) \
473                                         == REFCLOCK_ADDR)
474
475 /*
476  * Macro for checking for invalid addresses.  This is really, really
477  * gross, but is needed so no one configures a host on net 127 now that
478  * we're encouraging it the the configuration file.
479  */
480 #define LOOPBACKADR     0x7f000001
481 #define LOOPNETMASK     0xff000000
482
483 #define ISBADADR(srcadr)        (((SRCADR(srcadr) & LOOPNETMASK) \
484                                     == (LOOPBACKADR & LOOPNETMASK)) \
485                                     && (SRCADR(srcadr) != LOOPBACKADR))
486
487 /*
488  * Utilities for manipulating addresses and port numbers
489  */
490 #define NSRCADR(src)    ((src)->sin_addr.s_addr) /* address in net byte order */
491 #define NSRCPORT(src)   ((src)->sin_port)       /* port in net byte order */
492 #define SRCADR(src)     (ntohl(NSRCADR((src)))) /* address in host byte order */
493 #define SRCPORT(src)    (ntohs(NSRCPORT((src))))        /* host port */
494
495 /*
496  * NTP packet format.  The mac field is optional.  It isn't really
497  * an l_fp either, but for now declaring it that way is convenient.
498  * See Appendix A in the specification.
499  *
500  * Note that all u_fp and l_fp values arrive in network byte order
501  * and must be converted (except the mac, which isn't, really).
502  */
503 struct pkt {
504         u_char  li_vn_mode;     /* leap indicator, version and mode */
505         u_char  stratum;        /* peer stratum */
506         u_char  ppoll;          /* peer poll interval */
507         s_char  precision;      /* peer clock precision */
508         u_fp    rootdelay;      /* distance to primary clock */
509         u_fp    rootdispersion; /* clock dispersion */
510         u_int32 refid;          /* reference clock ID */
511         l_fp    reftime;        /* time peer clock was last updated */
512         l_fp    org;            /* originate time stamp */
513         l_fp    rec;            /* receive time stamp */
514         l_fp    xmt;            /* transmit time stamp */
515
516 #define LEN_PKT_NOMAC   12 * sizeof(u_int32) /* min header length */
517 #define LEN_PKT_MAC     LEN_PKT_NOMAC +  sizeof(u_int32)
518 #define MIN_MAC_LEN     3 * sizeof(u_int32)     /* DES */
519 #define MAX_MAC_LEN     5 * sizeof(u_int32)     /* MD5 */
520
521         /*
522          * The length of the packet less MAC must be a multiple of 64
523          * with an RSA modulus and Diffie-Hellman prime of 64 octets
524          * and maximum host name of 128 octets, the maximum autokey
525          * command is 152 octets and maximum autokey response is 460
526          * octets. A packet can contain no more than one command and one
527          * response, so the maximum total extension field length is 672
528          * octets. But, to handle humungus certificates, the bank must
529          * be broke.
530          */
531 #ifdef AUTOKEY
532 #ifdef PUBKEY
533         u_int32 exten[5000 / 4]; /* max extension field */
534 #else
535         u_int32 exten[672 / 4]; /* max extension field */
536 #endif /* PUBKEY */
537 #else /* AUTOKEY */
538         u_int32 exten[1];       /* misused */
539 #endif /* AUTOKEY */
540         u_char  mac[MAX_MAC_LEN]; /* mac */
541 };
542
543 /*
544  * Stuff for extracting things from li_vn_mode
545  */
546 #define PKT_MODE(li_vn_mode)    ((u_char)((li_vn_mode) & 0x7))
547 #define PKT_VERSION(li_vn_mode) ((u_char)(((li_vn_mode) >> 3) & 0x7))
548 #define PKT_LEAP(li_vn_mode)    ((u_char)(((li_vn_mode) >> 6) & 0x3))
549
550 /*
551  * Stuff for putting things back into li_vn_mode
552  */
553 #define PKT_LI_VN_MODE(li, vn, md) \
554         ((u_char)((((li) << 6) & 0xc0) | (((vn) << 3) & 0x38) | ((md) & 0x7)))
555
556
557 /*
558  * Dealing with stratum.  0 gets mapped to 16 incoming, and back to 0
559  * on output.
560  */
561 #define PKT_TO_STRATUM(s)       ((u_char)(((s) == (STRATUM_PKT_UNSPEC)) ?\
562                                 (STRATUM_UNSPEC) : (s)))
563
564 #define STRATUM_TO_PKT(s)       ((u_char)(((s) == (STRATUM_UNSPEC)) ?\
565                                 (STRATUM_PKT_UNSPEC) : (s)))
566
567 /*
568  * Event codes. Used for reporting errors/events to the control module
569  */
570 #define PEER_EVENT      0x80    /* this is a peer event */
571
572 /*
573  * System event codes
574  */
575 #define EVNT_UNSPEC     0       /* unspecified */
576 #define EVNT_SYSRESTART 1       /* system restart */
577 #define EVNT_SYSFAULT   2       /* wsystem or hardware fault */
578 #define EVNT_SYNCCHG    3       /* new leap or synch change */
579 #define EVNT_PEERSTCHG  4       /* new source or stratum */
580 #define EVNT_CLOCKRESET 5       /* clock reset */
581 #define EVNT_BADDATETIM 6       /* invalid time or date */
582 #define EVNT_CLOCKEXCPT 7       /* reference clock exception */
583
584 /*
585  * Peer event codes
586  */
587 #define EVNT_PEERIPERR  (1 | PEER_EVENT) /* IP error */
588 #define EVNT_PEERAUTH   (2 | PEER_EVENT) /* authentication failure */
589 #define EVNT_UNREACH    (3 | PEER_EVENT) /* change to unreachable */
590 #define EVNT_REACH      (4 | PEER_EVENT) /* change to reachable */
591 #define EVNT_PEERCLOCK  (5 | PEER_EVENT) /* clock exception */
592
593 /*
594  * Clock event codes
595  */
596 #define CEVNT_NOMINAL   0       /* unspecified */
597 #define CEVNT_TIMEOUT   1       /* poll timeout */
598 #define CEVNT_BADREPLY  2       /* bad reply format */
599 #define CEVNT_FAULT     3       /* hardware or software fault */
600 #define CEVNT_PROP      4       /* propagation failure */
601 #define CEVNT_BADDATE   5       /* bad date format or value */
602 #define CEVNT_BADTIME   6       /* bad time format or value */
603 #define CEVNT_MAX       CEVNT_BADTIME
604
605 /*
606  * Very misplaced value.  Default port through which we send traps.
607  */
608 #define TRAPPORT        18447
609
610
611 /*
612  * To speed lookups, peers are hashed by the low order bits of the
613  * remote IP address. These definitions relate to that.
614  */
615 #define HASH_SIZE       32
616 #define HASH_MASK       (HASH_SIZE-1)
617 #define HASH_ADDR(src)  ((SRCADR((src))^(SRCADR((src))>>8)) & HASH_MASK)
618
619 /*
620  * How we randomize polls.  The poll interval is a power of two.
621  * We chose a random value which is between 1/4 and 3/4 of the
622  * poll interval we would normally use and which is an even multiple
623  * of the EVENT_TIMEOUT.  The random number routine, given an argument
624  * spread value of n, returns an integer between 0 and (1<<n)-1.  This
625  * is shifted by EVENT_TIMEOUT and added to the base value.
626  */
627 #if defined(HAVE_MRAND48)
628 # define RANDOM         (mrand48())
629 # define SRANDOM(x)     (srand48(x))
630 #else
631 # define RANDOM         (random())
632 # define SRANDOM(x)     (srandom(x))
633 #endif
634
635 #define RANDPOLL(x)     ((1 << (x)) - 1 + (RANDOM & 0x3))
636 #define RANDOM_SPREAD(poll)     ((poll) - (EVENT_TIMEOUT+1))
637 #define RANDOM_POLL(poll, rval) ((((rval)+1)<<EVENT_TIMEOUT) + (1<<((poll)-2)))
638
639 /*
640  * min, min3 and max.  Makes it easier to transliterate the spec without
641  * thinking about it.
642  */
643 #define min(a,b)        (((a) < (b)) ? (a) : (b))
644 #define max(a,b)        (((a) > (b)) ? (a) : (b))
645 #define min3(a,b,c)     min(min((a),(b)), (c))
646
647
648 /*
649  * Configuration items.  These are for the protocol module (proto_config())
650  */
651 #define PROTO_BROADCLIENT       1
652 #define PROTO_PRECISION         2       /* (not used) */
653 #define PROTO_AUTHENTICATE      3
654 #define PROTO_BROADDELAY        4
655 #define PROTO_AUTHDELAY         5       /* (not used) */
656 #define PROTO_MULTICAST_ADD     6
657 #define PROTO_MULTICAST_DEL     7
658 #define PROTO_NTP               8
659 #define PROTO_KERNEL            9
660 #define PROTO_MONITOR           10
661 #define PROTO_FILEGEN           11
662 #define PROTO_PPS               12
663 #define PROTO_CAL               13
664
665 /*
666  * Configuration items for the loop filter
667  */
668 #define LOOP_DRIFTINIT          1       /* set initial frequency offset */
669 #define LOOP_DRIFTCOMP          2       /* set frequency offset */
670 #define LOOP_MAX                3       /* set step offset */
671 #define LOOP_PANIC              4       /* set panic offseet */
672 #define LOOP_PHI                5       /* set dispersion rate */
673 #define LOOP_MINSTEP            6       /* set step timeout */
674 #define LOOP_MINPOLL            7       /* set min poll interval (log2 s) */
675 #define LOOP_ALLAN              8       /* set minimum Allan intercept */
676 #define LOOP_HUFFPUFF           9       /* set huff-n'-puff filter length */
677
678 /*
679  * Configuration items for the stats printer
680  */
681 #define STATS_FREQ_FILE         1       /* configure drift file */
682 #define STATS_STATSDIR          2       /* directory prefix for stats files */
683 #define STATS_PID_FILE          3       /* configure ntpd PID file */
684
685 #define MJD_1970                40587   /* MJD for 1 Jan 1970 */
686
687 /*
688  * Default parameters.  We use these in the absence of something better.
689  */
690 #define DEFBROADDELAY   4e-3            /* default broadcast offset */
691 #define INADDR_NTP      0xe0000101      /* NTP multicast address 224.0.1.1 */
692
693 /*
694  * Structure used optionally for monitoring when this is turned on.
695  */
696 struct mon_data {
697         struct mon_data *hash_next;     /* next structure in hash list */
698         struct mon_data *mru_next;      /* next structure in MRU list */
699         struct mon_data *mru_prev;      /* previous structure in MRU list */
700         struct mon_data *fifo_next;     /* next structure in FIFO list */
701         struct mon_data *fifo_prev;     /* previous structure in FIFO list */
702         u_long lastdrop;                /* last time dropped due to RES_LIMIT*/
703         u_long lasttime;                /* last time data updated */
704         u_long firsttime;               /* time structure initialized */
705         u_long count;                   /* count we have seen */
706         u_int32 rmtadr;                 /* address of remote host */
707         struct interface *interface;    /* interface on which this arrived */
708         u_short rmtport;                /* remote port last came from */
709         u_char mode;                    /* mode of incoming packet */
710         u_char version;                 /* version of incoming packet */
711         u_char cast_flags;              /* flags MDF_?CAST */
712 };
713
714 /*
715  * Values for cast_flags
716  */
717 #define MDF_UCAST       0x01            /* unicast */
718 #define MDF_MCAST       0x02            /* multicast */
719 #define MDF_BCAST       0x04            /* broadcast */
720 #define MDF_LCAST       0x08            /* localcast */
721 #define MDF_ACAST       0x10            /* manycast */
722 #define MDF_BCLNT       0x20            /* broadcast client */
723
724 /*
725  * Values used with mon_enabled to indicate reason for enabling monitoring
726  */
727 #define MON_OFF    0x00                 /* no monitoring */
728 #define MON_ON     0x01                 /* monitoring explicitly enabled */
729 #define MON_RES    0x02                 /* implicit monitoring for RES_LIMITED */
730 /*
731  * Structure used for restrictlist entries
732  */
733 struct restrictlist {
734         struct restrictlist *next;      /* link to next entry */
735         u_int32 addr;                   /* host address (host byte order) */
736         u_int32 mask;                   /* mask for address (host byte order) */
737         u_long count;                   /* number of packets matched */
738         u_short flags;                  /* accesslist flags */
739         u_short mflags;                 /* match flags */
740 };
741
742 /*
743  * Access flags
744  */
745 #define RES_IGNORE              0x001   /* ignore if matched */
746 #define RES_DONTSERVE           0x002   /* don't give him any time */
747 #define RES_DONTTRUST           0x004   /* don't trust if matched */
748 #define RES_NOQUERY             0x008   /* don't allow queries if matched */
749 #define RES_NOMODIFY            0x010   /* don't allow him to modify server */
750 #define RES_NOPEER              0x020   /* don't allocate memory resources */
751 #define RES_NOTRAP              0x040   /* don't allow him to set traps */
752 #define RES_LPTRAP              0x080   /* traps set by him are low priority */
753 #define RES_LIMITED             0x100   /* limit per net number of clients */
754 #define RES_VERSION             0x200   /* serve only current version */
755 #define RES_DEMOBILIZE          0x400   /* demobilize association */
756
757 #define RES_ALLFLAGS \
758     (RES_IGNORE | RES_DONTSERVE | RES_DONTTRUST | RES_NOQUERY | \
759      RES_NOMODIFY | RES_NOPEER | RES_NOTRAP | RES_LPTRAP | \
760      RES_LIMITED | RES_VERSION | RES_DEMOBILIZE)
761
762 /*
763  * Match flags
764  */
765 #define RESM_INTERFACE          0x1     /* this is an interface */
766 #define RESM_NTPONLY            0x2     /* match ntp port only */
767
768 /*
769  * Restriction configuration ops
770  */
771 #define RESTRICT_FLAGS          1       /* add flags to restrict entry */
772 #define RESTRICT_UNFLAG         2       /* remove flags from restrict entry */
773 #define RESTRICT_REMOVE         3       /* remove a restrict entry */
774
775
776 /*
777  * Experimental alternate selection algorithm identifiers
778  */
779 #define SELECT_1        1
780 #define SELECT_2        2
781 #define SELECT_3        3
782 #define SELECT_4        4
783 #define SELECT_5        5
784
785 /*
786  * Endpoint structure for the select algorithm
787  */
788 struct endpoint {
789         double  val;                    /* offset of endpoint */
790         int     type;                   /* interval entry/exit */
791 };
792
793 /*
794  * Defines for association matching 
795  */
796 #define AM_MODES        10      /* total number of modes */
797 #define NO_PEER         0       /* action when no peer is found */
798
799 /*
800  * Association matching AM[] return codes
801  */
802 #define AM_ERR          -1
803 #define AM_NOMATCH       0
804 #define AM_PROCPKT       1
805 #define AM_FXMIT         2
806 #define AM_MANYCAST      3
807 #define AM_NEWPASS       4
808 #define AM_NEWBCL        5
809 #define AM_POSSBCL       6
810
811 /* NetInfo configuration locations */
812 #ifdef HAVE_NETINFO
813 #define NETINFO_CONFIG_DIR "/config/ntp"
814 #endif
815
816 #endif /* NTP_H */