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