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