xref: /freebsd/contrib/ntp/ntpd/ntp_proto.c (revision 0dbdecfd4f23486da21345fe446a28a1c27db3f2)
1 /*
2  * ntp_proto.c - NTP version 4 protocol machinery
3  *
4  * ATTENTION: Get approval from Harlan on all changes to this file!
5  *	    (Harlan will be discussing these changes with Dave Mills.)
6  *
7  */
8 #ifdef HAVE_CONFIG_H
9 #include <config.h>
10 #endif
11 
12 #include "ntpd.h"
13 #include "ntp_stdlib.h"
14 #include "ntp_unixtime.h"
15 #include "ntp_control.h"
16 #include "ntp_string.h"
17 #include "ntp_leapsec.h"
18 #include "refidsmear.h"
19 #include "lib_strbuf.h"
20 
21 #include <stdio.h>
22 #ifdef HAVE_LIBSCF_H
23 #include <libscf.h>
24 #endif
25 #ifdef HAVE_UNISTD_H
26 #include <unistd.h>
27 #endif
28 
29 /* [Bug 3031] define automatic broadcastdelay cutoff preset */
30 #ifndef BDELAY_DEFAULT
31 # define BDELAY_DEFAULT (-0.050)
32 #endif
33 
34 /*
35  * This macro defines the authentication state. If x is 1 authentication
36  * is required; othewise it is optional.
37  */
38 #define	AUTH(x, y)	((x) ? (y) == AUTH_OK \
39 			     : (y) == AUTH_OK || (y) == AUTH_NONE)
40 
41 typedef enum
42 auth_state {
43 	AUTH_UNKNOWN = -1,	/* Unknown */
44 	AUTH_NONE,		/* authentication not required */
45 	AUTH_OK,		/* authentication OK */
46 	AUTH_ERROR,		/* authentication error */
47 	AUTH_CRYPTO		/* crypto_NAK */
48 } auth_code;
49 
50 /*
51  * Set up Kiss Code values
52  */
53 
54 typedef enum
55 kiss_codes {
56 	NOKISS,				/* No Kiss Code */
57 	RATEKISS,			/* Rate limit Kiss Code */
58 	DENYKISS,			/* Deny Kiss */
59 	RSTRKISS,			/* Restricted Kiss */
60 	XKISS				/* Experimental Kiss */
61 } kiss_code;
62 
63 typedef enum
64 nak_error_codes {
65 	NONAK,				/* No NAK seen */
66 	INVALIDNAK,			/* NAK cannot be used */
67 	VALIDNAK			/* NAK is valid */
68 } nak_code;
69 
70 /*
71  * traffic shaping parameters
72  */
73 #define	NTP_IBURST	6	/* packets in iburst */
74 #define	RESP_DELAY	1	/* refclock burst delay (s) */
75 
76 /*
77  * pool soliciting restriction duration (s)
78  */
79 #define	POOL_SOLICIT_WINDOW	8
80 
81 /*
82  * peer_select groups statistics for a peer used by clock_select() and
83  * clock_cluster().
84  */
85 typedef struct peer_select_tag {
86 	struct peer *	peer;
87 	double		synch;	/* sync distance */
88 	double		error;	/* jitter */
89 	double		seljit;	/* selection jitter */
90 } peer_select;
91 
92 /*
93  * System variables are declared here. Unless specified otherwise, all
94  * times are in seconds.
95  */
96 u_char	sys_leap;		/* system leap indicator, use set_sys_leap() to change this */
97 u_char	xmt_leap;		/* leap indicator sent in client requests, set up by set_sys_leap() */
98 u_char	sys_stratum;		/* system stratum */
99 s_char	sys_precision;		/* local clock precision (log2 s) */
100 double	sys_rootdelay;		/* roundtrip delay to primary source */
101 double	sys_rootdisp;		/* dispersion to primary source */
102 u_int32 sys_refid;		/* reference id (network byte order) */
103 l_fp	sys_reftime;		/* last update time */
104 struct	peer *sys_peer;		/* current peer */
105 
106 #ifdef LEAP_SMEAR
107 struct leap_smear_info leap_smear;
108 #endif
109 int leap_sec_in_progress;
110 
111 /*
112  * Rate controls. Leaky buckets are used to throttle the packet
113  * transmission rates in order to protect busy servers such as at NIST
114  * and USNO. There is a counter for each association and another for KoD
115  * packets. The association counter decrements each second, but not
116  * below zero. Each time a packet is sent the counter is incremented by
117  * a configurable value representing the average interval between
118  * packets. A packet is delayed as long as the counter is greater than
119  * zero. Note this does not affect the time value computations.
120  */
121 /*
122  * Nonspecified system state variables
123  */
124 int	sys_bclient;		/* broadcast client enable */
125 double	sys_bdelay;		/* broadcast client default delay */
126 int	sys_authenticate;	/* requre authentication for config */
127 l_fp	sys_authdelay;		/* authentication delay */
128 double	sys_offset;	/* current local clock offset */
129 double	sys_mindisp = MINDISPERSE; /* minimum distance (s) */
130 double	sys_maxdist = MAXDISTANCE; /* selection threshold */
131 double	sys_jitter;		/* system jitter */
132 u_long	sys_epoch;		/* last clock update time */
133 static	double sys_clockhop;	/* clockhop threshold */
134 static int leap_vote_ins;	/* leap consensus for insert */
135 static int leap_vote_del;	/* leap consensus for delete */
136 keyid_t	sys_private;		/* private value for session seed */
137 int	sys_manycastserver;	/* respond to manycast client pkts */
138 int	ntp_mode7;		/* respond to ntpdc (mode7) */
139 int	peer_ntpdate;		/* active peers in ntpdate mode */
140 int	sys_survivors;		/* truest of the truechimers */
141 char	*sys_ident = NULL;	/* identity scheme */
142 
143 /*
144  * TOS and multicast mapping stuff
145  */
146 int	sys_floor = 0;		/* cluster stratum floor */
147 u_char	sys_bcpollbstep = 0;	/* Broadcast Poll backstep gate */
148 int	sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
149 int	sys_minsane = 1;	/* minimum candidates */
150 int	sys_minclock = NTP_MINCLOCK; /* minimum candidates */
151 int	sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
152 int	sys_cohort = 0;		/* cohort switch */
153 int	sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
154 int	sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
155 int	sys_beacon = BEACON;	/* manycast beacon interval */
156 u_int	sys_ttlmax;		/* max ttl mapping vector index */
157 u_char	sys_ttl[MAX_TTL];	/* ttl mapping vector */
158 
159 /*
160  * Statistics counters - first the good, then the bad
161  */
162 u_long	sys_stattime;		/* elapsed time */
163 u_long	sys_received;		/* packets received */
164 u_long	sys_processed;		/* packets for this host */
165 u_long	sys_newversion;		/* current version */
166 u_long	sys_oldversion;		/* old version */
167 u_long	sys_restricted;		/* access denied */
168 u_long	sys_badlength;		/* bad length or format */
169 u_long	sys_badauth;		/* bad authentication */
170 u_long	sys_declined;		/* declined */
171 u_long	sys_limitrejected;	/* rate exceeded */
172 u_long	sys_kodsent;		/* KoD sent */
173 
174 /*
175  * Mechanism knobs: how soon do we peer_clear() or unpeer()?
176  *
177  * The default way is "on-receipt".  If this was a packet from a
178  * well-behaved source, on-receipt will offer the fastest recovery.
179  * If this was from a DoS attack, the default way makes it easier
180  * for a bad-guy to DoS us.  So look and see what bites you harder
181  * and choose according to your environment.
182  */
183 int peer_clear_digest_early	= 1;	/* bad digest (TEST5) and Autokey */
184 int unpeer_crypto_early		= 1;	/* bad crypto (TEST9) */
185 int unpeer_crypto_nak_early	= 1;	/* crypto_NAK (TEST5) */
186 int unpeer_digest_early		= 1;	/* bad digest (TEST5) */
187 
188 int dynamic_interleave = DYNAMIC_INTERLEAVE;	/* Bug 2978 mitigation */
189 
190 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
191 nak_code	valid_NAK	(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
192 static	double	root_distance	(struct peer *);
193 static	void	clock_combine	(peer_select *, int, int);
194 static	void	peer_xmit	(struct peer *);
195 static	void	fast_xmit	(struct recvbuf *, int, keyid_t, int);
196 static	void	pool_xmit	(struct peer *);
197 static	void	clock_update	(struct peer *);
198 static	void	measure_precision(void);
199 static	double	measure_tick_fuzz(void);
200 static	int	local_refid	(struct peer *);
201 static	int	peer_unfit	(struct peer *);
202 #ifdef AUTOKEY
203 static	int	group_test	(char *, char *);
204 #endif /* AUTOKEY */
205 #ifdef WORKER
206 void	pool_name_resolved	(int, int, void *, const char *,
207 				 const char *, const struct addrinfo *,
208 				 const struct addrinfo *);
209 #endif /* WORKER */
210 
211 const char *	amtoa		(int am);
212 
213 
214 void
215 set_sys_leap(
216 	u_char new_sys_leap
217 	)
218 {
219 	sys_leap = new_sys_leap;
220 	xmt_leap = sys_leap;
221 
222 	/*
223 	 * Under certain conditions we send faked leap bits to clients, so
224 	 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
225 	 */
226 	if (xmt_leap != LEAP_NOTINSYNC) {
227 		if (leap_sec_in_progress) {
228 			/* always send "not sync" */
229 			xmt_leap = LEAP_NOTINSYNC;
230 		}
231 #ifdef LEAP_SMEAR
232 		else {
233 			/*
234 			 * If leap smear is enabled in general we must
235 			 * never send a leap second warning to clients,
236 			 * so make sure we only send "in sync".
237 			 */
238 			if (leap_smear.enabled)
239 				xmt_leap = LEAP_NOWARNING;
240 		}
241 #endif	/* LEAP_SMEAR */
242 	}
243 }
244 
245 
246 /*
247  * Kiss Code check
248  */
249 int
250 kiss_code_check(
251 	u_char hisleap,
252 	u_char hisstratum,
253 	u_char hismode,
254 	u_int32 refid
255 	)
256 {
257 
258 	if (   hismode == MODE_SERVER
259 	    && hisleap == LEAP_NOTINSYNC
260 	    && hisstratum == STRATUM_UNSPEC) {
261 		if(memcmp(&refid,"RATE", 4) == 0) {
262 			return (RATEKISS);
263 		} else if(memcmp(&refid,"DENY", 4) == 0) {
264 			return (DENYKISS);
265 		} else if(memcmp(&refid,"RSTR", 4) == 0) {
266 			return (RSTRKISS);
267 		} else if(memcmp(&refid,"X", 1) == 0) {
268 			return (XKISS);
269 		}
270 	}
271 	return (NOKISS);
272 }
273 
274 
275 /*
276  * Check that NAK is valid
277  */
278 nak_code
279 valid_NAK(
280 	  struct peer *peer,
281 	  struct recvbuf *rbufp,
282 	  u_char hismode
283 	  )
284 {
285 	int		base_packet_length = MIN_V4_PKT_LEN;
286 	int		remainder_size;
287 	struct pkt *	rpkt;
288 	int		keyid;
289 	l_fp		p_org;	/* origin timestamp */
290 	const l_fp *	myorg;	/* selected peer origin */
291 
292 	/*
293 	 * Check to see if there is something beyond the basic packet
294 	 */
295 	if (rbufp->recv_length == base_packet_length) {
296 		return NONAK;
297 	}
298 
299 	remainder_size = rbufp->recv_length - base_packet_length;
300 	/*
301 	 * Is this a potential NAK?
302 	 */
303 	if (remainder_size != 4) {
304 		return NONAK;
305 	}
306 
307 	/*
308 	 * Only server responses can contain NAK's
309 	 */
310 
311 	if (hismode != MODE_SERVER &&
312 	    hismode != MODE_ACTIVE &&
313 	    hismode != MODE_PASSIVE
314 	    ) {
315 		return INVALIDNAK;
316 	}
317 
318 	/*
319 	 * Make sure that the extra field in the packet is all zeros
320 	 */
321 	rpkt = &rbufp->recv_pkt;
322 	keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
323 	if (keyid != 0) {
324 		return INVALIDNAK;
325 	}
326 
327 	/*
328 	 * Only valid if peer uses a key
329 	 */
330 	if (!peer || !peer->keyid || !(peer->flags & FLAG_SKEY)) {
331 		return INVALIDNAK;
332 	}
333 
334 	/*
335 	 * The ORIGIN must match, or this cannot be a valid NAK, either.
336 	 */
337 	NTOHL_FP(&rpkt->org, &p_org);
338 	if (peer->flip > 0)
339 		myorg = &peer->borg;
340 	else
341 		myorg = &peer->aorg;
342 
343 	if (L_ISZERO(&p_org) ||
344 	    L_ISZERO( myorg) ||
345 	    !L_ISEQU(&p_org, myorg)) {
346 		return INVALIDNAK;
347 	}
348 
349 	/* If we ever passed all that checks, we should be safe. Well,
350 	 * as safe as we can ever be with an unauthenticated crypto-nak.
351 	 */
352 	return VALIDNAK;
353 }
354 
355 
356 /*
357  * transmit - transmit procedure called by poll timeout
358  */
359 void
360 transmit(
361 	struct peer *peer	/* peer structure pointer */
362 	)
363 {
364 	u_char	hpoll;
365 
366 	/*
367 	 * The polling state machine. There are two kinds of machines,
368 	 * those that never expect a reply (broadcast and manycast
369 	 * server modes) and those that do (all other modes). The dance
370 	 * is intricate...
371 	 */
372 	hpoll = peer->hpoll;
373 
374 	/*
375 	 * In broadcast mode the poll interval is never changed from
376 	 * minpoll.
377 	 */
378 	if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
379 		peer->outdate = current_time;
380 		if (sys_leap != LEAP_NOTINSYNC)
381 			peer_xmit(peer);
382 		poll_update(peer, hpoll);
383 		return;
384 	}
385 
386 	/*
387 	 * In manycast mode we start with unity ttl. The ttl is
388 	 * increased by one for each poll until either sys_maxclock
389 	 * servers have been found or the maximum ttl is reached. When
390 	 * sys_maxclock servers are found we stop polling until one or
391 	 * more servers have timed out or until less than sys_minclock
392 	 * associations turn up. In this case additional better servers
393 	 * are dragged in and preempt the existing ones.  Once every
394 	 * sys_beacon seconds we are to transmit unconditionally, but
395 	 * this code is not quite right -- peer->unreach counts polls
396 	 * and is being compared with sys_beacon, so the beacons happen
397 	 * every sys_beacon polls.
398 	 */
399 	if (peer->cast_flags & MDF_ACAST) {
400 		peer->outdate = current_time;
401 		if (peer->unreach > sys_beacon) {
402 			peer->unreach = 0;
403 			peer->ttl = 0;
404 			peer_xmit(peer);
405 		} else if (   sys_survivors < sys_minclock
406 			   || peer_associations < sys_maxclock) {
407 			if (peer->ttl < sys_ttlmax)
408 				peer->ttl++;
409 			peer_xmit(peer);
410 		}
411 		peer->unreach++;
412 		poll_update(peer, hpoll);
413 		return;
414 	}
415 
416 	/*
417 	 * Pool associations transmit unicast solicitations when there
418 	 * are less than a hard limit of 2 * sys_maxclock associations,
419 	 * and either less than sys_minclock survivors or less than
420 	 * sys_maxclock associations.  The hard limit prevents unbounded
421 	 * growth in associations if the system clock or network quality
422 	 * result in survivor count dipping below sys_minclock often.
423 	 * This was observed testing with pool, where sys_maxclock == 12
424 	 * resulted in 60 associations without the hard limit.  A
425 	 * similar hard limit on manycastclient ephemeral associations
426 	 * may be appropriate.
427 	 */
428 	if (peer->cast_flags & MDF_POOL) {
429 		peer->outdate = current_time;
430 		if (   (peer_associations <= 2 * sys_maxclock)
431 		    && (   peer_associations < sys_maxclock
432 			|| sys_survivors < sys_minclock))
433 			pool_xmit(peer);
434 		poll_update(peer, hpoll);
435 		return;
436 	}
437 
438 	/*
439 	 * In unicast modes the dance is much more intricate. It is
440 	 * designed to back off whenever possible to minimize network
441 	 * traffic.
442 	 */
443 	if (peer->burst == 0) {
444 		u_char oreach;
445 
446 		/*
447 		 * Update the reachability status. If not heard for
448 		 * three consecutive polls, stuff infinity in the clock
449 		 * filter.
450 		 */
451 		oreach = peer->reach;
452 		peer->outdate = current_time;
453 		peer->unreach++;
454 		peer->reach <<= 1;
455 		if (!peer->reach) {
456 
457 			/*
458 			 * Here the peer is unreachable. If it was
459 			 * previously reachable raise a trap. Send a
460 			 * burst if enabled.
461 			 */
462 			clock_filter(peer, 0., 0., MAXDISPERSE);
463 			if (oreach) {
464 				peer_unfit(peer);
465 				report_event(PEVNT_UNREACH, peer, NULL);
466 			}
467 			if (   (peer->flags & FLAG_IBURST)
468 			    && peer->retry == 0)
469 				peer->retry = NTP_RETRY;
470 		} else {
471 
472 			/*
473 			 * Here the peer is reachable. Send a burst if
474 			 * enabled and the peer is fit.  Reset unreach
475 			 * for persistent and ephemeral associations.
476 			 * Unreach is also reset for survivors in
477 			 * clock_select().
478 			 */
479 			hpoll = sys_poll;
480 			if (!(peer->flags & FLAG_PREEMPT))
481 				peer->unreach = 0;
482 			if (   (peer->flags & FLAG_BURST)
483 			    && peer->retry == 0
484 			    && !peer_unfit(peer))
485 				peer->retry = NTP_RETRY;
486 		}
487 
488 		/*
489 		 * Watch for timeout.  If ephemeral, toss the rascal;
490 		 * otherwise, bump the poll interval. Note the
491 		 * poll_update() routine will clamp it to maxpoll.
492 		 * If preemptible and we have more peers than maxclock,
493 		 * and this peer has the minimum score of preemptibles,
494 		 * demobilize.
495 		 */
496 		if (peer->unreach >= NTP_UNREACH) {
497 			hpoll++;
498 			/* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
499 			if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
500 				report_event(PEVNT_RESTART, peer, "timeout");
501 				peer_clear(peer, "TIME");
502 				unpeer(peer);
503 				return;
504 			}
505 			if (   (peer->flags & FLAG_PREEMPT)
506 			    && (peer_associations > sys_maxclock)
507 			    && score_all(peer)) {
508 				report_event(PEVNT_RESTART, peer, "timeout");
509 				peer_clear(peer, "TIME");
510 				unpeer(peer);
511 				return;
512 			}
513 		}
514 	} else {
515 		peer->burst--;
516 		if (peer->burst == 0) {
517 
518 			/*
519 			 * If ntpdate mode and the clock has not been
520 			 * set and all peers have completed the burst,
521 			 * we declare a successful failure.
522 			 */
523 			if (mode_ntpdate) {
524 				peer_ntpdate--;
525 				if (peer_ntpdate == 0) {
526 					msyslog(LOG_NOTICE,
527 					    "ntpd: no servers found");
528 					if (!msyslog_term)
529 						printf(
530 						    "ntpd: no servers found\n");
531 					exit (0);
532 				}
533 			}
534 		}
535 	}
536 	if (peer->retry > 0)
537 		peer->retry--;
538 
539 	/*
540 	 * Do not transmit if in broadcast client mode.
541 	 */
542 	if (peer->hmode != MODE_BCLIENT)
543 		peer_xmit(peer);
544 	poll_update(peer, hpoll);
545 
546 	return;
547 }
548 
549 
550 const char *
551 amtoa(
552 	int am
553 	)
554 {
555 	char *bp;
556 
557 	switch(am) {
558 	    case AM_ERR:	return "AM_ERR";
559 	    case AM_NOMATCH:	return "AM_NOMATCH";
560 	    case AM_PROCPKT:	return "AM_PROCPKT";
561 	    case AM_BCST:	return "AM_BCST";
562 	    case AM_FXMIT:	return "AM_FXMIT";
563 	    case AM_MANYCAST:	return "AM_MANYCAST";
564 	    case AM_NEWPASS:	return "AM_NEWPASS";
565 	    case AM_NEWBCL:	return "AM_NEWBCL";
566 	    case AM_POSSBCL:	return "AM_POSSBCL";
567 	    default:
568 		LIB_GETBUF(bp);
569 		snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
570 		return bp;
571 	}
572 }
573 
574 
575 /*
576  * receive - receive procedure called for each packet received
577  */
578 void
579 receive(
580 	struct recvbuf *rbufp
581 	)
582 {
583 	register struct peer *peer;	/* peer structure pointer */
584 	register struct pkt *pkt;	/* receive packet pointer */
585 	u_char	hisversion;		/* packet version */
586 	u_char	hisleap;		/* packet leap indicator */
587 	u_char	hismode;		/* packet mode */
588 	u_char	hisstratum;		/* packet stratum */
589 	r4addr	r4a;			/* address restrictions */
590 	u_short	restrict_mask;		/* restrict bits */
591 	const char *hm_str;		/* hismode string */
592 	const char *am_str;		/* association match string */
593 	int	kissCode = NOKISS;	/* Kiss Code */
594 	int	has_mac;		/* length of MAC field */
595 	int	authlen;		/* offset of MAC field */
596 	auth_code is_authentic = AUTH_UNKNOWN;	/* Was AUTH_NONE */
597 	nak_code crypto_nak_test;	/* result of crypto-NAK check */
598 	int	retcode = AM_NOMATCH;	/* match code */
599 	keyid_t	skeyid = 0;		/* key IDs */
600 	u_int32	opcode = 0;		/* extension field opcode */
601 	sockaddr_u *dstadr_sin;		/* active runway */
602 	struct peer *peer2;		/* aux peer structure pointer */
603 	endpt	*match_ep;		/* newpeer() local address */
604 	l_fp	p_org;			/* origin timestamp */
605 	l_fp	p_rec;			/* receive timestamp */
606 	l_fp	p_xmt;			/* transmit timestamp */
607 #ifdef AUTOKEY
608 	char	hostname[NTP_MAXSTRLEN + 1];
609 	char	*groupname = NULL;
610 	struct autokey *ap;		/* autokey structure pointer */
611 	int	rval;			/* cookie snatcher */
612 	keyid_t	pkeyid = 0, tkeyid = 0;	/* key IDs */
613 #endif	/* AUTOKEY */
614 #ifdef HAVE_NTP_SIGND
615 	static unsigned char zero_key[16];
616 #endif /* HAVE_NTP_SIGND */
617 
618 	/*
619 	 * Note that there are many places we do not call record_raw_stats().
620 	 *
621 	 * We only want to call it *after* we've sent a response, or perhaps
622 	 * when we've decided to drop a packet.
623 	 */
624 
625 	/*
626 	 * Monitor the packet and get restrictions. Note that the packet
627 	 * length for control and private mode packets must be checked
628 	 * by the service routines. Some restrictions have to be handled
629 	 * later in order to generate a kiss-o'-death packet.
630 	 */
631 	/*
632 	 * Bogus port check is before anything, since it probably
633 	 * reveals a clogging attack.
634 	 */
635 	sys_received++;
636 	if (0 == SRCPORT(&rbufp->recv_srcadr)) {
637 		sys_badlength++;
638 		return;				/* bogus port */
639 	}
640 	restrictions(&rbufp->recv_srcadr, &r4a);
641 	restrict_mask = r4a.rflags;
642 
643 	pkt = &rbufp->recv_pkt;
644 	hisversion = PKT_VERSION(pkt->li_vn_mode);
645 	hisleap = PKT_LEAP(pkt->li_vn_mode);
646 	hismode = (int)PKT_MODE(pkt->li_vn_mode);
647 	hisstratum = PKT_TO_STRATUM(pkt->stratum);
648 	DPRINTF(2, ("receive: at %ld %s<-%s ippeerlimit %d mode %d iflags %s restrict %s org %#010x.%08x xmt %#010x.%08x\n",
649 		    current_time, stoa(&rbufp->dstadr->sin),
650 		    stoa(&rbufp->recv_srcadr), r4a.ippeerlimit, hismode,
651 		    build_iflags(rbufp->dstadr->flags),
652 		    build_rflags(restrict_mask),
653 		    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
654 		    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
655 
656 	/* See basic mode and broadcast checks, below */
657 	INSIST(0 != hisstratum);
658 
659 	if (restrict_mask & RES_IGNORE) {
660 		DPRINTF(2, ("receive: drop: RES_IGNORE\n"));
661 		sys_restricted++;
662 		return;				/* ignore everything */
663 	}
664 	if (hismode == MODE_PRIVATE) {
665 		if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
666 			DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
667 			sys_restricted++;
668 			return;			/* no query private */
669 		}
670 		process_private(rbufp, ((restrict_mask &
671 		    RES_NOMODIFY) == 0));
672 		return;
673 	}
674 	if (hismode == MODE_CONTROL) {
675 		if (restrict_mask & RES_NOQUERY) {
676 			DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
677 			sys_restricted++;
678 			return;			/* no query control */
679 		}
680 		process_control(rbufp, restrict_mask);
681 		return;
682 	}
683 	if (restrict_mask & RES_DONTSERVE) {
684 		DPRINTF(2, ("receive: drop: RES_DONTSERVE\n"));
685 		sys_restricted++;
686 		return;				/* no time serve */
687 	}
688 
689 	/*
690 	 * This is for testing. If restricted drop ten percent of
691 	 * surviving packets.
692 	 */
693 	if (restrict_mask & RES_FLAKE) {
694 		if ((double)ntp_random() / 0x7fffffff < .1) {
695 			DPRINTF(2, ("receive: drop: RES_FLAKE\n"));
696 			sys_restricted++;
697 			return;			/* no flakeway */
698 		}
699 	}
700 
701 	/*
702 	** Format Layer Checks
703 	**
704 	** Validate the packet format.  The packet size, packet header,
705 	** and any extension field lengths are checked.  We identify
706 	** the beginning of the MAC, to identify the upper limit of
707 	** of the hash computation.
708 	**
709 	** In case of a format layer check violation, the packet is
710 	** discarded with no further processing.
711 	*/
712 
713 	/*
714 	 * Version check must be after the query packets, since they
715 	 * intentionally use an early version.
716 	 */
717 	if (hisversion == NTP_VERSION) {
718 		sys_newversion++;		/* new version */
719 	} else if (   !(restrict_mask & RES_VERSION)
720 		   && hisversion >= NTP_OLDVERSION) {
721 		sys_oldversion++;		/* previous version */
722 	} else {
723 		DPRINTF(2, ("receive: drop: RES_VERSION\n"));
724 		sys_badlength++;
725 		return;				/* old version */
726 	}
727 
728 	/*
729 	 * Figure out his mode and validate the packet. This has some
730 	 * legacy raunch that probably should be removed. In very early
731 	 * NTP versions mode 0 was equivalent to what later versions
732 	 * would interpret as client mode.
733 	 */
734 	if (hismode == MODE_UNSPEC) {
735 		if (hisversion == NTP_OLDVERSION) {
736 			hismode = MODE_CLIENT;
737 		} else {
738 			DPRINTF(2, ("receive: drop: MODE_UNSPEC\n"));
739 			sys_badlength++;
740 			return;                 /* invalid mode */
741 		}
742 	}
743 
744 	/*
745 	 * Parse the extension field if present. We figure out whether
746 	 * an extension field is present by measuring the MAC size. If
747 	 * the number of words following the packet header is 0, no MAC
748 	 * is present and the packet is not authenticated. If 1, the
749 	 * packet is a crypto-NAK; if 3, the packet is authenticated
750 	 * with DES; if 5, the packet is authenticated with MD5; if 6,
751 	 * the packet is authenticated with SHA. If 2 or * 4, the packet
752 	 * is a runt and discarded forthwith. If greater than 6, an
753 	 * extension field is present, so we subtract the length of the
754 	 * field and go around again.
755 	 *
756 	 * Note the above description is lame.  We should/could also check
757 	 * the two bytes that make up the EF type and subtype, and then
758 	 * check the two bytes that tell us the EF length.  A legacy MAC
759 	 * has a 4 byte keyID, and for conforming symmetric keys its value
760 	 * must be <= 64k, meaning the top two bytes will always be zero.
761 	 * Since the EF Type of 0 is reserved/unused, there's no way a
762 	 * conforming legacy MAC could ever be misinterpreted as an EF.
763 	 *
764 	 * There is more, but this isn't the place to document it.
765 	 */
766 
767 	authlen = LEN_PKT_NOMAC;
768 	has_mac = rbufp->recv_length - authlen;
769 	while (has_mac > 0) {
770 		u_int32	len;
771 #ifdef AUTOKEY
772 		u_int32	hostlen;
773 		struct exten *ep;
774 #endif /*AUTOKEY */
775 
776 		if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
777 			DPRINTF(2, ("receive: drop: bad post-packet length\n"));
778 			sys_badlength++;
779 			return;			/* bad length */
780 		}
781 		/*
782 		 * This next test is clearly wrong - it needlessly
783 		 * prohibits short EFs (which don't yet exist)
784 		 */
785 		if (has_mac <= (int)MAX_MAC_LEN) {
786 			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
787 			break;
788 
789 		} else {
790 			opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
791 			len = opcode & 0xffff;
792 			if (   len % 4 != 0
793 			    || len < 4
794 			    || (int)len + authlen > rbufp->recv_length) {
795 				DPRINTF(2, ("receive: drop: bad EF length\n"));
796 				sys_badlength++;
797 				return;		/* bad length */
798 			}
799 #ifdef AUTOKEY
800 			/*
801 			 * Extract calling group name for later.  If
802 			 * sys_groupname is non-NULL, there must be
803 			 * a group name provided to elicit a response.
804 			 */
805 			if (   (opcode & 0x3fff0000) == CRYPTO_ASSOC
806 			    && sys_groupname != NULL) {
807 				ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
808 				hostlen = ntohl(ep->vallen);
809 				if (   hostlen >= sizeof(hostname)
810 				    || hostlen > len -
811 						offsetof(struct exten, pkt)) {
812 					DPRINTF(2, ("receive: drop: bad autokey hostname length\n"));
813 					sys_badlength++;
814 					return;		/* bad length */
815 				}
816 				memcpy(hostname, &ep->pkt, hostlen);
817 				hostname[hostlen] = '\0';
818 				groupname = strchr(hostname, '@');
819 				if (groupname == NULL) {
820 					DPRINTF(2, ("receive: drop: empty autokey groupname\n"));
821 					sys_declined++;
822 					return;
823 				}
824 				groupname++;
825 			}
826 #endif /* AUTOKEY */
827 			authlen += len;
828 			has_mac -= len;
829 		}
830 	}
831 
832 	/*
833 	 * If has_mac is < 0 we had a malformed packet.
834 	 */
835 	if (has_mac < 0) {
836 		DPRINTF(2, ("receive: drop: post-packet under-read\n"));
837 		sys_badlength++;
838 		return;		/* bad length */
839 	}
840 
841 	/*
842 	** Packet Data Verification Layer
843 	**
844 	** This layer verifies the packet data content.  If
845 	** authentication is required, a MAC must be present.
846 	** If a MAC is present, it must validate.
847 	** Crypto-NAK?  Look - a shiny thing!
848 	**
849 	** If authentication fails, we're done.
850 	*/
851 
852 	/*
853 	 * If authentication is explicitly required, a MAC must be present.
854 	 */
855 	if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
856 		DPRINTF(2, ("receive: drop: RES_DONTTRUST\n"));
857 		sys_restricted++;
858 		return;				/* access denied */
859 	}
860 
861 	/*
862 	 * Update the MRU list and finger the cloggers. It can be a
863 	 * little expensive, so turn it off for production use.
864 	 * RES_LIMITED and RES_KOD will be cleared in the returned
865 	 * restrict_mask unless one or both actions are warranted.
866 	 */
867 	restrict_mask = ntp_monitor(rbufp, restrict_mask);
868 	if (restrict_mask & RES_LIMITED) {
869 		sys_limitrejected++;
870 		if (   !(restrict_mask & RES_KOD)
871 		    || MODE_BROADCAST == hismode
872 		    || MODE_SERVER == hismode) {
873 			if (MODE_SERVER == hismode) {
874 				DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
875 					stoa(&rbufp->recv_srcadr)));
876 			} else {
877 				DPRINTF(2, ("receive: drop: RES_KOD\n"));
878 			}
879 			return;			/* rate exceeded */
880 		}
881 		if (hismode == MODE_CLIENT)
882 			fast_xmit(rbufp, MODE_SERVER, skeyid,
883 			    restrict_mask);
884 		else
885 			fast_xmit(rbufp, MODE_ACTIVE, skeyid,
886 			    restrict_mask);
887 		return;				/* rate exceeded */
888 	}
889 	restrict_mask &= ~RES_KOD;
890 
891 	/*
892 	 * We have tossed out as many buggy packets as possible early in
893 	 * the game to reduce the exposure to a clogging attack. Now we
894 	 * have to burn some cycles to find the association and
895 	 * authenticate the packet if required. Note that we burn only
896 	 * digest cycles, again to reduce exposure. There may be no
897 	 * matching association and that's okay.
898 	 *
899 	 * More on the autokey mambo. Normally the local interface is
900 	 * found when the association was mobilized with respect to a
901 	 * designated remote address. We assume packets arriving from
902 	 * the remote address arrive via this interface and the local
903 	 * address used to construct the autokey is the unicast address
904 	 * of the interface. However, if the sender is a broadcaster,
905 	 * the interface broadcast address is used instead.
906 	 * Notwithstanding this technobabble, if the sender is a
907 	 * multicaster, the broadcast address is null, so we use the
908 	 * unicast address anyway. Don't ask.
909 	 */
910 
911 	peer = findpeer(rbufp,  hismode, &retcode);
912 	dstadr_sin = &rbufp->dstadr->sin;
913 	NTOHL_FP(&pkt->org, &p_org);
914 	NTOHL_FP(&pkt->rec, &p_rec);
915 	NTOHL_FP(&pkt->xmt, &p_xmt);
916 	hm_str = modetoa(hismode);
917 	am_str = amtoa(retcode);
918 
919 	/*
920 	 * Authentication is conditioned by three switches:
921 	 *
922 	 * NOPEER  (RES_NOPEER) do not mobilize an association unless
923 	 *         authenticated
924 	 * NOTRUST (RES_DONTTRUST) do not allow access unless
925 	 *         authenticated (implies NOPEER)
926 	 * enable  (sys_authenticate) master NOPEER switch, by default
927 	 *         on
928 	 *
929 	 * The NOPEER and NOTRUST can be specified on a per-client basis
930 	 * using the restrict command. The enable switch if on implies
931 	 * NOPEER for all clients. There are four outcomes:
932 	 *
933 	 * NONE    The packet has no MAC.
934 	 * OK      the packet has a MAC and authentication succeeds
935 	 * ERROR   the packet has a MAC and authentication fails
936 	 * CRYPTO  crypto-NAK. The MAC has four octets only.
937 	 *
938 	 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
939 	 * is zero, acceptable outcomes of y are NONE and OK. If x is
940 	 * one, the only acceptable outcome of y is OK.
941 	 */
942 	crypto_nak_test = valid_NAK(peer, rbufp, hismode);
943 
944 	/*
945 	 * Drop any invalid crypto-NAKs
946 	 */
947 	if (crypto_nak_test == INVALIDNAK) {
948 		report_event(PEVNT_AUTH, peer, "Invalid_NAK");
949 		if (0 != peer) {
950 			peer->badNAK++;
951 		}
952 		msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
953 			current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
954 		return;
955 	}
956 
957 	if (has_mac == 0) {
958 		restrict_mask &= ~RES_MSSNTP;
959 		is_authentic = AUTH_NONE; /* not required */
960 		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
961 			    current_time, stoa(dstadr_sin),
962 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
963 			    authlen,
964 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
965 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
966 	} else if (crypto_nak_test == VALIDNAK) {
967 		restrict_mask &= ~RES_MSSNTP;
968 		is_authentic = AUTH_CRYPTO; /* crypto-NAK */
969 		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\n",
970 			    current_time, stoa(dstadr_sin),
971 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
972 			    skeyid, authlen + has_mac, is_authentic,
973 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
974 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
975 
976 #ifdef HAVE_NTP_SIGND
977 		/*
978 		 * If the signature is 20 bytes long, the last 16 of
979 		 * which are zero, then this is a Microsoft client
980 		 * wanting AD-style authentication of the server's
981 		 * reply.
982 		 *
983 		 * This is described in Microsoft's WSPP docs, in MS-SNTP:
984 		 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
985 		 */
986 	} else if (   has_mac == MAX_MD5_LEN
987 		   && (restrict_mask & RES_MSSNTP)
988 		   && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
989 		   && (memcmp(zero_key, (char *)pkt + authlen + 4,
990 			      MAX_MD5_LEN - 4) == 0)) {
991 		is_authentic = AUTH_NONE;
992 #endif /* HAVE_NTP_SIGND */
993 
994 	} else {
995 		/*
996 		 * has_mac is not 0
997 		 * Not a VALID_NAK
998 		 * Not an MS-SNTP SIGND  packet
999 		 *
1000 		 * So there is a MAC here.
1001 		 */
1002 
1003 		restrict_mask &= ~RES_MSSNTP;
1004 #ifdef AUTOKEY
1005 		/*
1006 		 * For autokey modes, generate the session key
1007 		 * and install in the key cache. Use the socket
1008 		 * broadcast or unicast address as appropriate.
1009 		 */
1010 		if (crypto_flags && skeyid > NTP_MAXKEY) {
1011 
1012 			/*
1013 			 * More on the autokey dance (AKD). A cookie is
1014 			 * constructed from public and private values.
1015 			 * For broadcast packets, the cookie is public
1016 			 * (zero). For packets that match no
1017 			 * association, the cookie is hashed from the
1018 			 * addresses and private value. For server
1019 			 * packets, the cookie was previously obtained
1020 			 * from the server. For symmetric modes, the
1021 			 * cookie was previously constructed using an
1022 			 * agreement protocol; however, should PKI be
1023 			 * unavailable, we construct a fake agreement as
1024 			 * the EXOR of the peer and host cookies.
1025 			 *
1026 			 * hismode	ephemeral	persistent
1027 			 * =======================================
1028 			 * active	0		cookie#
1029 			 * passive	0%		cookie#
1030 			 * client	sys cookie	0%
1031 			 * server	0%		sys cookie
1032 			 * broadcast	0		0
1033 			 *
1034 			 * # if unsync, 0
1035 			 * % can't happen
1036 			 */
1037 			if (has_mac < (int)MAX_MD5_LEN) {
1038 				DPRINTF(2, ("receive: drop: MD5 digest too short\n"));
1039 				sys_badauth++;
1040 				return;
1041 			}
1042 			if (hismode == MODE_BROADCAST) {
1043 
1044 				/*
1045 				 * For broadcaster, use the interface
1046 				 * broadcast address when available;
1047 				 * otherwise, use the unicast address
1048 				 * found when the association was
1049 				 * mobilized. However, if this is from
1050 				 * the wildcard interface, game over.
1051 				 */
1052 				if (   crypto_flags
1053 				    && rbufp->dstadr ==
1054 				       ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
1055 					DPRINTF(2, ("receive: drop: BCAST from wildcard\n"));
1056 					sys_restricted++;
1057 					return;	     /* no wildcard */
1058 				}
1059 				pkeyid = 0;
1060 				if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
1061 					dstadr_sin =
1062 					    &rbufp->dstadr->bcast;
1063 			} else if (peer == NULL) {
1064 				pkeyid = session_key(
1065 				    &rbufp->recv_srcadr, dstadr_sin, 0,
1066 				    sys_private, 0);
1067 			} else {
1068 				pkeyid = peer->pcookie;
1069 			}
1070 
1071 			/*
1072 			 * The session key includes both the public
1073 			 * values and cookie. In case of an extension
1074 			 * field, the cookie used for authentication
1075 			 * purposes is zero. Note the hash is saved for
1076 			 * use later in the autokey mambo.
1077 			 */
1078 			if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
1079 				session_key(&rbufp->recv_srcadr,
1080 				    dstadr_sin, skeyid, 0, 2);
1081 				tkeyid = session_key(
1082 				    &rbufp->recv_srcadr, dstadr_sin,
1083 				    skeyid, pkeyid, 0);
1084 			} else {
1085 				tkeyid = session_key(
1086 				    &rbufp->recv_srcadr, dstadr_sin,
1087 				    skeyid, pkeyid, 2);
1088 			}
1089 
1090 		}
1091 #endif	/* AUTOKEY */
1092 
1093 		/*
1094 		 * Compute the cryptosum. Note a clogging attack may
1095 		 * succeed in bloating the key cache. If an autokey,
1096 		 * purge it immediately, since we won't be needing it
1097 		 * again. If the packet is authentic, it can mobilize an
1098 		 * association. Note that there is no key zero.
1099 		 */
1100 		if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1101 		    has_mac))
1102 			is_authentic = AUTH_ERROR;
1103 		else
1104 			is_authentic = AUTH_OK;
1105 #ifdef AUTOKEY
1106 		if (crypto_flags && skeyid > NTP_MAXKEY)
1107 			authtrust(skeyid, 0);
1108 #endif	/* AUTOKEY */
1109 		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n",
1110 			    current_time, stoa(dstadr_sin),
1111 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1112 			    skeyid, authlen + has_mac, is_authentic,
1113 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1114 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1115 	}
1116 
1117 
1118 	/*
1119 	 * Bug 3454:
1120 	 *
1121 	 * Now come at this from a different perspective:
1122 	 * - If we expect a MAC and it's not there, we drop it.
1123 	 * - If we expect one keyID and get another, we drop it.
1124 	 * - If we have a MAC ahd it hasn't been validated yet, try.
1125 	 * - if the provided MAC doesn't validate, we drop it.
1126 	 *
1127 	 * There might be more to this.
1128 	 */
1129 	if (0 != peer && 0 != peer->keyid) {
1130 		/* Should we msyslog() any of these? */
1131 
1132 		/*
1133 		 * This should catch:
1134 		 * - no keyID where one is expected,
1135 		 * - different keyID than what we expect.
1136 		 */
1137 		if (peer->keyid != skeyid) {
1138 			DPRINTF(2, ("receive: drop: Wanted keyID %d, got %d from %s\n",
1139 				    peer->keyid, skeyid,
1140 				    stoa(&rbufp->recv_srcadr)));
1141 			sys_restricted++;
1142 			return;			/* drop: access denied */
1143 		}
1144 
1145 		/*
1146 		 * if has_mac != 0 ...
1147 		 * - If it has not yet been validated, do so.
1148 		 *   (under what circumstances might that happen?)
1149 		 * - if missing or bad MAC, log and drop.
1150 		 */
1151 		if (0 != has_mac) {
1152 			if (is_authentic == AUTH_UNKNOWN) {
1153 				/* How can this happen? */
1154 				DPRINTF(2, ("receive: 3454 check: AUTH_UNKNOWN from %s\n",
1155 				    stoa(&rbufp->recv_srcadr)));
1156 				if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1157 				    has_mac)) {
1158 					/* MAC invalid or not found */
1159 					is_authentic = AUTH_ERROR;
1160 				} else {
1161 					is_authentic = AUTH_OK;
1162 				}
1163 			}
1164 			if (is_authentic != AUTH_OK) {
1165 				DPRINTF(2, ("receive: drop: missing or bad MAC from %s\n",
1166 					    stoa(&rbufp->recv_srcadr)));
1167 				sys_restricted++;
1168 				return;		/* drop: access denied */
1169 			}
1170 		}
1171 	}
1172 	/**/
1173 
1174 	/*
1175 	** On-Wire Protocol Layer
1176 	**
1177 	** Verify protocol operations consistent with the on-wire protocol.
1178 	** The protocol discards bogus and duplicate packets as well as
1179 	** minimizes disruptions doe to protocol restarts and dropped
1180 	** packets.  The operations are controlled by two timestamps:
1181 	** the transmit timestamp saved in the client state variables,
1182 	** and the origin timestamp in the server packet header.  The
1183 	** comparison of these two timestamps is called the loopback test.
1184 	** The transmit timestamp functions as a nonce to verify that the
1185 	** response corresponds to the original request.  The transmit
1186 	** timestamp also serves to discard replays of the most recent
1187 	** packet.  Upon failure of either test, the packet is discarded
1188 	** with no further action.
1189 	*/
1190 
1191 	/*
1192 	 * The association matching rules are implemented by a set of
1193 	 * routines and an association table. A packet matching an
1194 	 * association is processed by the peer process for that
1195 	 * association. If there are no errors, an ephemeral association
1196 	 * is mobilized: a broadcast packet mobilizes a broadcast client
1197 	 * aassociation; a manycast server packet mobilizes a manycast
1198 	 * client association; a symmetric active packet mobilizes a
1199 	 * symmetric passive association.
1200 	 */
1201 	switch (retcode) {
1202 
1203 	/*
1204 	 * This is a client mode packet not matching any association. If
1205 	 * an ordinary client, simply toss a server mode packet back
1206 	 * over the fence. If a manycast client, we have to work a
1207 	 * little harder.
1208 	 *
1209 	 * There are cases here where we do not call record_raw_stats().
1210 	 */
1211 	case AM_FXMIT:
1212 
1213 		/*
1214 		 * If authentication OK, send a server reply; otherwise,
1215 		 * send a crypto-NAK.
1216 		 */
1217 		if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1218 			/* HMS: would be nice to log FAST_XMIT|BADAUTH|RESTRICTED */
1219 			record_raw_stats(&rbufp->recv_srcadr,
1220 			    &rbufp->dstadr->sin,
1221 			    &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1222 			    PKT_LEAP(pkt->li_vn_mode),
1223 			    PKT_VERSION(pkt->li_vn_mode),
1224 			    PKT_MODE(pkt->li_vn_mode),
1225 			    PKT_TO_STRATUM(pkt->stratum),
1226 			    pkt->ppoll,
1227 			    pkt->precision,
1228 			    FPTOD(NTOHS_FP(pkt->rootdelay)),
1229 			    FPTOD(NTOHS_FP(pkt->rootdisp)),
1230 			    pkt->refid,
1231 			    rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1232 
1233 			if (AUTH(restrict_mask & RES_DONTTRUST,
1234 			   is_authentic)) {
1235 				fast_xmit(rbufp, MODE_SERVER, skeyid,
1236 				    restrict_mask);
1237 			} else if (is_authentic == AUTH_ERROR) {
1238 				fast_xmit(rbufp, MODE_SERVER, 0,
1239 				    restrict_mask);
1240 				sys_badauth++;
1241 			} else {
1242 				DPRINTF(2, ("receive: AM_FXMIT drop: !mcast restricted\n"));
1243 				sys_restricted++;
1244 			}
1245 
1246 			return;			/* hooray */
1247 		}
1248 
1249 		/*
1250 		 * This must be manycast. Do not respond if not
1251 		 * configured as a manycast server.
1252 		 */
1253 		if (!sys_manycastserver) {
1254 			DPRINTF(2, ("receive: AM_FXMIT drop: Not manycastserver\n"));
1255 			sys_restricted++;
1256 			return;			/* not enabled */
1257 		}
1258 
1259 #ifdef AUTOKEY
1260 		/*
1261 		 * Do not respond if not the same group.
1262 		 */
1263 		if (group_test(groupname, NULL)) {
1264 			DPRINTF(2, ("receive: AM_FXMIT drop: empty groupname\n"));
1265 			sys_declined++;
1266 			return;
1267 		}
1268 #endif /* AUTOKEY */
1269 
1270 		/*
1271 		 * Do not respond if we are not synchronized or our
1272 		 * stratum is greater than the manycaster or the
1273 		 * manycaster has already synchronized to us.
1274 		 */
1275 		if (   sys_leap == LEAP_NOTINSYNC
1276 		    || sys_stratum >= hisstratum
1277 		    || (!sys_cohort && sys_stratum == hisstratum + 1)
1278 		    || rbufp->dstadr->addr_refid == pkt->refid) {
1279 			DPRINTF(2, ("receive: AM_FXMIT drop: LEAP_NOTINSYNC || stratum || loop\n"));
1280 			sys_declined++;
1281 			return;			/* no help */
1282 		}
1283 
1284 		/*
1285 		 * Respond only if authentication succeeds. Don't do a
1286 		 * crypto-NAK, as that would not be useful.
1287 		 */
1288 		if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) {
1289 			record_raw_stats(&rbufp->recv_srcadr,
1290 			    &rbufp->dstadr->sin,
1291 			    &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1292 			    PKT_LEAP(pkt->li_vn_mode),
1293 			    PKT_VERSION(pkt->li_vn_mode),
1294 			    PKT_MODE(pkt->li_vn_mode),
1295 			    PKT_TO_STRATUM(pkt->stratum),
1296 			    pkt->ppoll,
1297 			    pkt->precision,
1298 			    FPTOD(NTOHS_FP(pkt->rootdelay)),
1299 			    FPTOD(NTOHS_FP(pkt->rootdisp)),
1300 			    pkt->refid,
1301 			    rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1302 
1303 			fast_xmit(rbufp, MODE_SERVER, skeyid,
1304 			    restrict_mask);
1305 		}
1306 		return;				/* hooray */
1307 
1308 	/*
1309 	 * This is a server mode packet returned in response to a client
1310 	 * mode packet sent to a multicast group address (for
1311 	 * manycastclient) or to a unicast address (for pool). The
1312 	 * origin timestamp is a good nonce to reliably associate the
1313 	 * reply with what was sent. If there is no match, that's
1314 	 * curious and could be an intruder attempting to clog, so we
1315 	 * just ignore it.
1316 	 *
1317 	 * If the packet is authentic and the manycastclient or pool
1318 	 * association is found, we mobilize a client association and
1319 	 * copy pertinent variables from the manycastclient or pool
1320 	 * association to the new client association. If not, just
1321 	 * ignore the packet.
1322 	 *
1323 	 * There is an implosion hazard at the manycast client, since
1324 	 * the manycast servers send the server packet immediately. If
1325 	 * the guy is already here, don't fire up a duplicate.
1326 	 *
1327 	 * There are cases here where we do not call record_raw_stats().
1328 	 */
1329 	case AM_MANYCAST:
1330 
1331 #ifdef AUTOKEY
1332 		/*
1333 		 * Do not respond if not the same group.
1334 		 */
1335 		if (group_test(groupname, NULL)) {
1336 			DPRINTF(2, ("receive: AM_MANYCAST drop: empty groupname\n"));
1337 			sys_declined++;
1338 			return;
1339 		}
1340 #endif /* AUTOKEY */
1341 		if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1342 			DPRINTF(2, ("receive: AM_MANYCAST drop: No manycast peer\n"));
1343 			sys_restricted++;
1344 			return;			/* not enabled */
1345 		}
1346 		if (!AUTH(  (!(peer2->cast_flags & MDF_POOL)
1347 			     && sys_authenticate)
1348 			  || (restrict_mask & (RES_NOPEER |
1349 			      RES_DONTTRUST)), is_authentic)
1350 		    /* MC: RES_NOEPEER? */
1351 		   ) {
1352 			DPRINTF(2, ("receive: AM_MANYCAST drop: bad auth || (NOPEER|DONTTRUST)\n"));
1353 			sys_restricted++;
1354 			return;			/* access denied */
1355 		}
1356 
1357 		/*
1358 		 * Do not respond if unsynchronized or stratum is below
1359 		 * the floor or at or above the ceiling.
1360 		 */
1361 		if (   hisleap == LEAP_NOTINSYNC
1362 		    || hisstratum < sys_floor
1363 		    || hisstratum >= sys_ceiling) {
1364 			DPRINTF(2, ("receive: AM_MANYCAST drop: unsync/stratum\n"));
1365 			sys_declined++;
1366 			return;			/* no help */
1367 		}
1368 		peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1369 			       r4a.ippeerlimit, MODE_CLIENT, hisversion,
1370 			       peer2->minpoll, peer2->maxpoll,
1371 			       FLAG_PREEMPT | (FLAG_IBURST & peer2->flags),
1372 			       MDF_UCAST | MDF_UCLNT, 0, skeyid, sys_ident);
1373 		if (NULL == peer) {
1374 			DPRINTF(2, ("receive: AM_MANYCAST drop: duplicate\n"));
1375 			sys_declined++;
1376 			return;			/* ignore duplicate  */
1377 		}
1378 
1379 		/*
1380 		 * After each ephemeral pool association is spun,
1381 		 * accelerate the next poll for the pool solicitor so
1382 		 * the pool will fill promptly.
1383 		 */
1384 		if (peer2->cast_flags & MDF_POOL)
1385 			peer2->nextdate = current_time + 1;
1386 
1387 		/*
1388 		 * Further processing of the solicitation response would
1389 		 * simply detect its origin timestamp as bogus for the
1390 		 * brand-new association (it matches the prototype
1391 		 * association) and tinker with peer->nextdate delaying
1392 		 * first sync.
1393 		 */
1394 		return;		/* solicitation response handled */
1395 
1396 	/*
1397 	 * This is the first packet received from a broadcast server. If
1398 	 * the packet is authentic and we are enabled as broadcast
1399 	 * client, mobilize a broadcast client association. We don't
1400 	 * kiss any frogs here.
1401 	 *
1402 	 * There are cases here where we do not call record_raw_stats().
1403 	 */
1404 	case AM_NEWBCL:
1405 
1406 #ifdef AUTOKEY
1407 		/*
1408 		 * Do not respond if not the same group.
1409 		 */
1410 		if (group_test(groupname, sys_ident)) {
1411 			DPRINTF(2, ("receive: AM_NEWBCL drop: groupname mismatch\n"));
1412 			sys_declined++;
1413 			return;
1414 		}
1415 #endif /* AUTOKEY */
1416 		if (sys_bclient == 0) {
1417 			DPRINTF(2, ("receive: AM_NEWBCL drop: not a bclient\n"));
1418 			sys_restricted++;
1419 			return;			/* not enabled */
1420 		}
1421 		if (!AUTH(sys_authenticate | (restrict_mask &
1422 			  (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1423 		    /* NEWBCL: RES_NOEPEER? */
1424 		   ) {
1425 			DPRINTF(2, ("receive: AM_NEWBCL drop: AUTH failed\n"));
1426 			sys_restricted++;
1427 			return;			/* access denied */
1428 		}
1429 
1430 		/*
1431 		 * Do not respond if unsynchronized or stratum is below
1432 		 * the floor or at or above the ceiling.
1433 		 */
1434 		if (   hisleap == LEAP_NOTINSYNC
1435 		    || hisstratum < sys_floor
1436 		    || hisstratum >= sys_ceiling) {
1437 			DPRINTF(2, ("receive: AM_NEWBCL drop: Unsync or bad stratum\n"));
1438 			sys_declined++;
1439 			return;			/* no help */
1440 		}
1441 
1442 #ifdef AUTOKEY
1443 		/*
1444 		 * Do not respond if Autokey and the opcode is not a
1445 		 * CRYPTO_ASSOC response with association ID.
1446 		 */
1447 		if (   crypto_flags && skeyid > NTP_MAXKEY
1448 		    && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1449 			DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not CRYPTO_ASSOC\n"));
1450 			sys_declined++;
1451 			return;			/* protocol error */
1452 		}
1453 #endif	/* AUTOKEY */
1454 
1455 		/*
1456 		 * Broadcasts received via a multicast address may
1457 		 * arrive after a unicast volley has begun
1458 		 * with the same remote address.  newpeer() will not
1459 		 * find duplicate associations on other local endpoints
1460 		 * if a non-NULL endpoint is supplied.  multicastclient
1461 		 * ephemeral associations are unique across all local
1462 		 * endpoints.
1463 		 */
1464 		if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1465 			match_ep = rbufp->dstadr;
1466 		else
1467 			match_ep = NULL;
1468 
1469 		/*
1470 		 * Determine whether to execute the initial volley.
1471 		 */
1472 		if (sys_bdelay > 0.0) {
1473 #ifdef AUTOKEY
1474 			/*
1475 			 * If a two-way exchange is not possible,
1476 			 * neither is Autokey.
1477 			 */
1478 			if (crypto_flags && skeyid > NTP_MAXKEY) {
1479 				sys_restricted++;
1480 				DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not 2-way\n"));
1481 				return;		/* no autokey */
1482 			}
1483 #endif	/* AUTOKEY */
1484 
1485 			/*
1486 			 * Do not execute the volley. Start out in
1487 			 * broadcast client mode.
1488 			 */
1489 			peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1490 			    r4a.ippeerlimit, MODE_BCLIENT, hisversion,
1491 			    pkt->ppoll, pkt->ppoll,
1492 			    FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident);
1493 			if (NULL == peer) {
1494 				DPRINTF(2, ("receive: AM_NEWBCL drop: duplicate\n"));
1495 				sys_restricted++;
1496 				return;		/* ignore duplicate */
1497 
1498 			} else {
1499 				peer->delay = sys_bdelay;
1500 				peer->bxmt = p_xmt;
1501 			}
1502 			break;
1503 		}
1504 
1505 		/*
1506 		 * Execute the initial volley in order to calibrate the
1507 		 * propagation delay and run the Autokey protocol.
1508 		 *
1509 		 * Note that the minpoll is taken from the broadcast
1510 		 * packet, normally 6 (64 s) and that the poll interval
1511 		 * is fixed at this value.
1512 		 */
1513 		peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1514 		    r4a.ippeerlimit, MODE_CLIENT, hisversion,
1515 		    pkt->ppoll, pkt->ppoll,
1516 		    FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1517 		    0, skeyid, sys_ident);
1518 		if (NULL == peer) {
1519 			DPRINTF(2, ("receive: AM_NEWBCL drop: empty newpeer() failed\n"));
1520 			sys_restricted++;
1521 			return;			/* ignore duplicate */
1522 		}
1523 		peer->bxmt = p_xmt;
1524 #ifdef AUTOKEY
1525 		if (skeyid > NTP_MAXKEY)
1526 			crypto_recv(peer, rbufp);
1527 #endif	/* AUTOKEY */
1528 
1529 		return;				/* hooray */
1530 
1531 	/*
1532 	 * This is the first packet received from a symmetric active
1533 	 * peer.  If the packet is authentic, the first he sent, and
1534 	 * RES_NOEPEER is not enabled, mobilize a passive association
1535 	 * If not, kiss the frog.
1536 	 *
1537 	 * There are cases here where we do not call record_raw_stats().
1538 	 */
1539 	case AM_NEWPASS:
1540 
1541 #ifdef AUTOKEY
1542 		/*
1543 		 * Do not respond if not the same group.
1544 		 */
1545 		if (group_test(groupname, sys_ident)) {
1546 			DPRINTF(2, ("receive: AM_NEWPASS drop: Autokey group mismatch\n"));
1547 			sys_declined++;
1548 			return;
1549 		}
1550 #endif /* AUTOKEY */
1551 		if (!AUTH(sys_authenticate | (restrict_mask &
1552 			  (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1553 		   ) {
1554 			if (0 == (restrict_mask & RES_NOEPEER)) {
1555 				/*
1556 				 * If authenticated but cannot mobilize an
1557 				 * association, send a symmetric passive
1558 				 * response without mobilizing an association.
1559 				 * This is for drat broken Windows clients. See
1560 				 * Microsoft KB 875424 for preferred workaround.
1561 				 */
1562 				if (AUTH(restrict_mask & RES_DONTTRUST,
1563 					 is_authentic)) {
1564 					fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1565 					    restrict_mask);
1566 					return;			/* hooray */
1567 				}
1568 				if (is_authentic == AUTH_ERROR) {
1569 					fast_xmit(rbufp, MODE_ACTIVE, 0,
1570 					    restrict_mask);
1571 					sys_restricted++;
1572 					return;
1573 				}
1574 			}
1575 			/* [Bug 2941]
1576 			 * If we got here, the packet isn't part of an
1577 			 * existing association, either isn't correctly
1578 			 * authenticated or it is but we are refusing
1579 			 * ephemeral peer requests, and it didn't meet
1580 			 * either of the previous two special cases so we
1581 			 * should just drop it on the floor.  For example,
1582 			 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1583 			 * will make it this far.  This is just
1584 			 * debug-printed and not logged to avoid log
1585 			 * flooding.
1586 			 */
1587 			DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1588 				    " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1589 				    current_time, stoa(&rbufp->recv_srcadr),
1590 				    hismode, hm_str, am_str, skeyid,
1591 				    (authlen + has_mac), is_authentic));
1592 			sys_declined++;
1593 			return;
1594 		}
1595 
1596 		/*
1597 		 * Do not respond if synchronized and if stratum is
1598 		 * below the floor or at or above the ceiling. Note,
1599 		 * this allows an unsynchronized peer to synchronize to
1600 		 * us. It would be very strange if he did and then was
1601 		 * nipped, but that could only happen if we were
1602 		 * operating at the top end of the range.  It also means
1603 		 * we will spin an ephemeral association in response to
1604 		 * MODE_ACTIVE KoDs, which will time out eventually.
1605 		 */
1606 		if (   hisleap != LEAP_NOTINSYNC
1607 		    && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1608 			DPRINTF(2, ("receive: AM_NEWPASS drop: Autokey group mismatch\n"));
1609 			sys_declined++;
1610 			return;			/* no help */
1611 		}
1612 
1613 		/*
1614 		 * The message is correctly authenticated and allowed.
1615 		 * Mobilize a symmetric passive association, if we won't
1616 		 * exceed the ippeerlimit.
1617 		 */
1618 		if ((peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1619 				    r4a.ippeerlimit, MODE_PASSIVE, hisversion,
1620 				    pkt->ppoll, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
1621 				    skeyid, sys_ident)) == NULL) {
1622 			DPRINTF(2, ("receive: AM_NEWPASS drop: newpeer() failed\n"));
1623 			sys_declined++;
1624 			return;			/* ignore duplicate */
1625 		}
1626 		break;
1627 
1628 
1629 	/*
1630 	 * Process regular packet. Nothing special.
1631 	 *
1632 	 * There are cases here where we do not call record_raw_stats().
1633 	 */
1634 	case AM_PROCPKT:
1635 
1636 #ifdef AUTOKEY
1637 		/*
1638 		 * Do not respond if not the same group.
1639 		 */
1640 		if (group_test(groupname, peer->ident)) {
1641 			DPRINTF(2, ("receive: AM_PROCPKT drop: Autokey group mismatch\n"));
1642 			sys_declined++;
1643 			return;
1644 		}
1645 #endif /* AUTOKEY */
1646 
1647 		if (MODE_BROADCAST == hismode) {
1648 			int	bail = 0;
1649 			l_fp	tdiff;
1650 			u_long	deadband;
1651 
1652 			DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1653 				    (current_time - peer->timelastrec),
1654 				    peer->ppoll, (1 << peer->ppoll)
1655 				    ));
1656 			/* Things we can check:
1657 			 *
1658 			 * Did the poll interval change?
1659 			 * Is the poll interval in the packet in-range?
1660 			 * Did this packet arrive too soon?
1661 			 * Is the timestamp in this packet monotonic
1662 			 *  with respect to the previous packet?
1663 			 */
1664 
1665 			/* This is noteworthy, not error-worthy */
1666 			if (pkt->ppoll != peer->ppoll) {
1667 				msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %u to %u",
1668 					stoa(&rbufp->recv_srcadr),
1669 					peer->ppoll, pkt->ppoll);
1670 			}
1671 
1672 			/* This is error-worthy */
1673 			if (pkt->ppoll < peer->minpoll ||
1674 			    pkt->ppoll > peer->maxpoll  ) {
1675 				msyslog(LOG_INFO, "receive: broadcast poll of %u from %s is out-of-range (%d to %d)!",
1676 					pkt->ppoll, stoa(&rbufp->recv_srcadr),
1677 					peer->minpoll, peer->maxpoll);
1678 				++bail;
1679 			}
1680 
1681 			/* too early? worth an error, too!
1682 			 *
1683 			 * [Bug 3113] Ensure that at least one poll
1684 			 * interval has elapsed since the last **clean**
1685 			 * packet was received.  We limit the check to
1686 			 * **clean** packets to prevent replayed packets
1687 			 * and incorrectly authenticated packets, which
1688 			 * we'll discard, from being used to create a
1689 			 * denial of service condition.
1690 			 */
1691 			deadband = (1u << pkt->ppoll);
1692 			if (FLAG_BC_VOL & peer->flags)
1693 				deadband -= 3;	/* allow greater fuzz after volley */
1694 			if ((current_time - peer->timereceived) < deadband) {
1695 				msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1696 					stoa(&rbufp->recv_srcadr),
1697 					(current_time - peer->timereceived),
1698 					deadband);
1699 				++bail;
1700 			}
1701 
1702 			/* Alert if time from the server is non-monotonic.
1703 			 *
1704 			 * [Bug 3114] is about Broadcast mode replay DoS.
1705 			 *
1706 			 * Broadcast mode *assumes* a trusted network.
1707 			 * Even so, it's nice to be robust in the face
1708 			 * of attacks.
1709 			 *
1710 			 * If we get an authenticated broadcast packet
1711 			 * with an "earlier" timestamp, it means one of
1712 			 * two things:
1713 			 *
1714 			 * - the broadcast server had a backward step.
1715 			 *
1716 			 * - somebody is trying a replay attack.
1717 			 *
1718 			 * deadband: By default, we assume the broadcast
1719 			 * network is trustable, so we take our accepted
1720 			 * broadcast packets as we receive them.  But
1721 			 * some folks might want to take additional poll
1722 			 * delays before believing a backward step.
1723 			 */
1724 			if (sys_bcpollbstep) {
1725 				/* pkt->ppoll or peer->ppoll ? */
1726 				deadband = (1u << pkt->ppoll)
1727 					   * sys_bcpollbstep + 2;
1728 			} else {
1729 				deadband = 0;
1730 			}
1731 
1732 			if (L_ISZERO(&peer->bxmt)) {
1733 				tdiff.l_ui = tdiff.l_uf = 0;
1734 			} else {
1735 				tdiff = p_xmt;
1736 				L_SUB(&tdiff, &peer->bxmt);
1737 			}
1738 			if (tdiff.l_i < 0 &&
1739 			    (current_time - peer->timereceived) < deadband)
1740 			{
1741 				msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1742 					stoa(&rbufp->recv_srcadr),
1743 					peer->bxmt.l_ui, peer->bxmt.l_uf,
1744 					p_xmt.l_ui, p_xmt.l_uf
1745 					);
1746 				++bail;
1747 			}
1748 
1749 			if (bail) {
1750 				DPRINTF(2, ("receive: AM_PROCPKT drop: bail\n"));
1751 				peer->timelastrec = current_time;
1752 				sys_declined++;
1753 				return;
1754 			}
1755 		}
1756 
1757 		break;
1758 
1759 	/*
1760 	 * A passive packet matches a passive association. This is
1761 	 * usually the result of reconfiguring a client on the fly. As
1762 	 * this association might be legitimate and this packet an
1763 	 * attempt to deny service, just ignore it.
1764 	 */
1765 	case AM_ERR:
1766 		DPRINTF(2, ("receive: AM_ERR drop.\n"));
1767 		sys_declined++;
1768 		return;
1769 
1770 	/*
1771 	 * For everything else there is the bit bucket.
1772 	 */
1773 	default:
1774 		DPRINTF(2, ("receive: default drop.\n"));
1775 		sys_declined++;
1776 		return;
1777 	}
1778 
1779 #ifdef AUTOKEY
1780 	/*
1781 	 * If the association is configured for Autokey, the packet must
1782 	 * have a public key ID; if not, the packet must have a
1783 	 * symmetric key ID.
1784 	 */
1785 	if (   is_authentic != AUTH_CRYPTO
1786 	    && (   ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1787 	        || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1788 		DPRINTF(2, ("receive: drop: Autokey but wrong/bad auth\n"));
1789 		sys_badauth++;
1790 		return;
1791 	}
1792 #endif	/* AUTOKEY */
1793 
1794 	peer->received++;
1795 	peer->flash &= ~PKT_TEST_MASK;
1796 	if (peer->flags & FLAG_XBOGUS) {
1797 		peer->flags &= ~FLAG_XBOGUS;
1798 		peer->flash |= TEST3;
1799 	}
1800 
1801 	/*
1802 	 * Next comes a rigorous schedule of timestamp checking. If the
1803 	 * transmit timestamp is zero, the server has not initialized in
1804 	 * interleaved modes or is horribly broken.
1805 	 *
1806 	 * A KoD packet we pay attention to cannot have a 0 transmit
1807 	 * timestamp.
1808 	 */
1809 
1810 	kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1811 
1812 	if (L_ISZERO(&p_xmt)) {
1813 		peer->flash |= TEST3;			/* unsynch */
1814 		if (kissCode != NOKISS) {		/* KoD packet */
1815 			peer->bogusorg++;		/* for TEST2 or TEST3 */
1816 			msyslog(LOG_INFO,
1817 				"receive: Unexpected zero transmit timestamp in KoD from %s",
1818 				ntoa(&peer->srcadr));
1819 			return;
1820 		}
1821 
1822 	/*
1823 	 * If the transmit timestamp duplicates our previous one, the
1824 	 * packet is a replay. This prevents the bad guys from replaying
1825 	 * the most recent packet, authenticated or not.
1826 	 */
1827 	} else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1828 		DPRINTF(2, ("receive: drop: Duplicate xmit\n"));
1829 		peer->flash |= TEST1;			/* duplicate */
1830 		peer->oldpkt++;
1831 		return;
1832 
1833 	/*
1834 	 * If this is a broadcast mode packet, make sure hisstratum
1835 	 * is appropriate.  Don't do anything else here - we wait to
1836 	 * see if this is an interleave broadcast packet until after
1837 	 * we've validated the MAC that SHOULD be provided.
1838 	 *
1839 	 * hisstratum cannot be 0 - see assertion above.
1840 	 * If hisstratum is 15, then we'll advertise as UNSPEC but
1841 	 * at least we'll be able to sync with the broadcast server.
1842 	 */
1843 	} else if (hismode == MODE_BROADCAST) {
1844 		/* 0 is unexpected too, and impossible */
1845 		if (STRATUM_UNSPEC <= hisstratum) {
1846 			/* Is this a ++sys_declined or ??? */
1847 			msyslog(LOG_INFO,
1848 				"receive: Unexpected stratum (%d) in broadcast from %s",
1849 				hisstratum, ntoa(&peer->srcadr));
1850 			return;
1851 		}
1852 
1853 	/*
1854 	 * Basic KoD validation checking:
1855 	 *
1856 	 * KoD packets are a mixed-blessing.  Forged KoD packets
1857 	 * are DoS attacks.  There are rare situations where we might
1858 	 * get a valid KoD response, though.  Since KoD packets are
1859 	 * a special case that complicate the checks we do next, we
1860 	 * handle the basic KoD checks here.
1861 	 *
1862 	 * Note that we expect the incoming KoD packet to have its
1863 	 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1864 	 * that we have previously sent out.  Watch interleave mode.
1865 	 */
1866 	} else if (kissCode != NOKISS) {
1867 		DEBUG_INSIST(!L_ISZERO(&p_xmt));
1868 		if (   L_ISZERO(&p_org)		/* We checked p_xmt above */
1869 		    || L_ISZERO(&p_rec)) {
1870 			peer->bogusorg++;
1871 			msyslog(LOG_INFO,
1872 				"receive: KoD packet from %s has a zero org or rec timestamp.  Ignoring.",
1873 				ntoa(&peer->srcadr));
1874 			return;
1875 		}
1876 
1877 		if (   !L_ISEQU(&p_xmt, &p_org)
1878 		    || !L_ISEQU(&p_xmt, &p_rec)) {
1879 			peer->bogusorg++;
1880 			msyslog(LOG_INFO,
1881 				"receive: KoD packet from %s has inconsistent xmt/org/rec timestamps.  Ignoring.",
1882 				ntoa(&peer->srcadr));
1883 			return;
1884 		}
1885 
1886 		/* Be conservative */
1887 		if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1888 			peer->bogusorg++;
1889 			msyslog(LOG_INFO,
1890 				"receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1891 				p_org.l_ui, p_org.l_uf,
1892 				ntoa(&peer->srcadr),
1893 				peer->aorg.l_ui, peer->aorg.l_uf);
1894 			return;
1895 		} else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1896 			peer->bogusorg++;
1897 			msyslog(LOG_INFO,
1898 				"receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1899 				p_org.l_ui, p_org.l_uf,
1900 				ntoa(&peer->srcadr),
1901 				peer->borg.l_ui, peer->borg.l_uf);
1902 			return;
1903 		}
1904 
1905 	/*
1906 	 * Basic mode checks:
1907 	 *
1908 	 * If there is no origin timestamp, it's either an initial packet
1909 	 * or we've already received a response to our query.  Of course,
1910 	 * should 'aorg' be all-zero because this really was the original
1911 	 * transmit timestamp, we'll ignore this reply.  There is a window
1912 	 * of one nanosecond once every 136 years' time where this is
1913 	 * possible.  We currently ignore this situation, as a completely
1914 	 * zero timestamp is (quietly?) disallowed.
1915 	 *
1916 	 * Otherwise, check for bogus packet in basic mode.
1917 	 * If it is bogus, switch to interleaved mode and resynchronize,
1918 	 * but only after confirming the packet is not bogus in
1919 	 * symmetric interleaved mode.
1920 	 *
1921 	 * This could also mean somebody is forging packets claiming to
1922 	 * be from us, attempting to cause our server to KoD us.
1923 	 *
1924 	 * We have earlier asserted that hisstratum cannot be 0.
1925 	 * If hisstratum is STRATUM_UNSPEC, it means he's not sync'd.
1926 	 */
1927 	} else if (peer->flip == 0) {
1928 		if (0) {
1929 		} else if (L_ISZERO(&p_org)) {
1930 			const char *action;
1931 
1932 #ifdef BUG3361
1933 			msyslog(LOG_INFO,
1934 				"receive: BUG 3361: Clearing peer->aorg ");
1935 			L_CLR(&peer->aorg);
1936 #endif
1937 			/**/
1938 			switch (hismode) {
1939 			/* We allow 0org for: */
1940 			    case UCHAR_MAX:
1941 				action = "Allow";
1942 				break;
1943 			/* We disallow 0org for: */
1944 			    case MODE_UNSPEC:
1945 			    case MODE_ACTIVE:
1946 			    case MODE_PASSIVE:
1947 			    case MODE_CLIENT:
1948 			    case MODE_SERVER:
1949 			    case MODE_BROADCAST:
1950 				action = "Drop";
1951 				peer->bogusorg++;
1952 				peer->flash |= TEST2;	/* bogus */
1953 				break;
1954 			    default:
1955 				action = "";	/* for cranky compilers / MSVC */
1956 				INSIST(!"receive(): impossible hismode");
1957 				break;
1958 			}
1959 			/**/
1960 			msyslog(LOG_INFO,
1961 				"receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
1962 				action, hm_str, ntoa(&peer->srcadr),
1963 				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1964 		} else if (!L_ISEQU(&p_org, &peer->aorg)) {
1965 			/* are there cases here where we should bail? */
1966 			/* Should we set TEST2 if we decide to try xleave? */
1967 			peer->bogusorg++;
1968 			peer->flash |= TEST2;	/* bogus */
1969 			msyslog(LOG_INFO,
1970 				"receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1971 				ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1972 				peer->aorg.l_ui, peer->aorg.l_uf,
1973 				hm_str, ntoa(&peer->srcadr),
1974 				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1975 			if (  !L_ISZERO(&peer->dst)
1976 			    && L_ISEQU(&p_org, &peer->dst)) {
1977 				/* Might be the start of an interleave */
1978 				if (dynamic_interleave) {
1979 					peer->flip = 1;
1980 					report_event(PEVNT_XLEAVE, peer, NULL);
1981 				} else {
1982 					msyslog(LOG_INFO,
1983 						"receive: Dynamic interleave from %s@%s denied",
1984 						hm_str, ntoa(&peer->srcadr));
1985 				}
1986 			}
1987 		} else {
1988 			L_CLR(&peer->aorg);
1989 		}
1990 
1991 	/*
1992 	 * Check for valid nonzero timestamp fields.
1993 	 */
1994 	} else if (   L_ISZERO(&p_org)
1995 		   || L_ISZERO(&p_rec)
1996 		   || L_ISZERO(&peer->dst)) {
1997 		peer->flash |= TEST3;		/* unsynch */
1998 
1999 	/*
2000 	 * Check for bogus packet in interleaved symmetric mode. This
2001 	 * can happen if a packet is lost, duplicated or crossed. If
2002 	 * found, flip and resynchronize.
2003 	 */
2004 	} else if (   !L_ISZERO(&peer->dst)
2005 		   && !L_ISEQU(&p_org, &peer->dst)) {
2006 		DPRINTF(2, ("receive: drop: Bogus packet in interleaved symmetric mode\n"));
2007 		peer->bogusorg++;
2008 		peer->flags |= FLAG_XBOGUS;
2009 		peer->flash |= TEST2;		/* bogus */
2010 #ifdef BUG3453
2011 		return; /* Bogus packet, we are done */
2012 #endif
2013 	}
2014 
2015 	/**/
2016 
2017 	/*
2018 	 * If this is a crypto_NAK, the server cannot authenticate a
2019 	 * client packet. The server might have just changed keys. Clear
2020 	 * the association and restart the protocol.
2021 	 */
2022 	if (crypto_nak_test == VALIDNAK) {
2023 		report_event(PEVNT_AUTH, peer, "crypto_NAK");
2024 		peer->flash |= TEST5;		/* bad auth */
2025 		peer->badauth++;
2026 		if (peer->flags & FLAG_PREEMPT) {
2027 			if (unpeer_crypto_nak_early) {
2028 				unpeer(peer);
2029 			}
2030 			DPRINTF(2, ("receive: drop: PREEMPT crypto_NAK\n"));
2031 			return;
2032 		}
2033 #ifdef AUTOKEY
2034 		if (peer->crypto) {
2035 			peer_clear(peer, "AUTH");
2036 		}
2037 #endif	/* AUTOKEY */
2038 		DPRINTF(2, ("receive: drop: crypto_NAK\n"));
2039 		return;
2040 
2041 	/*
2042 	 * If the digest fails or it's missing for authenticated
2043 	 * associations, the client cannot authenticate a server
2044 	 * reply to a client packet previously sent. The loopback check
2045 	 * is designed to avoid a bait-and-switch attack, which was
2046 	 * possible in past versions. If symmetric modes, return a
2047 	 * crypto-NAK. The peer should restart the protocol.
2048 	 */
2049 	} else if (!AUTH(peer->keyid || has_mac ||
2050 			 (restrict_mask & RES_DONTTRUST), is_authentic)) {
2051 
2052 		if (peer->flash & PKT_TEST_MASK) {
2053 			msyslog(LOG_INFO,
2054 				"receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
2055 				ntoa(&peer->srcadr));
2056 			return;
2057 		}
2058 
2059 		report_event(PEVNT_AUTH, peer, "digest");
2060 		peer->flash |= TEST5;		/* bad auth */
2061 		peer->badauth++;
2062 		if (   has_mac
2063 		    && (   hismode == MODE_ACTIVE
2064 			|| hismode == MODE_PASSIVE))
2065 			fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
2066 		if (peer->flags & FLAG_PREEMPT) {
2067 			if (unpeer_digest_early) {
2068 				unpeer(peer);
2069 			}
2070 		}
2071 #ifdef AUTOKEY
2072 		else if (peer_clear_digest_early && peer->crypto) {
2073 			peer_clear(peer, "AUTH");
2074 		}
2075 #endif	/* AUTOKEY */
2076 		DPRINTF(2, ("receive: drop: Bad or missing AUTH\n"));
2077 		return;
2078 	}
2079 
2080 	/*
2081 	 * For broadcast packets:
2082 	 *
2083 	 * HMS: This next line never made much sense to me, even
2084 	 * when it was up higher:
2085 	 *   If an initial volley, bail out now and let the
2086 	 *   client do its stuff.
2087 	 *
2088 	 * If the packet has not failed authentication, then
2089 	 * - if the origin timestamp is nonzero this is an
2090 	 *   interleaved broadcast, so restart the protocol.
2091 	 * - else, this is not an interleaved broadcast packet.
2092 	 */
2093 	if (hismode == MODE_BROADCAST) {
2094 		if (   is_authentic == AUTH_OK
2095 		    || is_authentic == AUTH_NONE) {
2096 			if (!L_ISZERO(&p_org)) {
2097 				if (!(peer->flags & FLAG_XB)) {
2098 					msyslog(LOG_INFO,
2099 						"receive: Broadcast server at %s is in interleave mode",
2100 						ntoa(&peer->srcadr));
2101 					peer->flags |= FLAG_XB;
2102 					peer->aorg = p_xmt;
2103 					peer->borg = rbufp->recv_time;
2104 					report_event(PEVNT_XLEAVE, peer, NULL);
2105 					return;
2106 				}
2107 			} else if (peer->flags & FLAG_XB) {
2108 				msyslog(LOG_INFO,
2109 					"receive: Broadcast server at %s is no longer in interleave mode",
2110 					ntoa(&peer->srcadr));
2111 				peer->flags &= ~FLAG_XB;
2112 			}
2113 		} else {
2114 			msyslog(LOG_INFO,
2115 				"receive: Bad broadcast auth (%d) from %s",
2116 				is_authentic, ntoa(&peer->srcadr));
2117 		}
2118 
2119 		/*
2120 		 * Now that we know the packet is correctly authenticated,
2121 		 * update peer->bxmt.
2122 		 */
2123 		peer->bxmt = p_xmt;
2124 	}
2125 
2126 
2127 	/*
2128 	** Update the state variables.
2129 	*/
2130 	if (peer->flip == 0) {
2131 		if (hismode != MODE_BROADCAST)
2132 			peer->rec = p_xmt;
2133 		peer->dst = rbufp->recv_time;
2134 	}
2135 	peer->xmt = p_xmt;
2136 
2137 	/*
2138 	 * Set the peer ppoll to the maximum of the packet ppoll and the
2139 	 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
2140 	 * this maximum and advance the headway to give the sender some
2141 	 * headroom. Very intricate.
2142 	 */
2143 
2144 	/*
2145 	 * Check for any kiss codes. Note this is only used when a server
2146 	 * responds to a packet request.
2147 	 */
2148 
2149 	/*
2150 	 * Check to see if this is a RATE Kiss Code
2151 	 * Currently this kiss code will accept whatever poll
2152 	 * rate that the server sends
2153 	 */
2154 	peer->ppoll = max(peer->minpoll, pkt->ppoll);
2155 	if (kissCode == RATEKISS) {
2156 		peer->selbroken++;	/* Increment the KoD count */
2157 		report_event(PEVNT_RATE, peer, NULL);
2158 		if (pkt->ppoll > peer->minpoll)
2159 			peer->minpoll = peer->ppoll;
2160 		peer->burst = peer->retry = 0;
2161 		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
2162 		poll_update(peer, pkt->ppoll);
2163 		return;				/* kiss-o'-death */
2164 	}
2165 	if (kissCode != NOKISS) {
2166 		peer->selbroken++;	/* Increment the KoD count */
2167 		return;		/* Drop any other kiss code packets */
2168 	}
2169 
2170 
2171 	/*
2172 	 * XXX
2173 	 */
2174 
2175 
2176 	/*
2177 	 * If:
2178 	 *	- this is a *cast (uni-, broad-, or m-) server packet
2179 	 *	- and it's symmetric-key authenticated
2180 	 * then see if the sender's IP is trusted for this keyid.
2181 	 * If it is, great - nothing special to do here.
2182 	 * Otherwise, we should report and bail.
2183 	 *
2184 	 * Autokey-authenticated packets are accepted.
2185 	 */
2186 
2187 	switch (hismode) {
2188 	    case MODE_SERVER:		/* server mode */
2189 	    case MODE_BROADCAST:	/* broadcast mode */
2190 	    case MODE_ACTIVE:		/* symmetric active mode */
2191 	    case MODE_PASSIVE:		/* symmetric passive mode */
2192 		if (   is_authentic == AUTH_OK
2193 		    && skeyid
2194 		    && skeyid <= NTP_MAXKEY
2195 		    && !authistrustedip(skeyid, &peer->srcadr)) {
2196 			report_event(PEVNT_AUTH, peer, "authIP");
2197 			peer->badauth++;
2198 			return;
2199 		}
2200 		break;
2201 
2202 	    case MODE_CLIENT:		/* client mode */
2203 #if 0		/* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
2204 	    case MODE_CONTROL:		/* control mode */
2205 #endif
2206 	    case MODE_PRIVATE:		/* private mode */
2207 	    case MODE_BCLIENT:		/* broadcast client mode */
2208 		break;
2209 
2210 	    case MODE_UNSPEC:		/* unspecified (old version) */
2211 	    default:
2212 		msyslog(LOG_INFO,
2213 			"receive: Unexpected mode (%d) in packet from %s",
2214 			hismode, ntoa(&peer->srcadr));
2215 		break;
2216 	}
2217 
2218 
2219 	/*
2220 	 * That was hard and I am sweaty, but the packet is squeaky
2221 	 * clean. Get on with real work.
2222 	 */
2223 	peer->timereceived = current_time;
2224 	peer->timelastrec = current_time;
2225 	if (is_authentic == AUTH_OK)
2226 		peer->flags |= FLAG_AUTHENTIC;
2227 	else
2228 		peer->flags &= ~FLAG_AUTHENTIC;
2229 
2230 #ifdef AUTOKEY
2231 	/*
2232 	 * More autokey dance. The rules of the cha-cha are as follows:
2233 	 *
2234 	 * 1. If there is no key or the key is not auto, do nothing.
2235 	 *
2236 	 * 2. If this packet is in response to the one just previously
2237 	 *    sent or from a broadcast server, do the extension fields.
2238 	 *    Otherwise, assume bogosity and bail out.
2239 	 *
2240 	 * 3. If an extension field contains a verified signature, it is
2241 	 *    self-authenticated and we sit the dance.
2242 	 *
2243 	 * 4. If this is a server reply, check only to see that the
2244 	 *    transmitted key ID matches the received key ID.
2245 	 *
2246 	 * 5. Check to see that one or more hashes of the current key ID
2247 	 *    matches the previous key ID or ultimate original key ID
2248 	 *    obtained from the broadcaster or symmetric peer. If no
2249 	 *    match, sit the dance and call for new autokey values.
2250 	 *
2251 	 * In case of crypto error, fire the orchestra, stop dancing and
2252 	 * restart the protocol.
2253 	 */
2254 	if (peer->flags & FLAG_SKEY) {
2255 		/*
2256 		 * Decrement remaining autokey hashes. This isn't
2257 		 * perfect if a packet is lost, but results in no harm.
2258 		 */
2259 		ap = (struct autokey *)peer->recval.ptr;
2260 		if (ap != NULL) {
2261 			if (ap->seq > 0)
2262 				ap->seq--;
2263 		}
2264 		peer->flash |= TEST8;
2265 		rval = crypto_recv(peer, rbufp);
2266 		if (rval == XEVNT_OK) {
2267 			peer->unreach = 0;
2268 		} else {
2269 			if (rval == XEVNT_ERR) {
2270 				report_event(PEVNT_RESTART, peer,
2271 				    "crypto error");
2272 				peer_clear(peer, "CRYP");
2273 				peer->flash |= TEST9;	/* bad crypt */
2274 				if (peer->flags & FLAG_PREEMPT) {
2275 					if (unpeer_crypto_early) {
2276 						unpeer(peer);
2277 					}
2278 				}
2279 			}
2280 			return;
2281 		}
2282 
2283 		/*
2284 		 * If server mode, verify the receive key ID matches
2285 		 * the transmit key ID.
2286 		 */
2287 		if (hismode == MODE_SERVER) {
2288 			if (skeyid == peer->keyid)
2289 				peer->flash &= ~TEST8;
2290 
2291 		/*
2292 		 * If an extension field is present, verify only that it
2293 		 * has been correctly signed. We don't need a sequence
2294 		 * check here, but the sequence continues.
2295 		 */
2296 		} else if (!(peer->flash & TEST8)) {
2297 			peer->pkeyid = skeyid;
2298 
2299 		/*
2300 		 * Now the fun part. Here, skeyid is the current ID in
2301 		 * the packet, pkeyid is the ID in the last packet and
2302 		 * tkeyid is the hash of skeyid. If the autokey values
2303 		 * have not been received, this is an automatic error.
2304 		 * If so, check that the tkeyid matches pkeyid. If not,
2305 		 * hash tkeyid and try again. If the number of hashes
2306 		 * exceeds the number remaining in the sequence, declare
2307 		 * a successful failure and refresh the autokey values.
2308 		 */
2309 		} else if (ap != NULL) {
2310 			int i;
2311 
2312 			for (i = 0; ; i++) {
2313 				if (   tkeyid == peer->pkeyid
2314 				    || tkeyid == ap->key) {
2315 					peer->flash &= ~TEST8;
2316 					peer->pkeyid = skeyid;
2317 					ap->seq -= i;
2318 					break;
2319 				}
2320 				if (i > ap->seq) {
2321 					peer->crypto &=
2322 					    ~CRYPTO_FLAG_AUTO;
2323 					break;
2324 				}
2325 				tkeyid = session_key(
2326 				    &rbufp->recv_srcadr, dstadr_sin,
2327 				    tkeyid, pkeyid, 0);
2328 			}
2329 			if (peer->flash & TEST8)
2330 				report_event(PEVNT_AUTH, peer, "keylist");
2331 		}
2332 		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2333 			peer->flash |= TEST8;	/* bad autokey */
2334 
2335 		/*
2336 		 * The maximum lifetime of the protocol is about one
2337 		 * week before restarting the Autokey protocol to
2338 		 * refresh certificates and leapseconds values.
2339 		 */
2340 		if (current_time > peer->refresh) {
2341 			report_event(PEVNT_RESTART, peer,
2342 			    "crypto refresh");
2343 			peer_clear(peer, "TIME");
2344 			return;
2345 		}
2346 	}
2347 #endif	/* AUTOKEY */
2348 
2349 	/*
2350 	 * The dance is complete and the flash bits have been lit. Toss
2351 	 * the packet over the fence for processing, which may light up
2352 	 * more flashers.
2353 	 */
2354 	process_packet(peer, pkt, rbufp->recv_length);
2355 
2356 	/*
2357 	 * In interleaved mode update the state variables. Also adjust the
2358 	 * transmit phase to avoid crossover.
2359 	 */
2360 	if (peer->flip != 0) {
2361 		peer->rec = p_rec;
2362 		peer->dst = rbufp->recv_time;
2363 		if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2364 		    peer->hpoll)) / 2)
2365 			peer->nextdate++;
2366 		else
2367 			peer->nextdate--;
2368 	}
2369 }
2370 
2371 
2372 /*
2373  * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2374  *	Or almost, at least.  If we're in here we have a reasonable
2375  *	expectation that we will be having a long term
2376  *	relationship with this host.
2377  */
2378 void
2379 process_packet(
2380 	register struct peer *peer,
2381 	register struct pkt *pkt,
2382 	u_int	len
2383 	)
2384 {
2385 	double	t34, t21;
2386 	double	p_offset, p_del, p_disp;
2387 	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
2388 	u_char	pmode, pleap, pversion, pstratum;
2389 	char	statstr[NTP_MAXSTRLEN];
2390 #ifdef ASSYM
2391 	int	itemp;
2392 	double	etemp, ftemp, td;
2393 #endif /* ASSYM */
2394 
2395 #if 0
2396 	sys_processed++;
2397 	peer->processed++;
2398 #endif
2399 	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2400 	p_offset = 0;
2401 	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
2402 	NTOHL_FP(&pkt->reftime, &p_reftime);
2403 	NTOHL_FP(&pkt->org, &p_org);
2404 	NTOHL_FP(&pkt->rec, &p_rec);
2405 	NTOHL_FP(&pkt->xmt, &p_xmt);
2406 	pmode = PKT_MODE(pkt->li_vn_mode);
2407 	pleap = PKT_LEAP(pkt->li_vn_mode);
2408 	pversion = PKT_VERSION(pkt->li_vn_mode);
2409 	pstratum = PKT_TO_STRATUM(pkt->stratum);
2410 
2411 	/**/
2412 
2413 	/**/
2414 
2415 	/*
2416 	 * Verify the server is synchronized; that is, the leap bits,
2417 	 * stratum and root distance are valid.
2418 	 */
2419 	if (   pleap == LEAP_NOTINSYNC		/* test 6 */
2420 	    || pstratum < sys_floor || pstratum >= sys_ceiling)
2421 		peer->flash |= TEST6;		/* bad synch or strat */
2422 	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
2423 		peer->flash |= TEST7;		/* bad header */
2424 
2425 	/*
2426 	 * If any tests fail at this point, the packet is discarded.
2427 	 * Note that some flashers may have already been set in the
2428 	 * receive() routine.
2429 	 */
2430 	if (peer->flash & PKT_TEST_MASK) {
2431 		peer->seldisptoolarge++;
2432 		DPRINTF(1, ("packet: flash header %04x\n",
2433 			    peer->flash));
2434 		return;
2435 	}
2436 
2437 	/**/
2438 
2439 #if 1
2440 	sys_processed++;
2441 	peer->processed++;
2442 #endif
2443 
2444 	/*
2445 	 * Capture the header values in the client/peer association..
2446 	 */
2447 	record_raw_stats(&peer->srcadr,
2448 	    peer->dstadr ? &peer->dstadr->sin : NULL,
2449 	    &p_org, &p_rec, &p_xmt, &peer->dst,
2450 	    pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2451 	    p_del, p_disp, pkt->refid,
2452 	    len - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
2453 	peer->leap = pleap;
2454 	peer->stratum = min(pstratum, STRATUM_UNSPEC);
2455 	peer->pmode = pmode;
2456 	peer->precision = pkt->precision;
2457 	peer->rootdelay = p_del;
2458 	peer->rootdisp = p_disp;
2459 	peer->refid = pkt->refid;		/* network byte order */
2460 	peer->reftime = p_reftime;
2461 
2462 	/*
2463 	 * First, if either burst mode is armed, enable the burst.
2464 	 * Compute the headway for the next packet and delay if
2465 	 * necessary to avoid exceeding the threshold.
2466 	 */
2467 	if (peer->retry > 0) {
2468 		peer->retry = 0;
2469 		if (peer->reach)
2470 			peer->burst = min(1 << (peer->hpoll -
2471 			    peer->minpoll), NTP_SHIFT) - 1;
2472 		else
2473 			peer->burst = NTP_IBURST - 1;
2474 		if (peer->burst > 0)
2475 			peer->nextdate = current_time;
2476 	}
2477 	poll_update(peer, peer->hpoll);
2478 
2479 	/**/
2480 
2481 	/*
2482 	 * If the peer was previously unreachable, raise a trap. In any
2483 	 * case, mark it reachable.
2484 	 */
2485 	if (!peer->reach) {
2486 		report_event(PEVNT_REACH, peer, NULL);
2487 		peer->timereachable = current_time;
2488 	}
2489 	peer->reach |= 1;
2490 
2491 	/*
2492 	 * For a client/server association, calculate the clock offset,
2493 	 * roundtrip delay and dispersion. The equations are reordered
2494 	 * from the spec for more efficient use of temporaries. For a
2495 	 * broadcast association, offset the last measurement by the
2496 	 * computed delay during the client/server volley. Note the
2497 	 * computation of dispersion includes the system precision plus
2498 	 * that due to the frequency error since the origin time.
2499 	 *
2500 	 * It is very important to respect the hazards of overflow. The
2501 	 * only permitted operation on raw timestamps is subtraction,
2502 	 * where the result is a signed quantity spanning from 68 years
2503 	 * in the past to 68 years in the future. To avoid loss of
2504 	 * precision, these calculations are done using 64-bit integer
2505 	 * arithmetic. However, the offset and delay calculations are
2506 	 * sums and differences of these first-order differences, which
2507 	 * if done using 64-bit integer arithmetic, would be valid over
2508 	 * only half that span. Since the typical first-order
2509 	 * differences are usually very small, they are converted to 64-
2510 	 * bit doubles and all remaining calculations done in floating-
2511 	 * double arithmetic. This preserves the accuracy while
2512 	 * retaining the 68-year span.
2513 	 *
2514 	 * There are three interleaving schemes, basic, interleaved
2515 	 * symmetric and interleaved broadcast. The timestamps are
2516 	 * idioscyncratically different. See the onwire briefing/white
2517 	 * paper at www.eecis.udel.edu/~mills for details.
2518 	 *
2519 	 * Interleaved symmetric mode
2520 	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2521 	 * t4 = peer->dst
2522 	 */
2523 	if (peer->flip != 0) {
2524 		ci = p_xmt;				/* t3 - t4 */
2525 		L_SUB(&ci, &peer->dst);
2526 		LFPTOD(&ci, t34);
2527 		ci = p_rec;				/* t2 - t1 */
2528 		if (peer->flip > 0)
2529 			L_SUB(&ci, &peer->borg);
2530 		else
2531 			L_SUB(&ci, &peer->aorg);
2532 		LFPTOD(&ci, t21);
2533 		p_del = t21 - t34;
2534 		p_offset = (t21 + t34) / 2.;
2535 		if (p_del < 0 || p_del > 1.) {
2536 			snprintf(statstr, sizeof(statstr),
2537 			    "t21 %.6f t34 %.6f", t21, t34);
2538 			report_event(PEVNT_XERR, peer, statstr);
2539 			return;
2540 		}
2541 
2542 	/*
2543 	 * Broadcast modes
2544 	 */
2545 	} else if (peer->pmode == MODE_BROADCAST) {
2546 
2547 		/*
2548 		 * Interleaved broadcast mode. Use interleaved timestamps.
2549 		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2550 		 */
2551 		if (peer->flags & FLAG_XB) {
2552 			ci = p_org;			/* delay */
2553 			L_SUB(&ci, &peer->aorg);
2554 			LFPTOD(&ci, t34);
2555 			ci = p_org;			/* t2 - t1 */
2556 			L_SUB(&ci, &peer->borg);
2557 			LFPTOD(&ci, t21);
2558 			peer->aorg = p_xmt;
2559 			peer->borg = peer->dst;
2560 			if (t34 < 0 || t34 > 1.) {
2561 				/* drop all if in the initial volley */
2562 				if (FLAG_BC_VOL & peer->flags)
2563 					goto bcc_init_volley_fail;
2564 				snprintf(statstr, sizeof(statstr),
2565 				    "offset %.6f delay %.6f", t21, t34);
2566 				report_event(PEVNT_XERR, peer, statstr);
2567 				return;
2568 			}
2569 			p_offset = t21;
2570 			peer->xleave = t34;
2571 
2572 		/*
2573 		 * Basic broadcast - use direct timestamps.
2574 		 * t3 = p_xmt, t4 = peer->dst
2575 		 */
2576 		} else {
2577 			ci = p_xmt;		/* t3 - t4 */
2578 			L_SUB(&ci, &peer->dst);
2579 			LFPTOD(&ci, t34);
2580 			p_offset = t34;
2581 		}
2582 
2583 		/*
2584 		 * When calibration is complete and the clock is
2585 		 * synchronized, the bias is calculated as the difference
2586 		 * between the unicast timestamp and the broadcast
2587 		 * timestamp. This works for both basic and interleaved
2588 		 * modes.
2589 		 * [Bug 3031] Don't keep this peer when the delay
2590 		 * calculation gives reason to suspect clock steps.
2591 		 * This is assumed for delays > 50ms.
2592 		 */
2593 		if (FLAG_BC_VOL & peer->flags) {
2594 			peer->flags &= ~FLAG_BC_VOL;
2595 			peer->delay = fabs(peer->offset - p_offset) * 2;
2596 			DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2597 				peer->delay));
2598 			if (peer->delay > fabs(sys_bdelay)) {
2599 		bcc_init_volley_fail:
2600 				DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2601 				unpeer(peer);
2602 				return;
2603 			}
2604 		}
2605 		peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2606 		p_del = peer->delay;
2607 		p_offset += p_del / 2;
2608 
2609 
2610 	/*
2611 	 * Basic mode, otherwise known as the old fashioned way.
2612 	 *
2613 	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2614 	 */
2615 	} else {
2616 		ci = p_xmt;				/* t3 - t4 */
2617 		L_SUB(&ci, &peer->dst);
2618 		LFPTOD(&ci, t34);
2619 		ci = p_rec;				/* t2 - t1 */
2620 		L_SUB(&ci, &p_org);
2621 		LFPTOD(&ci, t21);
2622 		p_del = fabs(t21 - t34);
2623 		p_offset = (t21 + t34) / 2.;
2624 	}
2625 	p_del = max(p_del, LOGTOD(sys_precision));
2626 	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2627 	    clock_phi * p_del;
2628 
2629 #if ASSYM
2630 	/*
2631 	 * This code calculates the outbound and inbound data rates by
2632 	 * measuring the differences between timestamps at different
2633 	 * packet lengths. This is helpful in cases of large asymmetric
2634 	 * delays commonly experienced on deep space communication
2635 	 * links.
2636 	 */
2637 	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2638 		itemp = peer->t21_bytes - peer->t21_last;
2639 		if (itemp > 25) {
2640 			etemp = t21 - peer->t21;
2641 			if (fabs(etemp) > 1e-6) {
2642 				ftemp = itemp / etemp;
2643 				if (ftemp > 1000.)
2644 					peer->r21 = ftemp;
2645 			}
2646 		}
2647 		itemp = len - peer->t34_bytes;
2648 		if (itemp > 25) {
2649 			etemp = -t34 - peer->t34;
2650 			if (fabs(etemp) > 1e-6) {
2651 				ftemp = itemp / etemp;
2652 				if (ftemp > 1000.)
2653 					peer->r34 = ftemp;
2654 			}
2655 		}
2656 	}
2657 
2658 	/*
2659 	 * The following section compensates for different data rates on
2660 	 * the outbound (d21) and inbound (t34) directions. To do this,
2661 	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2662 	 * the roundtrip delay. Then it calculates the correction as a
2663 	 * fraction of d.
2664 	 */
2665 	peer->t21 = t21;
2666 	peer->t21_last = peer->t21_bytes;
2667 	peer->t34 = -t34;
2668 	peer->t34_bytes = len;
2669 	DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2670 		    peer->t21_bytes, peer->t34, peer->t34_bytes));
2671 	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2672 		if (peer->pmode != MODE_BROADCAST)
2673 			td = (peer->r34 / (peer->r21 + peer->r34) -
2674 			    .5) * p_del;
2675 		else
2676 			td = 0;
2677 
2678 		/*
2679 		 * Unfortunately, in many cases the errors are
2680 		 * unacceptable, so for the present the rates are not
2681 		 * used. In future, we might find conditions where the
2682 		 * calculations are useful, so this should be considered
2683 		 * a work in progress.
2684 		 */
2685 		t21 -= td;
2686 		t34 -= td;
2687 		DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2688 			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2689 			    td));
2690 	}
2691 #endif /* ASSYM */
2692 
2693 	/*
2694 	 * That was awesome. Now hand off to the clock filter.
2695 	 */
2696 	clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2697 
2698 	/*
2699 	 * If we are in broadcast calibrate mode, return to broadcast
2700 	 * client mode when the client is fit and the autokey dance is
2701 	 * complete.
2702 	 */
2703 	if (   (FLAG_BC_VOL & peer->flags)
2704 	    && MODE_CLIENT == peer->hmode
2705 	    && !(TEST11 & peer_unfit(peer))) {	/* distance exceeded */
2706 #ifdef AUTOKEY
2707 		if (peer->flags & FLAG_SKEY) {
2708 			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2709 				peer->hmode = MODE_BCLIENT;
2710 		} else {
2711 			peer->hmode = MODE_BCLIENT;
2712 		}
2713 #else	/* !AUTOKEY follows */
2714 		peer->hmode = MODE_BCLIENT;
2715 #endif	/* !AUTOKEY */
2716 	}
2717 }
2718 
2719 
2720 /*
2721  * clock_update - Called at system process update intervals.
2722  */
2723 static void
2724 clock_update(
2725 	struct peer *peer	/* peer structure pointer */
2726 	)
2727 {
2728 	double	dtemp;
2729 	l_fp	now;
2730 #ifdef HAVE_LIBSCF_H
2731 	char	*fmri;
2732 #endif /* HAVE_LIBSCF_H */
2733 
2734 	/*
2735 	 * Update the system state variables. We do this very carefully,
2736 	 * as the poll interval might need to be clamped differently.
2737 	 */
2738 	sys_peer = peer;
2739 	sys_epoch = peer->epoch;
2740 	if (sys_poll < peer->minpoll)
2741 		sys_poll = peer->minpoll;
2742 	if (sys_poll > peer->maxpoll)
2743 		sys_poll = peer->maxpoll;
2744 	poll_update(peer, sys_poll);
2745 	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2746 	if (   peer->stratum == STRATUM_REFCLOCK
2747 	    || peer->stratum == STRATUM_UNSPEC)
2748 		sys_refid = peer->refid;
2749 	else
2750 		sys_refid = addr2refid(&peer->srcadr);
2751 	/*
2752 	 * Root Dispersion (E) is defined (in RFC 5905) as:
2753 	 *
2754 	 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2755 	 *
2756 	 * where:
2757 	 *  p.epsilon_r is the PollProc's root dispersion
2758 	 *  p.epsilon   is the PollProc's dispersion
2759 	 *  p.psi       is the PollProc's jitter
2760 	 *  THETA       is the combined offset
2761 	 *
2762 	 * NB: Think Hard about where these numbers come from and
2763 	 * what they mean.  When did peer->update happen?  Has anything
2764 	 * interesting happened since then?  What values are the most
2765 	 * defensible?  Why?
2766 	 *
2767 	 * DLM thinks this equation is probably the best of all worse choices.
2768 	 */
2769 	dtemp	= peer->rootdisp
2770 		+ peer->disp
2771 		+ sys_jitter
2772 		+ clock_phi * (current_time - peer->update)
2773 		+ fabs(sys_offset);
2774 
2775 	if (dtemp > sys_mindisp)
2776 		sys_rootdisp = dtemp;
2777 	else
2778 		sys_rootdisp = sys_mindisp;
2779 	sys_rootdelay = peer->delay + peer->rootdelay;
2780 	sys_reftime = peer->dst;
2781 
2782 	DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2783 		    current_time, peer->epoch, peer->associd));
2784 
2785 	/*
2786 	 * Comes now the moment of truth. Crank the clock discipline and
2787 	 * see what comes out.
2788 	 */
2789 	switch (local_clock(peer, sys_offset)) {
2790 
2791 	/*
2792 	 * Clock exceeds panic threshold. Life as we know it ends.
2793 	 */
2794 	case -1:
2795 #ifdef HAVE_LIBSCF_H
2796 		/*
2797 		 * For Solaris enter the maintenance mode.
2798 		 */
2799 		if ((fmri = getenv("SMF_FMRI")) != NULL) {
2800 			if (smf_maintain_instance(fmri, 0) < 0) {
2801 				printf("smf_maintain_instance: %s\n",
2802 				    scf_strerror(scf_error()));
2803 				exit(1);
2804 			}
2805 			/*
2806 			 * Sleep until SMF kills us.
2807 			 */
2808 			for (;;)
2809 				pause();
2810 		}
2811 #endif /* HAVE_LIBSCF_H */
2812 		exit (-1);
2813 		/* not reached */
2814 
2815 	/*
2816 	 * Clock was stepped. Flush all time values of all peers.
2817 	 */
2818 	case 2:
2819 		clear_all();
2820 		set_sys_leap(LEAP_NOTINSYNC);
2821 		sys_stratum = STRATUM_UNSPEC;
2822 		memcpy(&sys_refid, "STEP", 4);
2823 		sys_rootdelay = 0;
2824 		sys_rootdisp = 0;
2825 		L_CLR(&sys_reftime);
2826 		sys_jitter = LOGTOD(sys_precision);
2827 		leapsec_reset_frame();
2828 		break;
2829 
2830 	/*
2831 	 * Clock was slewed. Handle the leapsecond stuff.
2832 	 */
2833 	case 1:
2834 
2835 		/*
2836 		 * If this is the first time the clock is set, reset the
2837 		 * leap bits. If crypto, the timer will goose the setup
2838 		 * process.
2839 		 */
2840 		if (sys_leap == LEAP_NOTINSYNC) {
2841 			set_sys_leap(LEAP_NOWARNING);
2842 #ifdef AUTOKEY
2843 			if (crypto_flags)
2844 				crypto_update();
2845 #endif	/* AUTOKEY */
2846 			/*
2847 			 * If our parent process is waiting for the
2848 			 * first clock sync, send them home satisfied.
2849 			 */
2850 #ifdef HAVE_WORKING_FORK
2851 			if (waitsync_fd_to_close != -1) {
2852 				close(waitsync_fd_to_close);
2853 				waitsync_fd_to_close = -1;
2854 				DPRINTF(1, ("notified parent --wait-sync is done\n"));
2855 			}
2856 #endif /* HAVE_WORKING_FORK */
2857 
2858 		}
2859 
2860 		/*
2861 		 * If there is no leap second pending and the number of
2862 		 * survivor leap bits is greater than half the number of
2863 		 * survivors, try to schedule a leap for the end of the
2864 		 * current month. (This only works if no leap second for
2865 		 * that range is in the table, so doing this more than
2866 		 * once is mostly harmless.)
2867 		 */
2868 		if (leapsec == LSPROX_NOWARN) {
2869 			if (   leap_vote_ins > leap_vote_del
2870 			    && leap_vote_ins > sys_survivors / 2) {
2871 				get_systime(&now);
2872 				leapsec_add_dyn(TRUE, now.l_ui, NULL);
2873 			}
2874 			if (   leap_vote_del > leap_vote_ins
2875 			    && leap_vote_del > sys_survivors / 2) {
2876 				get_systime(&now);
2877 				leapsec_add_dyn(FALSE, now.l_ui, NULL);
2878 			}
2879 		}
2880 		break;
2881 
2882 	/*
2883 	 * Popcorn spike or step threshold exceeded. Pretend it never
2884 	 * happened.
2885 	 */
2886 	default:
2887 		break;
2888 	}
2889 }
2890 
2891 
2892 /*
2893  * poll_update - update peer poll interval
2894  */
2895 void
2896 poll_update(
2897 	struct peer *peer,	/* peer structure pointer */
2898 	u_char	mpoll
2899 	)
2900 {
2901 	u_long	next, utemp;
2902 	u_char	hpoll;
2903 
2904 	/*
2905 	 * This routine figures out when the next poll should be sent.
2906 	 * That turns out to be wickedly complicated. One problem is
2907 	 * that sometimes the time for the next poll is in the past when
2908 	 * the poll interval is reduced. We watch out for races here
2909 	 * between the receive process and the poll process.
2910 	 *
2911 	 * Clamp the poll interval between minpoll and maxpoll.
2912 	 */
2913 	hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2914 
2915 #ifdef AUTOKEY
2916 	/*
2917 	 * If during the crypto protocol the poll interval has changed,
2918 	 * the lifetimes in the key list are probably bogus. Purge the
2919 	 * the key list and regenerate it later.
2920 	 */
2921 	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2922 		key_expire(peer);
2923 #endif	/* AUTOKEY */
2924 	peer->hpoll = hpoll;
2925 
2926 	/*
2927 	 * There are three variables important for poll scheduling, the
2928 	 * current time (current_time), next scheduled time (nextdate)
2929 	 * and the earliest time (utemp). The earliest time is 2 s
2930 	 * seconds, but could be more due to rate management. When
2931 	 * sending in a burst, use the earliest time. When not in a
2932 	 * burst but with a reply pending, send at the earliest time
2933 	 * unless the next scheduled time has not advanced. This can
2934 	 * only happen if multiple replies are pending in the same
2935 	 * response interval. Otherwise, send at the later of the next
2936 	 * scheduled time and the earliest time.
2937 	 *
2938 	 * Now we figure out if there is an override. If a burst is in
2939 	 * progress and we get called from the receive process, just
2940 	 * slink away. If called from the poll process, delay 1 s for a
2941 	 * reference clock, otherwise 2 s.
2942 	 */
2943 	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2944 	    (1 << peer->minpoll), ntp_minpkt);
2945 	if (peer->burst > 0) {
2946 		if (peer->nextdate > current_time)
2947 			return;
2948 #ifdef REFCLOCK
2949 		else if (peer->flags & FLAG_REFCLOCK)
2950 			peer->nextdate = current_time + RESP_DELAY;
2951 #endif /* REFCLOCK */
2952 		else
2953 			peer->nextdate = utemp;
2954 
2955 #ifdef AUTOKEY
2956 	/*
2957 	 * If a burst is not in progress and a crypto response message
2958 	 * is pending, delay 2 s, but only if this is a new interval.
2959 	 */
2960 	} else if (peer->cmmd != NULL) {
2961 		if (peer->nextdate > current_time) {
2962 			if (peer->nextdate + ntp_minpkt != utemp)
2963 				peer->nextdate = utemp;
2964 		} else {
2965 			peer->nextdate = utemp;
2966 		}
2967 #endif	/* AUTOKEY */
2968 
2969 	/*
2970 	 * The ordinary case. If a retry, use minpoll; if unreachable,
2971 	 * use host poll; otherwise, use the minimum of host and peer
2972 	 * polls; In other words, oversampling is okay but
2973 	 * understampling is evil. Use the maximum of this value and the
2974 	 * headway. If the average headway is greater than the headway
2975 	 * threshold, increase the headway by the minimum interval.
2976 	 */
2977 	} else {
2978 		if (peer->retry > 0)
2979 			hpoll = peer->minpoll;
2980 		else if (!(peer->reach))
2981 			hpoll = peer->hpoll;
2982 		else
2983 			hpoll = min(peer->ppoll, peer->hpoll);
2984 #ifdef REFCLOCK
2985 		if (peer->flags & FLAG_REFCLOCK)
2986 			next = 1 << hpoll;
2987 		else
2988 #endif /* REFCLOCK */
2989 			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2990 			    hpoll) >> 12;
2991 		next += peer->outdate;
2992 		if (next > utemp)
2993 			peer->nextdate = next;
2994 		else
2995 			peer->nextdate = utemp;
2996 		if (peer->throttle > (1 << peer->minpoll))
2997 			peer->nextdate += ntp_minpkt;
2998 	}
2999 	DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
3000 		    current_time, ntoa(&peer->srcadr), peer->hpoll,
3001 		    peer->burst, peer->retry, peer->throttle,
3002 		    utemp - current_time, peer->nextdate -
3003 		    current_time));
3004 }
3005 
3006 
3007 /*
3008  * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
3009  * spec.
3010  */
3011 void
3012 peer_clear(
3013 	struct peer *peer,		/* peer structure */
3014 	const char *ident		/* tally lights */
3015 	)
3016 {
3017 	u_char	u;
3018 	l_fp	bxmt = peer->bxmt;	/* bcast clients retain this! */
3019 
3020 #ifdef AUTOKEY
3021 	/*
3022 	 * If cryptographic credentials have been acquired, toss them to
3023 	 * Valhalla. Note that autokeys are ephemeral, in that they are
3024 	 * tossed immediately upon use. Therefore, the keylist can be
3025 	 * purged anytime without needing to preserve random keys. Note
3026 	 * that, if the peer is purged, the cryptographic variables are
3027 	 * purged, too. This makes it much harder to sneak in some
3028 	 * unauthenticated data in the clock filter.
3029 	 */
3030 	key_expire(peer);
3031 	if (peer->iffval != NULL)
3032 		BN_free(peer->iffval);
3033 	value_free(&peer->cookval);
3034 	value_free(&peer->recval);
3035 	value_free(&peer->encrypt);
3036 	value_free(&peer->sndval);
3037 	if (peer->cmmd != NULL)
3038 		free(peer->cmmd);
3039 	if (peer->subject != NULL)
3040 		free(peer->subject);
3041 	if (peer->issuer != NULL)
3042 		free(peer->issuer);
3043 #endif /* AUTOKEY */
3044 
3045 	/*
3046 	 * Clear all values, including the optional crypto values above.
3047 	 */
3048 	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
3049 	peer->ppoll = peer->maxpoll;
3050 	peer->hpoll = peer->minpoll;
3051 	peer->disp = MAXDISPERSE;
3052 	peer->flash = peer_unfit(peer);
3053 	peer->jitter = LOGTOD(sys_precision);
3054 
3055 	/* Don't throw away our broadcast replay protection */
3056 	if (peer->hmode == MODE_BCLIENT)
3057 		peer->bxmt = bxmt;
3058 
3059 	/*
3060 	 * If interleave mode, initialize the alternate origin switch.
3061 	 */
3062 	if (peer->flags & FLAG_XLEAVE)
3063 		peer->flip = 1;
3064 	for (u = 0; u < NTP_SHIFT; u++) {
3065 		peer->filter_order[u] = u;
3066 		peer->filter_disp[u] = MAXDISPERSE;
3067 	}
3068 #ifdef REFCLOCK
3069 	if (!(peer->flags & FLAG_REFCLOCK)) {
3070 #endif
3071 		peer->leap = LEAP_NOTINSYNC;
3072 		peer->stratum = STRATUM_UNSPEC;
3073 		memcpy(&peer->refid, ident, 4);
3074 #ifdef REFCLOCK
3075 	}
3076 #endif
3077 
3078 	/*
3079 	 * During initialization use the association count to spread out
3080 	 * the polls at one-second intervals. Passive associations'
3081 	 * first poll is delayed by the "discard minimum" to avoid rate
3082 	 * limiting. Other post-startup new or cleared associations
3083 	 * randomize the first poll over the minimum poll interval to
3084 	 * avoid implosion.
3085 	 */
3086 	peer->nextdate = peer->update = peer->outdate = current_time;
3087 	if (initializing) {
3088 		peer->nextdate += peer_associations;
3089 	} else if (MODE_PASSIVE == peer->hmode) {
3090 		peer->nextdate += ntp_minpkt;
3091 	} else {
3092 		peer->nextdate += ntp_random() % peer->minpoll;
3093 	}
3094 #ifdef AUTOKEY
3095 	peer->refresh = current_time + (1 << NTP_REFRESH);
3096 #endif	/* AUTOKEY */
3097 	DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
3098 		    current_time, peer->nextdate, peer->associd,
3099 		    ident));
3100 }
3101 
3102 
3103 /*
3104  * clock_filter - add incoming clock sample to filter register and run
3105  *		  the filter procedure to find the best sample.
3106  */
3107 void
3108 clock_filter(
3109 	struct peer *peer,		/* peer structure pointer */
3110 	double	sample_offset,		/* clock offset */
3111 	double	sample_delay,		/* roundtrip delay */
3112 	double	sample_disp		/* dispersion */
3113 	)
3114 {
3115 	double	dst[NTP_SHIFT];		/* distance vector */
3116 	int	ord[NTP_SHIFT];		/* index vector */
3117 	int	i, j, k, m;
3118 	double	dtemp, etemp;
3119 	char	tbuf[80];
3120 
3121 	/*
3122 	 * A sample consists of the offset, delay, dispersion and epoch
3123 	 * of arrival. The offset and delay are determined by the on-
3124 	 * wire protocol. The dispersion grows from the last outbound
3125 	 * packet to the arrival of this one increased by the sum of the
3126 	 * peer precision and the system precision as required by the
3127 	 * error budget. First, shift the new arrival into the shift
3128 	 * register discarding the oldest one.
3129 	 */
3130 	j = peer->filter_nextpt;
3131 	peer->filter_offset[j] = sample_offset;
3132 	peer->filter_delay[j] = sample_delay;
3133 	peer->filter_disp[j] = sample_disp;
3134 	peer->filter_epoch[j] = current_time;
3135 	j = (j + 1) % NTP_SHIFT;
3136 	peer->filter_nextpt = j;
3137 
3138 	/*
3139 	 * Update dispersions since the last update and at the same
3140 	 * time initialize the distance and index lists. Since samples
3141 	 * become increasingly uncorrelated beyond the Allan intercept,
3142 	 * only under exceptional cases will an older sample be used.
3143 	 * Therefore, the distance list uses a compound metric. If the
3144 	 * dispersion is greater than the maximum dispersion, clamp the
3145 	 * distance at that value. If the time since the last update is
3146 	 * less than the Allan intercept use the delay; otherwise, use
3147 	 * the sum of the delay and dispersion.
3148 	 */
3149 	dtemp = clock_phi * (current_time - peer->update);
3150 	peer->update = current_time;
3151 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
3152 		if (i != 0)
3153 			peer->filter_disp[j] += dtemp;
3154 		if (peer->filter_disp[j] >= MAXDISPERSE) {
3155 			peer->filter_disp[j] = MAXDISPERSE;
3156 			dst[i] = MAXDISPERSE;
3157 		} else if (peer->update - peer->filter_epoch[j] >
3158 		    (u_long)ULOGTOD(allan_xpt)) {
3159 			dst[i] = peer->filter_delay[j] +
3160 			    peer->filter_disp[j];
3161 		} else {
3162 			dst[i] = peer->filter_delay[j];
3163 		}
3164 		ord[i] = j;
3165 		j = (j + 1) % NTP_SHIFT;
3166 	}
3167 
3168 	/*
3169 	 * If the clock has stabilized, sort the samples by distance.
3170 	 */
3171 	if (freq_cnt == 0) {
3172 		for (i = 1; i < NTP_SHIFT; i++) {
3173 			for (j = 0; j < i; j++) {
3174 				if (dst[j] > dst[i]) {
3175 					k = ord[j];
3176 					ord[j] = ord[i];
3177 					ord[i] = k;
3178 					etemp = dst[j];
3179 					dst[j] = dst[i];
3180 					dst[i] = etemp;
3181 				}
3182 			}
3183 		}
3184 	}
3185 
3186 	/*
3187 	 * Copy the index list to the association structure so ntpq
3188 	 * can see it later. Prune the distance list to leave only
3189 	 * samples less than the maximum dispersion, which disfavors
3190 	 * uncorrelated samples older than the Allan intercept. To
3191 	 * further improve the jitter estimate, of the remainder leave
3192 	 * only samples less than the maximum distance, but keep at
3193 	 * least two samples for jitter calculation.
3194 	 */
3195 	m = 0;
3196 	for (i = 0; i < NTP_SHIFT; i++) {
3197 		peer->filter_order[i] = (u_char) ord[i];
3198 		if (   dst[i] >= MAXDISPERSE
3199 		    || (m >= 2 && dst[i] >= sys_maxdist))
3200 			continue;
3201 		m++;
3202 	}
3203 
3204 	/*
3205 	 * Compute the dispersion and jitter. The dispersion is weighted
3206 	 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
3207 	 * to 1.0. The jitter is the RMS differences relative to the
3208 	 * lowest delay sample.
3209 	 */
3210 	peer->disp = peer->jitter = 0;
3211 	k = ord[0];
3212 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
3213 		j = ord[i];
3214 		peer->disp = NTP_FWEIGHT * (peer->disp +
3215 		    peer->filter_disp[j]);
3216 		if (i < m)
3217 			peer->jitter += DIFF(peer->filter_offset[j],
3218 			    peer->filter_offset[k]);
3219 	}
3220 
3221 	/*
3222 	 * If no acceptable samples remain in the shift register,
3223 	 * quietly tiptoe home leaving only the dispersion. Otherwise,
3224 	 * save the offset, delay and jitter. Note the jitter must not
3225 	 * be less than the precision.
3226 	 */
3227 	if (m == 0) {
3228 		clock_select();
3229 		return;
3230 	}
3231 	etemp = fabs(peer->offset - peer->filter_offset[k]);
3232 	peer->offset = peer->filter_offset[k];
3233 	peer->delay = peer->filter_delay[k];
3234 	if (m > 1)
3235 		peer->jitter /= m - 1;
3236 	peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
3237 
3238 	/*
3239 	 * If the the new sample and the current sample are both valid
3240 	 * and the difference between their offsets exceeds CLOCK_SGATE
3241 	 * (3) times the jitter and the interval between them is less
3242 	 * than twice the host poll interval, consider the new sample
3243 	 * a popcorn spike and ignore it.
3244 	 */
3245 	if (   peer->disp < sys_maxdist
3246 	    && peer->filter_disp[k] < sys_maxdist
3247 	    && etemp > CLOCK_SGATE * peer->jitter
3248 	    && peer->filter_epoch[k] - peer->epoch
3249 	       < 2. * ULOGTOD(peer->hpoll)) {
3250 		snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3251 		report_event(PEVNT_POPCORN, peer, tbuf);
3252 		return;
3253 	}
3254 
3255 	/*
3256 	 * A new minimum sample is useful only if it is later than the
3257 	 * last one used. In this design the maximum lifetime of any
3258 	 * sample is not greater than eight times the poll interval, so
3259 	 * the maximum interval between minimum samples is eight
3260 	 * packets.
3261 	 */
3262 	if (peer->filter_epoch[k] <= peer->epoch) {
3263 	DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3264 		    peer->filter_epoch[k]));
3265 		return;
3266 	}
3267 	peer->epoch = peer->filter_epoch[k];
3268 
3269 	/*
3270 	 * The mitigated sample statistics are saved for later
3271 	 * processing. If not synchronized or not in a burst, tickle the
3272 	 * clock select algorithm.
3273 	 */
3274 	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3275 	    peer->offset, peer->delay, peer->disp, peer->jitter);
3276 	DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
3277 		    m, peer->offset, peer->delay, peer->disp,
3278 		    peer->jitter));
3279 	if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
3280 		clock_select();
3281 }
3282 
3283 
3284 /*
3285  * clock_select - find the pick-of-the-litter clock
3286  *
3287  * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3288  * be enabled, even if declared falseticker, (2) only the prefer peer
3289  * can be selected as the system peer, (3) if the external source is
3290  * down, the system leap bits are set to 11 and the stratum set to
3291  * infinity.
3292  */
3293 void
3294 clock_select(void)
3295 {
3296 	struct peer *peer;
3297 	int	i, j, k, n;
3298 	int	nlist, nl2;
3299 	int	allow;
3300 	int	speer;
3301 	double	d, e, f, g;
3302 	double	high, low;
3303 	double	speermet;
3304 	double	orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3305 	struct endpoint endp;
3306 	struct peer *osys_peer;
3307 	struct peer *sys_prefer = NULL;	/* prefer peer */
3308 	struct peer *typesystem = NULL;
3309 	struct peer *typeorphan = NULL;
3310 #ifdef REFCLOCK
3311 	struct peer *typeacts = NULL;
3312 	struct peer *typelocal = NULL;
3313 	struct peer *typepps = NULL;
3314 #endif /* REFCLOCK */
3315 	static struct endpoint *endpoint = NULL;
3316 	static int *indx = NULL;
3317 	static peer_select *peers = NULL;
3318 	static u_int endpoint_size = 0;
3319 	static u_int peers_size = 0;
3320 	static u_int indx_size = 0;
3321 	size_t octets;
3322 
3323 	/*
3324 	 * Initialize and create endpoint, index and peer lists big
3325 	 * enough to handle all associations.
3326 	 */
3327 	osys_peer = sys_peer;
3328 	sys_survivors = 0;
3329 #ifdef LOCKCLOCK
3330 	set_sys_leap(LEAP_NOTINSYNC);
3331 	sys_stratum = STRATUM_UNSPEC;
3332 	memcpy(&sys_refid, "DOWN", 4);
3333 #endif /* LOCKCLOCK */
3334 
3335 	/*
3336 	 * Allocate dynamic space depending on the number of
3337 	 * associations.
3338 	 */
3339 	nlist = 1;
3340 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3341 		nlist++;
3342 	endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3343 	peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3344 	indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3345 	octets = endpoint_size + peers_size + indx_size;
3346 	endpoint = erealloc(endpoint, octets);
3347 	peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3348 	indx = INC_ALIGNED_PTR(peers, peers_size);
3349 
3350 	/*
3351 	 * Initially, we populate the island with all the rifraff peers
3352 	 * that happen to be lying around. Those with seriously
3353 	 * defective clocks are immediately booted off the island. Then,
3354 	 * the falsetickers are culled and put to sea. The truechimers
3355 	 * remaining are subject to repeated rounds where the most
3356 	 * unpopular at each round is kicked off. When the population
3357 	 * has dwindled to sys_minclock, the survivors split a million
3358 	 * bucks and collectively crank the chimes.
3359 	 */
3360 	nlist = nl2 = 0;	/* none yet */
3361 	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3362 		peer->new_status = CTL_PST_SEL_REJECT;
3363 
3364 		/*
3365 		 * Leave the island immediately if the peer is
3366 		 * unfit to synchronize.
3367 		 */
3368 		if (peer_unfit(peer)) {
3369 			continue;
3370 		}
3371 
3372 		/*
3373 		 * If this peer is an orphan parent, elect the
3374 		 * one with the lowest metric defined as the
3375 		 * IPv4 address or the first 64 bits of the
3376 		 * hashed IPv6 address.  To ensure convergence
3377 		 * on the same selected orphan, consider as
3378 		 * well that this system may have the lowest
3379 		 * metric and be the orphan parent.  If this
3380 		 * system wins, sys_peer will be NULL to trigger
3381 		 * orphan mode in timer().
3382 		 */
3383 		if (peer->stratum == sys_orphan) {
3384 			u_int32	localmet;
3385 			u_int32 peermet;
3386 
3387 			if (peer->dstadr != NULL)
3388 				localmet = ntohl(peer->dstadr->addr_refid);
3389 			else
3390 				localmet = U_INT32_MAX;
3391 			peermet = ntohl(addr2refid(&peer->srcadr));
3392 			if (peermet < localmet && peermet < orphmet) {
3393 				typeorphan = peer;
3394 				orphmet = peermet;
3395 			}
3396 			continue;
3397 		}
3398 
3399 		/*
3400 		 * If this peer could have the orphan parent
3401 		 * as a synchronization ancestor, exclude it
3402 		 * from selection to avoid forming a
3403 		 * synchronization loop within the orphan mesh,
3404 		 * triggering stratum climb to infinity
3405 		 * instability.  Peers at stratum higher than
3406 		 * the orphan stratum could have the orphan
3407 		 * parent in ancestry so are excluded.
3408 		 * See http://bugs.ntp.org/2050
3409 		 */
3410 		if (peer->stratum > sys_orphan) {
3411 			continue;
3412 		}
3413 #ifdef REFCLOCK
3414 		/*
3415 		 * The following are special cases. We deal
3416 		 * with them later.
3417 		 */
3418 		if (!(peer->flags & FLAG_PREFER)) {
3419 			switch (peer->refclktype) {
3420 			case REFCLK_LOCALCLOCK:
3421 				if (   current_time > orphwait
3422 				    && typelocal == NULL)
3423 					typelocal = peer;
3424 				continue;
3425 
3426 			case REFCLK_ACTS:
3427 				if (   current_time > orphwait
3428 				    && typeacts == NULL)
3429 					typeacts = peer;
3430 				continue;
3431 			}
3432 		}
3433 #endif /* REFCLOCK */
3434 
3435 		/*
3436 		 * If we get this far, the peer can stay on the
3437 		 * island, but does not yet have the immunity
3438 		 * idol.
3439 		 */
3440 		peer->new_status = CTL_PST_SEL_SANE;
3441 		f = root_distance(peer);
3442 		peers[nlist].peer = peer;
3443 		peers[nlist].error = peer->jitter;
3444 		peers[nlist].synch = f;
3445 		nlist++;
3446 
3447 		/*
3448 		 * Insert each interval endpoint on the unsorted
3449 		 * endpoint[] list.
3450 		 */
3451 		e = peer->offset;
3452 		endpoint[nl2].type = -1;	/* lower end */
3453 		endpoint[nl2].val = e - f;
3454 		nl2++;
3455 		endpoint[nl2].type = 1;		/* upper end */
3456 		endpoint[nl2].val = e + f;
3457 		nl2++;
3458 	}
3459 	/*
3460 	 * Construct sorted indx[] of endpoint[] indexes ordered by
3461 	 * offset.
3462 	 */
3463 	for (i = 0; i < nl2; i++)
3464 		indx[i] = i;
3465 	for (i = 0; i < nl2; i++) {
3466 		endp = endpoint[indx[i]];
3467 		e = endp.val;
3468 		k = i;
3469 		for (j = i + 1; j < nl2; j++) {
3470 			endp = endpoint[indx[j]];
3471 			if (endp.val < e) {
3472 				e = endp.val;
3473 				k = j;
3474 			}
3475 		}
3476 		if (k != i) {
3477 			j = indx[k];
3478 			indx[k] = indx[i];
3479 			indx[i] = j;
3480 		}
3481 	}
3482 	for (i = 0; i < nl2; i++)
3483 		DPRINTF(3, ("select: endpoint %2d %.6f\n",
3484 			endpoint[indx[i]].type, endpoint[indx[i]].val));
3485 
3486 	/*
3487 	 * This is the actual algorithm that cleaves the truechimers
3488 	 * from the falsetickers. The original algorithm was described
3489 	 * in Keith Marzullo's dissertation, but has been modified for
3490 	 * better accuracy.
3491 	 *
3492 	 * Briefly put, we first assume there are no falsetickers, then
3493 	 * scan the candidate list first from the low end upwards and
3494 	 * then from the high end downwards. The scans stop when the
3495 	 * number of intersections equals the number of candidates less
3496 	 * the number of falsetickers. If this doesn't happen for a
3497 	 * given number of falsetickers, we bump the number of
3498 	 * falsetickers and try again. If the number of falsetickers
3499 	 * becomes equal to or greater than half the number of
3500 	 * candidates, the Albanians have won the Byzantine wars and
3501 	 * correct synchronization is not possible.
3502 	 *
3503 	 * Here, nlist is the number of candidates and allow is the
3504 	 * number of falsetickers. Upon exit, the truechimers are the
3505 	 * survivors with offsets not less than low and not greater than
3506 	 * high. There may be none of them.
3507 	 */
3508 	low = 1e9;
3509 	high = -1e9;
3510 	for (allow = 0; 2 * allow < nlist; allow++) {
3511 
3512 		/*
3513 		 * Bound the interval (low, high) as the smallest
3514 		 * interval containing points from the most sources.
3515 		 */
3516 		n = 0;
3517 		for (i = 0; i < nl2; i++) {
3518 			low = endpoint[indx[i]].val;
3519 			n -= endpoint[indx[i]].type;
3520 			if (n >= nlist - allow)
3521 				break;
3522 		}
3523 		n = 0;
3524 		for (j = nl2 - 1; j >= 0; j--) {
3525 			high = endpoint[indx[j]].val;
3526 			n += endpoint[indx[j]].type;
3527 			if (n >= nlist - allow)
3528 				break;
3529 		}
3530 
3531 		/*
3532 		 * If an interval containing truechimers is found, stop.
3533 		 * If not, increase the number of falsetickers and go
3534 		 * around again.
3535 		 */
3536 		if (high > low)
3537 			break;
3538 	}
3539 
3540 	/*
3541 	 * Clustering algorithm. Whittle candidate list of falsetickers,
3542 	 * who leave the island immediately. The TRUE peer is always a
3543 	 * truechimer. We must leave at least one peer to collect the
3544 	 * million bucks.
3545 	 *
3546 	 * We assert the correct time is contained in the interval, but
3547 	 * the best offset estimate for the interval might not be
3548 	 * contained in the interval. For this purpose, a truechimer is
3549 	 * defined as the midpoint of an interval that overlaps the
3550 	 * intersection interval.
3551 	 */
3552 	j = 0;
3553 	for (i = 0; i < nlist; i++) {
3554 		double	h;
3555 
3556 		peer = peers[i].peer;
3557 		h = peers[i].synch;
3558 		if ((   high <= low
3559 		     || peer->offset + h < low
3560 		     || peer->offset - h > high
3561 		    ) && !(peer->flags & FLAG_TRUE))
3562 			continue;
3563 
3564 #ifdef REFCLOCK
3565 		/*
3566 		 * Eligible PPS peers must survive the intersection
3567 		 * algorithm. Use the first one found, but don't
3568 		 * include any of them in the cluster population.
3569 		 */
3570 		if (peer->flags & FLAG_PPS) {
3571 			if (typepps == NULL)
3572 				typepps = peer;
3573 			if (!(peer->flags & FLAG_TSTAMP_PPS))
3574 				continue;
3575 		}
3576 #endif /* REFCLOCK */
3577 
3578 		if (j != i)
3579 			peers[j] = peers[i];
3580 		j++;
3581 	}
3582 	nlist = j;
3583 
3584 	/*
3585 	 * If no survivors remain at this point, check if the modem
3586 	 * driver, local driver or orphan parent in that order. If so,
3587 	 * nominate the first one found as the only survivor.
3588 	 * Otherwise, give up and leave the island to the rats.
3589 	 */
3590 	if (nlist == 0) {
3591 		peers[0].error = 0;
3592 		peers[0].synch = sys_mindisp;
3593 #ifdef REFCLOCK
3594 		if (typeacts != NULL) {
3595 			peers[0].peer = typeacts;
3596 			nlist = 1;
3597 		} else if (typelocal != NULL) {
3598 			peers[0].peer = typelocal;
3599 			nlist = 1;
3600 		} else
3601 #endif /* REFCLOCK */
3602 		if (typeorphan != NULL) {
3603 			peers[0].peer = typeorphan;
3604 			nlist = 1;
3605 		}
3606 	}
3607 
3608 	/*
3609 	 * Mark the candidates at this point as truechimers.
3610 	 */
3611 	for (i = 0; i < nlist; i++) {
3612 		peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3613 		DPRINTF(2, ("select: survivor %s %f\n",
3614 			stoa(&peers[i].peer->srcadr), peers[i].synch));
3615 	}
3616 
3617 	/*
3618 	 * Now, vote outliers off the island by select jitter weighted
3619 	 * by root distance. Continue voting as long as there are more
3620 	 * than sys_minclock survivors and the select jitter of the peer
3621 	 * with the worst metric is greater than the minimum peer
3622 	 * jitter. Stop if we are about to discard a TRUE or PREFER
3623 	 * peer, who of course have the immunity idol.
3624 	 */
3625 	while (1) {
3626 		d = 1e9;
3627 		e = -1e9;
3628 		g = 0;
3629 		k = 0;
3630 		for (i = 0; i < nlist; i++) {
3631 			if (peers[i].error < d)
3632 				d = peers[i].error;
3633 			peers[i].seljit = 0;
3634 			if (nlist > 1) {
3635 				f = 0;
3636 				for (j = 0; j < nlist; j++)
3637 					f += DIFF(peers[j].peer->offset,
3638 					    peers[i].peer->offset);
3639 				peers[i].seljit = SQRT(f / (nlist - 1));
3640 			}
3641 			if (peers[i].seljit * peers[i].synch > e) {
3642 				g = peers[i].seljit;
3643 				e = peers[i].seljit * peers[i].synch;
3644 				k = i;
3645 			}
3646 		}
3647 		g = max(g, LOGTOD(sys_precision));
3648 		if (   nlist <= max(1, sys_minclock)
3649 		    || g <= d
3650 		    || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3651 			break;
3652 
3653 		DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3654 			ntoa(&peers[k].peer->srcadr), g, d));
3655 		if (nlist > sys_maxclock)
3656 			peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3657 		for (j = k + 1; j < nlist; j++)
3658 			peers[j - 1] = peers[j];
3659 		nlist--;
3660 	}
3661 
3662 	/*
3663 	 * What remains is a list usually not greater than sys_minclock
3664 	 * peers. Note that unsynchronized peers cannot survive this
3665 	 * far.  Count and mark these survivors.
3666 	 *
3667 	 * While at it, count the number of leap warning bits found.
3668 	 * This will be used later to vote the system leap warning bit.
3669 	 * If a leap warning bit is found on a reference clock, the vote
3670 	 * is always won.
3671 	 *
3672 	 * Choose the system peer using a hybrid metric composed of the
3673 	 * selection jitter scaled by the root distance augmented by
3674 	 * stratum scaled by sys_mindisp (.001 by default). The goal of
3675 	 * the small stratum factor is to avoid clockhop between a
3676 	 * reference clock and a network peer which has a refclock and
3677 	 * is using an older ntpd, which does not floor sys_rootdisp at
3678 	 * sys_mindisp.
3679 	 *
3680 	 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3681 	 * in selecting the system peer, using a weight of 1 second of
3682 	 * additional root distance per stratum.  This heavy bias is no
3683 	 * longer appropriate, as the scaled root distance provides a
3684 	 * more rational metric carrying the cumulative error budget.
3685 	 */
3686 	e = 1e9;
3687 	speer = 0;
3688 	leap_vote_ins = 0;
3689 	leap_vote_del = 0;
3690 	for (i = 0; i < nlist; i++) {
3691 		peer = peers[i].peer;
3692 		peer->unreach = 0;
3693 		peer->new_status = CTL_PST_SEL_SYNCCAND;
3694 		sys_survivors++;
3695 		if (peer->leap == LEAP_ADDSECOND) {
3696 			if (peer->flags & FLAG_REFCLOCK)
3697 				leap_vote_ins = nlist;
3698 			else if (leap_vote_ins < nlist)
3699 				leap_vote_ins++;
3700 		}
3701 		if (peer->leap == LEAP_DELSECOND) {
3702 			if (peer->flags & FLAG_REFCLOCK)
3703 				leap_vote_del = nlist;
3704 			else if (leap_vote_del < nlist)
3705 				leap_vote_del++;
3706 		}
3707 		if (peer->flags & FLAG_PREFER)
3708 			sys_prefer = peer;
3709 		speermet = peers[i].seljit * peers[i].synch +
3710 		    peer->stratum * sys_mindisp;
3711 		if (speermet < e) {
3712 			e = speermet;
3713 			speer = i;
3714 		}
3715 	}
3716 
3717 	/*
3718 	 * Unless there are at least sys_misane survivors, leave the
3719 	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3720 	 * use the selected survivor speer. However, if the current
3721 	 * system peer is not speer, stay with the current system peer
3722 	 * as long as it doesn't get too old or too ugly.
3723 	 */
3724 	if (nlist > 0 && nlist >= sys_minsane) {
3725 		double	x;
3726 
3727 		typesystem = peers[speer].peer;
3728 		if (osys_peer == NULL || osys_peer == typesystem) {
3729 			sys_clockhop = 0;
3730 		} else if ((x = fabs(typesystem->offset -
3731 		    osys_peer->offset)) < sys_mindisp) {
3732 			if (sys_clockhop == 0)
3733 				sys_clockhop = sys_mindisp;
3734 			else
3735 				sys_clockhop *= .5;
3736 			DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3737 				j, x, sys_clockhop));
3738 			if (fabs(x) < sys_clockhop)
3739 				typesystem = osys_peer;
3740 			else
3741 				sys_clockhop = 0;
3742 		} else {
3743 			sys_clockhop = 0;
3744 		}
3745 	}
3746 
3747 	/*
3748 	 * Mitigation rules of the game. We have the pick of the
3749 	 * litter in typesystem if any survivors are left. If
3750 	 * there is a prefer peer, use its offset and jitter.
3751 	 * Otherwise, use the combined offset and jitter of all kitters.
3752 	 */
3753 	if (typesystem != NULL) {
3754 		if (sys_prefer == NULL) {
3755 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3756 			clock_combine(peers, sys_survivors, speer);
3757 		} else {
3758 			typesystem = sys_prefer;
3759 			sys_clockhop = 0;
3760 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3761 			sys_offset = typesystem->offset;
3762 			sys_jitter = typesystem->jitter;
3763 		}
3764 		DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3765 			sys_offset, sys_jitter));
3766 	}
3767 #ifdef REFCLOCK
3768 	/*
3769 	 * If a PPS driver is lit and the combined offset is less than
3770 	 * 0.4 s, select the driver as the PPS peer and use its offset
3771 	 * and jitter. However, if this is the atom driver, use it only
3772 	 * if there is a prefer peer or there are no survivors and none
3773 	 * are required.
3774 	 */
3775 	if (   typepps != NULL
3776 	    && fabs(sys_offset) < 0.4
3777 	    && (   typepps->refclktype != REFCLK_ATOM_PPS
3778 		|| (   typepps->refclktype == REFCLK_ATOM_PPS
3779 		    && (   sys_prefer != NULL
3780 			|| (typesystem == NULL && sys_minsane == 0))))) {
3781 		typesystem = typepps;
3782 		sys_clockhop = 0;
3783 		typesystem->new_status = CTL_PST_SEL_PPS;
3784 		sys_offset = typesystem->offset;
3785 		sys_jitter = typesystem->jitter;
3786 		DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3787 			sys_offset, sys_jitter));
3788 	}
3789 #endif /* REFCLOCK */
3790 
3791 	/*
3792 	 * If there are no survivors at this point, there is no
3793 	 * system peer. If so and this is an old update, keep the
3794 	 * current statistics, but do not update the clock.
3795 	 */
3796 	if (typesystem == NULL) {
3797 		if (osys_peer != NULL) {
3798 			if (sys_orphwait > 0)
3799 				orphwait = current_time + sys_orphwait;
3800 			report_event(EVNT_NOPEER, NULL, NULL);
3801 		}
3802 		sys_peer = NULL;
3803 		for (peer = peer_list; peer != NULL; peer = peer->p_link)
3804 			peer->status = peer->new_status;
3805 		return;
3806 	}
3807 
3808 	/*
3809 	 * Do not use old data, as this may mess up the clock discipline
3810 	 * stability.
3811 	 */
3812 	if (typesystem->epoch <= sys_epoch)
3813 		return;
3814 
3815 	/*
3816 	 * We have found the alpha male. Wind the clock.
3817 	 */
3818 	if (osys_peer != typesystem)
3819 		report_event(PEVNT_NEWPEER, typesystem, NULL);
3820 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3821 		peer->status = peer->new_status;
3822 	clock_update(typesystem);
3823 }
3824 
3825 
3826 static void
3827 clock_combine(
3828 	peer_select *	peers,	/* survivor list */
3829 	int		npeers,	/* number of survivors */
3830 	int		syspeer	/* index of sys.peer */
3831 	)
3832 {
3833 	int	i;
3834 	double	x, y, z, w;
3835 
3836 	y = z = w = 0;
3837 	for (i = 0; i < npeers; i++) {
3838 		x = 1. / peers[i].synch;
3839 		y += x;
3840 		z += x * peers[i].peer->offset;
3841 		w += x * DIFF(peers[i].peer->offset,
3842 		    peers[syspeer].peer->offset);
3843 	}
3844 	sys_offset = z / y;
3845 	sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
3846 }
3847 
3848 
3849 /*
3850  * root_distance - compute synchronization distance from peer to root
3851  */
3852 static double
3853 root_distance(
3854 	struct peer *peer	/* peer structure pointer */
3855 	)
3856 {
3857 	double	dtemp;
3858 
3859 	/*
3860 	 * Root Distance (LAMBDA) is defined as:
3861 	 * (delta + DELTA)/2 + epsilon + EPSILON + D
3862 	 *
3863 	 * where:
3864 	 *  delta   is the round-trip delay
3865 	 *  DELTA   is the root delay
3866 	 *  epsilon is the peer dispersion
3867 	 *	    + (15 usec each second)
3868 	 *  EPSILON is the root dispersion
3869 	 *  D       is sys_jitter
3870 	 *
3871 	 * NB: Think hard about why we are using these values, and what
3872 	 * the alternatives are, and the various pros/cons.
3873 	 *
3874 	 * DLM thinks these are probably the best choices from any of the
3875 	 * other worse choices.
3876 	 */
3877 	dtemp = (peer->delay + peer->rootdelay) / 2
3878 		+ peer->disp
3879 		  + clock_phi * (current_time - peer->update)
3880 		+ peer->rootdisp
3881 		+ peer->jitter;
3882 	/*
3883 	 * Careful squeak here. The value returned must be greater than
3884 	 * the minimum root dispersion in order to avoid clockhop with
3885 	 * highly precise reference clocks. Note that the root distance
3886 	 * cannot exceed the sys_maxdist, as this is the cutoff by the
3887 	 * selection algorithm.
3888 	 */
3889 	if (dtemp < sys_mindisp)
3890 		dtemp = sys_mindisp;
3891 	return (dtemp);
3892 }
3893 
3894 
3895 /*
3896  * peer_xmit - send packet for persistent association.
3897  */
3898 static void
3899 peer_xmit(
3900 	struct peer *peer	/* peer structure pointer */
3901 	)
3902 {
3903 	struct pkt xpkt;	/* transmit packet */
3904 	size_t	sendlen, authlen;
3905 	keyid_t	xkeyid = 0;	/* transmit key ID */
3906 	l_fp	xmt_tx, xmt_ty;
3907 
3908 	if (!peer->dstadr)	/* drop peers without interface */
3909 		return;
3910 
3911 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3912 	    peer->hmode);
3913 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3914 	xpkt.ppoll = peer->hpoll;
3915 	xpkt.precision = sys_precision;
3916 	xpkt.refid = sys_refid;
3917 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3918 	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
3919 	HTONL_FP(&sys_reftime, &xpkt.reftime);
3920 	HTONL_FP(&peer->rec, &xpkt.org);
3921 	HTONL_FP(&peer->dst, &xpkt.rec);
3922 
3923 	/*
3924 	 * If the received packet contains a MAC, the transmitted packet
3925 	 * is authenticated and contains a MAC. If not, the transmitted
3926 	 * packet is not authenticated.
3927 	 *
3928 	 * It is most important when autokey is in use that the local
3929 	 * interface IP address be known before the first packet is
3930 	 * sent. Otherwise, it is not possible to compute a correct MAC
3931 	 * the recipient will accept. Thus, the I/O semantics have to do
3932 	 * a little more work. In particular, the wildcard interface
3933 	 * might not be usable.
3934 	 */
3935 	sendlen = LEN_PKT_NOMAC;
3936 	if (
3937 #ifdef AUTOKEY
3938 	    !(peer->flags & FLAG_SKEY) &&
3939 #endif	/* !AUTOKEY */
3940 	    peer->keyid == 0) {
3941 
3942 		/*
3943 		 * Transmit a-priori timestamps
3944 		 */
3945 		get_systime(&xmt_tx);
3946 		if (peer->flip == 0) {	/* basic mode */
3947 			peer->aorg = xmt_tx;
3948 			HTONL_FP(&xmt_tx, &xpkt.xmt);
3949 		} else {		/* interleaved modes */
3950 			if (peer->hmode == MODE_BROADCAST) { /* bcst */
3951 				HTONL_FP(&xmt_tx, &xpkt.xmt);
3952 				if (peer->flip > 0)
3953 					HTONL_FP(&peer->borg,
3954 					    &xpkt.org);
3955 				else
3956 					HTONL_FP(&peer->aorg,
3957 					    &xpkt.org);
3958 			} else {	/* symmetric */
3959 				if (peer->flip > 0)
3960 					HTONL_FP(&peer->borg,
3961 					    &xpkt.xmt);
3962 				else
3963 					HTONL_FP(&peer->aorg,
3964 					    &xpkt.xmt);
3965 			}
3966 		}
3967 		peer->t21_bytes = sendlen;
3968 		sendpkt(&peer->srcadr, peer->dstadr,
3969 			sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
3970 			&xpkt, sendlen);
3971 		peer->sent++;
3972 		peer->throttle += (1 << peer->minpoll) - 2;
3973 
3974 		/*
3975 		 * Capture a-posteriori timestamps
3976 		 */
3977 		get_systime(&xmt_ty);
3978 		if (peer->flip != 0) {		/* interleaved modes */
3979 			if (peer->flip > 0)
3980 				peer->aorg = xmt_ty;
3981 			else
3982 				peer->borg = xmt_ty;
3983 			peer->flip = -peer->flip;
3984 		}
3985 		L_SUB(&xmt_ty, &xmt_tx);
3986 		LFPTOD(&xmt_ty, peer->xleave);
3987 		DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3988 			    current_time,
3989 			    peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3990 		            stoa(&peer->srcadr), peer->hmode, sendlen,
3991 			    xmt_tx.l_ui, xmt_tx.l_uf));
3992 		return;
3993 	}
3994 
3995 	/*
3996 	 * Authentication is enabled, so the transmitted packet must be
3997 	 * authenticated. If autokey is enabled, fuss with the various
3998 	 * modes; otherwise, symmetric key cryptography is used.
3999 	 */
4000 #ifdef AUTOKEY
4001 	if (peer->flags & FLAG_SKEY) {
4002 		struct exten *exten;	/* extension field */
4003 
4004 		/*
4005 		 * The Public Key Dance (PKD): Cryptographic credentials
4006 		 * are contained in extension fields, each including a
4007 		 * 4-octet length/code word followed by a 4-octet
4008 		 * association ID and optional additional data. Optional
4009 		 * data includes a 4-octet data length field followed by
4010 		 * the data itself. Request messages are sent from a
4011 		 * configured association; response messages can be sent
4012 		 * from a configured association or can take the fast
4013 		 * path without ever matching an association. Response
4014 		 * messages have the same code as the request, but have
4015 		 * a response bit and possibly an error bit set. In this
4016 		 * implementation, a message may contain no more than
4017 		 * one command and one or more responses.
4018 		 *
4019 		 * Cryptographic session keys include both a public and
4020 		 * a private componet. Request and response messages
4021 		 * using extension fields are always sent with the
4022 		 * private component set to zero. Packets without
4023 		 * extension fields indlude the private component when
4024 		 * the session key is generated.
4025 		 */
4026 		while (1) {
4027 
4028 			/*
4029 			 * Allocate and initialize a keylist if not
4030 			 * already done. Then, use the list in inverse
4031 			 * order, discarding keys once used. Keep the
4032 			 * latest key around until the next one, so
4033 			 * clients can use client/server packets to
4034 			 * compute propagation delay.
4035 			 *
4036 			 * Note that once a key is used from the list,
4037 			 * it is retained in the key cache until the
4038 			 * next key is used. This is to allow a client
4039 			 * to retrieve the encrypted session key
4040 			 * identifier to verify authenticity.
4041 			 *
4042 			 * If for some reason a key is no longer in the
4043 			 * key cache, a birthday has happened or the key
4044 			 * has expired, so the pseudo-random sequence is
4045 			 * broken. In that case, purge the keylist and
4046 			 * regenerate it.
4047 			 */
4048 			if (peer->keynumber == 0)
4049 				make_keylist(peer, peer->dstadr);
4050 			else
4051 				peer->keynumber--;
4052 			xkeyid = peer->keylist[peer->keynumber];
4053 			if (authistrusted(xkeyid))
4054 				break;
4055 			else
4056 				key_expire(peer);
4057 		}
4058 		peer->keyid = xkeyid;
4059 		exten = NULL;
4060 		switch (peer->hmode) {
4061 
4062 		/*
4063 		 * In broadcast server mode the autokey values are
4064 		 * required by the broadcast clients. Push them when a
4065 		 * new keylist is generated; otherwise, push the
4066 		 * association message so the client can request them at
4067 		 * other times.
4068 		 */
4069 		case MODE_BROADCAST:
4070 			if (peer->flags & FLAG_ASSOC)
4071 				exten = crypto_args(peer, CRYPTO_AUTO |
4072 				    CRYPTO_RESP, peer->associd, NULL);
4073 			else
4074 				exten = crypto_args(peer, CRYPTO_ASSOC |
4075 				    CRYPTO_RESP, peer->associd, NULL);
4076 			break;
4077 
4078 		/*
4079 		 * In symmetric modes the parameter, certificate,
4080 		 * identity, cookie and autokey exchanges are
4081 		 * required. The leapsecond exchange is optional. But, a
4082 		 * peer will not believe the other peer until the other
4083 		 * peer has synchronized, so the certificate exchange
4084 		 * might loop until then. If a peer finds a broken
4085 		 * autokey sequence, it uses the autokey exchange to
4086 		 * retrieve the autokey values. In any case, if a new
4087 		 * keylist is generated, the autokey values are pushed.
4088 		 */
4089 		case MODE_ACTIVE:
4090 		case MODE_PASSIVE:
4091 
4092 			/*
4093 			 * Parameter, certificate and identity.
4094 			 */
4095 			if (!peer->crypto)
4096 				exten = crypto_args(peer, CRYPTO_ASSOC,
4097 				    peer->associd, hostval.ptr);
4098 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4099 				exten = crypto_args(peer, CRYPTO_CERT,
4100 				    peer->associd, peer->issuer);
4101 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4102 				exten = crypto_args(peer,
4103 				    crypto_ident(peer), peer->associd,
4104 				    NULL);
4105 
4106 			/*
4107 			 * Cookie and autokey. We request the cookie
4108 			 * only when the this peer and the other peer
4109 			 * are synchronized. But, this peer needs the
4110 			 * autokey values when the cookie is zero. Any
4111 			 * time we regenerate the key list, we offer the
4112 			 * autokey values without being asked. If for
4113 			 * some reason either peer finds a broken
4114 			 * autokey sequence, the autokey exchange is
4115 			 * used to retrieve the autokey values.
4116 			 */
4117 			else if (   sys_leap != LEAP_NOTINSYNC
4118 				 && peer->leap != LEAP_NOTINSYNC
4119 				 && !(peer->crypto & CRYPTO_FLAG_COOK))
4120 				exten = crypto_args(peer, CRYPTO_COOK,
4121 				    peer->associd, NULL);
4122 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4123 				exten = crypto_args(peer, CRYPTO_AUTO,
4124 				    peer->associd, NULL);
4125 			else if (   peer->flags & FLAG_ASSOC
4126 				 && peer->crypto & CRYPTO_FLAG_SIGN)
4127 				exten = crypto_args(peer, CRYPTO_AUTO |
4128 				    CRYPTO_RESP, peer->assoc, NULL);
4129 
4130 			/*
4131 			 * Wait for clock sync, then sign the
4132 			 * certificate and retrieve the leapsecond
4133 			 * values.
4134 			 */
4135 			else if (sys_leap == LEAP_NOTINSYNC)
4136 				break;
4137 
4138 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4139 				exten = crypto_args(peer, CRYPTO_SIGN,
4140 				    peer->associd, hostval.ptr);
4141 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4142 				exten = crypto_args(peer, CRYPTO_LEAP,
4143 				    peer->associd, NULL);
4144 			break;
4145 
4146 		/*
4147 		 * In client mode the parameter, certificate, identity,
4148 		 * cookie and sign exchanges are required. The
4149 		 * leapsecond exchange is optional. If broadcast client
4150 		 * mode the same exchanges are required, except that the
4151 		 * autokey exchange is substitutes for the cookie
4152 		 * exchange, since the cookie is always zero. If the
4153 		 * broadcast client finds a broken autokey sequence, it
4154 		 * uses the autokey exchange to retrieve the autokey
4155 		 * values.
4156 		 */
4157 		case MODE_CLIENT:
4158 
4159 			/*
4160 			 * Parameter, certificate and identity.
4161 			 */
4162 			if (!peer->crypto)
4163 				exten = crypto_args(peer, CRYPTO_ASSOC,
4164 				    peer->associd, hostval.ptr);
4165 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4166 				exten = crypto_args(peer, CRYPTO_CERT,
4167 				    peer->associd, peer->issuer);
4168 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4169 				exten = crypto_args(peer,
4170 				    crypto_ident(peer), peer->associd,
4171 				    NULL);
4172 
4173 			/*
4174 			 * Cookie and autokey. These are requests, but
4175 			 * we use the peer association ID with autokey
4176 			 * rather than our own.
4177 			 */
4178 			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
4179 				exten = crypto_args(peer, CRYPTO_COOK,
4180 				    peer->associd, NULL);
4181 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4182 				exten = crypto_args(peer, CRYPTO_AUTO,
4183 				    peer->assoc, NULL);
4184 
4185 			/*
4186 			 * Wait for clock sync, then sign the
4187 			 * certificate and retrieve the leapsecond
4188 			 * values.
4189 			 */
4190 			else if (sys_leap == LEAP_NOTINSYNC)
4191 				break;
4192 
4193 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4194 				exten = crypto_args(peer, CRYPTO_SIGN,
4195 				    peer->associd, hostval.ptr);
4196 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4197 				exten = crypto_args(peer, CRYPTO_LEAP,
4198 				    peer->associd, NULL);
4199 			break;
4200 		}
4201 
4202 		/*
4203 		 * Add a queued extension field if present. This is
4204 		 * always a request message, so the reply ID is already
4205 		 * in the message. If an error occurs, the error bit is
4206 		 * lit in the response.
4207 		 */
4208 		if (peer->cmmd != NULL) {
4209 			u_int32 temp32;
4210 
4211 			temp32 = CRYPTO_RESP;
4212 			peer->cmmd->opcode |= htonl(temp32);
4213 			sendlen += crypto_xmit(peer, &xpkt, NULL,
4214 			    sendlen, peer->cmmd, 0);
4215 			free(peer->cmmd);
4216 			peer->cmmd = NULL;
4217 		}
4218 
4219 		/*
4220 		 * Add an extension field created above. All but the
4221 		 * autokey response message are request messages.
4222 		 */
4223 		if (exten != NULL) {
4224 			if (exten->opcode != 0)
4225 				sendlen += crypto_xmit(peer, &xpkt,
4226 				    NULL, sendlen, exten, 0);
4227 			free(exten);
4228 		}
4229 
4230 		/*
4231 		 * Calculate the next session key. Since extension
4232 		 * fields are present, the cookie value is zero.
4233 		 */
4234 		if (sendlen > (int)LEN_PKT_NOMAC) {
4235 			session_key(&peer->dstadr->sin, &peer->srcadr,
4236 			    xkeyid, 0, 2);
4237 		}
4238 	}
4239 #endif	/* AUTOKEY */
4240 
4241 	/*
4242 	 * Transmit a-priori timestamps
4243 	 */
4244 	get_systime(&xmt_tx);
4245 	if (peer->flip == 0) {		/* basic mode */
4246 		peer->aorg = xmt_tx;
4247 		HTONL_FP(&xmt_tx, &xpkt.xmt);
4248 	} else {			/* interleaved modes */
4249 		if (peer->hmode == MODE_BROADCAST) { /* bcst */
4250 			HTONL_FP(&xmt_tx, &xpkt.xmt);
4251 			if (peer->flip > 0)
4252 				HTONL_FP(&peer->borg, &xpkt.org);
4253 			else
4254 				HTONL_FP(&peer->aorg, &xpkt.org);
4255 		} else {		/* symmetric */
4256 			if (peer->flip > 0)
4257 				HTONL_FP(&peer->borg, &xpkt.xmt);
4258 			else
4259 				HTONL_FP(&peer->aorg, &xpkt.xmt);
4260 		}
4261 	}
4262 	xkeyid = peer->keyid;
4263 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4264 	if (authlen == 0) {
4265 		report_event(PEVNT_AUTH, peer, "no key");
4266 		peer->flash |= TEST5;		/* auth error */
4267 		peer->badauth++;
4268 		return;
4269 	}
4270 	sendlen += authlen;
4271 #ifdef AUTOKEY
4272 	if (xkeyid > NTP_MAXKEY)
4273 		authtrust(xkeyid, 0);
4274 #endif	/* AUTOKEY */
4275 	if (sendlen > sizeof(xpkt)) {
4276 		msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4277 		exit (-1);
4278 	}
4279 	peer->t21_bytes = sendlen;
4280 	sendpkt(&peer->srcadr, peer->dstadr,
4281 		sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
4282 		&xpkt, sendlen);
4283 	peer->sent++;
4284 	peer->throttle += (1 << peer->minpoll) - 2;
4285 
4286 	/*
4287 	 * Capture a-posteriori timestamps
4288 	 */
4289 	get_systime(&xmt_ty);
4290 	if (peer->flip != 0) {			/* interleaved modes */
4291 		if (peer->flip > 0)
4292 			peer->aorg = xmt_ty;
4293 		else
4294 			peer->borg = xmt_ty;
4295 		peer->flip = -peer->flip;
4296 	}
4297 	L_SUB(&xmt_ty, &xmt_tx);
4298 	LFPTOD(&xmt_ty, peer->xleave);
4299 #ifdef AUTOKEY
4300 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4301 		    current_time, latoa(peer->dstadr),
4302 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4303 		    peer->keynumber));
4304 #else	/* !AUTOKEY follows */
4305 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu\n",
4306 		    current_time, peer->dstadr ?
4307 		    ntoa(&peer->dstadr->sin) : "-",
4308 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4309 #endif	/* !AUTOKEY */
4310 
4311 	return;
4312 }
4313 
4314 
4315 #ifdef LEAP_SMEAR
4316 
4317 static void
4318 leap_smear_add_offs(
4319 	l_fp *t,
4320 	l_fp *t_recv
4321 	)
4322 {
4323 
4324 	L_ADD(t, &leap_smear.offset);
4325 
4326 	/*
4327 	** XXX: Should the smear be added to the root dispersion?
4328 	*/
4329 
4330 	return;
4331 }
4332 
4333 #endif  /* LEAP_SMEAR */
4334 
4335 
4336 /*
4337  * fast_xmit - Send packet for nonpersistent association. Note that
4338  * neither the source or destination can be a broadcast address.
4339  */
4340 static void
4341 fast_xmit(
4342 	struct recvbuf *rbufp,	/* receive packet pointer */
4343 	int	xmode,		/* receive mode */
4344 	keyid_t	xkeyid,		/* transmit key ID */
4345 	int	flags		/* restrict mask */
4346 	)
4347 {
4348 	struct pkt xpkt;	/* transmit packet structure */
4349 	struct pkt *rpkt;	/* receive packet structure */
4350 	l_fp	xmt_tx, xmt_ty;
4351 	size_t	sendlen;
4352 #ifdef AUTOKEY
4353 	u_int32	temp32;
4354 #endif
4355 
4356 	/*
4357 	 * Initialize transmit packet header fields from the receive
4358 	 * buffer provided. We leave the fields intact as received, but
4359 	 * set the peer poll at the maximum of the receive peer poll and
4360 	 * the system minimum poll (ntp_minpoll). This is for KoD rate
4361 	 * control and not strictly specification compliant, but doesn't
4362 	 * break anything.
4363 	 *
4364 	 * If the gazinta was from a multicast address, the gazoutta
4365 	 * must go out another way.
4366 	 */
4367 	rpkt = &rbufp->recv_pkt;
4368 	if (rbufp->dstadr->flags & INT_MCASTOPEN)
4369 		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
4370 
4371 	/*
4372 	 * If this is a kiss-o'-death (KoD) packet, show leap
4373 	 * unsynchronized, stratum zero, reference ID the four-character
4374 	 * kiss code and system root delay. Note we don't reveal the
4375 	 * local time, so these packets can't be used for
4376 	 * synchronization.
4377 	 */
4378 	if (flags & RES_KOD) {
4379 		sys_kodsent++;
4380 		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4381 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4382 		xpkt.stratum = STRATUM_PKT_UNSPEC;
4383 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4384 		xpkt.precision = rpkt->precision;
4385 		memcpy(&xpkt.refid, "RATE", 4);
4386 		xpkt.rootdelay = rpkt->rootdelay;
4387 		xpkt.rootdisp = rpkt->rootdisp;
4388 		xpkt.reftime = rpkt->reftime;
4389 		xpkt.org = rpkt->xmt;
4390 		xpkt.rec = rpkt->xmt;
4391 		xpkt.xmt = rpkt->xmt;
4392 
4393 	/*
4394 	 * This is a normal packet. Use the system variables.
4395 	 */
4396 	} else {
4397 #ifdef LEAP_SMEAR
4398 		/*
4399 		 * Make copies of the variables which can be affected by smearing.
4400 		 */
4401 		l_fp this_ref_time;
4402 		l_fp this_recv_time;
4403 #endif
4404 
4405 		/*
4406 		 * If we are inside the leap smear interval we add the current smear offset to
4407 		 * the packet receive time, to the packet transmit time, and eventually to the
4408 		 * reftime to make sure the reftime isn't later than the transmit/receive times.
4409 		 */
4410 		xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
4411 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4412 
4413 		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4414 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4415 		xpkt.precision = sys_precision;
4416 		xpkt.refid = sys_refid;
4417 		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4418 		xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4419 
4420 #ifdef LEAP_SMEAR
4421 		this_ref_time = sys_reftime;
4422 		if (leap_smear.in_progress) {
4423 			leap_smear_add_offs(&this_ref_time, NULL);
4424 			xpkt.refid = convertLFPToRefID(leap_smear.offset);
4425 			DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4426 				ntohl(xpkt.refid),
4427 				lfptoa(&leap_smear.offset, 8)
4428 				));
4429 		}
4430 		HTONL_FP(&this_ref_time, &xpkt.reftime);
4431 #else
4432 		HTONL_FP(&sys_reftime, &xpkt.reftime);
4433 #endif
4434 
4435 		xpkt.org = rpkt->xmt;
4436 
4437 #ifdef LEAP_SMEAR
4438 		this_recv_time = rbufp->recv_time;
4439 		if (leap_smear.in_progress)
4440 			leap_smear_add_offs(&this_recv_time, NULL);
4441 		HTONL_FP(&this_recv_time, &xpkt.rec);
4442 #else
4443 		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4444 #endif
4445 
4446 		get_systime(&xmt_tx);
4447 #ifdef LEAP_SMEAR
4448 		if (leap_smear.in_progress)
4449 			leap_smear_add_offs(&xmt_tx, &this_recv_time);
4450 #endif
4451 		HTONL_FP(&xmt_tx, &xpkt.xmt);
4452 	}
4453 
4454 #ifdef HAVE_NTP_SIGND
4455 	if (flags & RES_MSSNTP) {
4456 		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4457 		return;
4458 	}
4459 #endif /* HAVE_NTP_SIGND */
4460 
4461 	/*
4462 	 * If the received packet contains a MAC, the transmitted packet
4463 	 * is authenticated and contains a MAC. If not, the transmitted
4464 	 * packet is not authenticated.
4465 	 */
4466 	sendlen = LEN_PKT_NOMAC;
4467 	if (rbufp->recv_length == sendlen) {
4468 		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4469 		    sendlen);
4470 		DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4471 			    current_time, stoa(&rbufp->dstadr->sin),
4472 			    stoa(&rbufp->recv_srcadr), xmode,
4473 			    (u_long)sendlen));
4474 		return;
4475 	}
4476 
4477 	/*
4478 	 * The received packet contains a MAC, so the transmitted packet
4479 	 * must be authenticated. For symmetric key cryptography, use
4480 	 * the predefined and trusted symmetric keys to generate the
4481 	 * cryptosum. For autokey cryptography, use the server private
4482 	 * value to generate the cookie, which is unique for every
4483 	 * source-destination-key ID combination.
4484 	 */
4485 #ifdef AUTOKEY
4486 	if (xkeyid > NTP_MAXKEY) {
4487 		keyid_t cookie;
4488 
4489 		/*
4490 		 * The only way to get here is a reply to a legitimate
4491 		 * client request message, so the mode must be
4492 		 * MODE_SERVER. If an extension field is present, there
4493 		 * can be only one and that must be a command. Do what
4494 		 * needs, but with private value of zero so the poor
4495 		 * jerk can decode it. If no extension field is present,
4496 		 * use the cookie to generate the session key.
4497 		 */
4498 		cookie = session_key(&rbufp->recv_srcadr,
4499 		    &rbufp->dstadr->sin, 0, sys_private, 0);
4500 		if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4501 			session_key(&rbufp->dstadr->sin,
4502 			    &rbufp->recv_srcadr, xkeyid, 0, 2);
4503 			temp32 = CRYPTO_RESP;
4504 			rpkt->exten[0] |= htonl(temp32);
4505 			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4506 			    sendlen, (struct exten *)rpkt->exten,
4507 			    cookie);
4508 		} else {
4509 			session_key(&rbufp->dstadr->sin,
4510 			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
4511 		}
4512 	}
4513 #endif	/* AUTOKEY */
4514 	get_systime(&xmt_tx);
4515 	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4516 #ifdef AUTOKEY
4517 	if (xkeyid > NTP_MAXKEY)
4518 		authtrust(xkeyid, 0);
4519 #endif	/* AUTOKEY */
4520 	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4521 	get_systime(&xmt_ty);
4522 	L_SUB(&xmt_ty, &xmt_tx);
4523 	sys_authdelay = xmt_ty;
4524 	DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4525 		    current_time, ntoa(&rbufp->dstadr->sin),
4526 		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4527 		    (u_long)sendlen));
4528 }
4529 
4530 
4531 /*
4532  * pool_xmit - resolve hostname or send unicast solicitation for pool.
4533  */
4534 static void
4535 pool_xmit(
4536 	struct peer *pool	/* pool solicitor association */
4537 	)
4538 {
4539 #ifdef WORKER
4540 	struct pkt		xpkt;	/* transmit packet structure */
4541 	struct addrinfo		hints;
4542 	int			rc;
4543 	struct interface *	lcladr;
4544 	sockaddr_u *		rmtadr;
4545 	r4addr			r4a;
4546 	int			restrict_mask;
4547 	struct peer *		p;
4548 	l_fp			xmt_tx;
4549 
4550 	if (NULL == pool->ai) {
4551 		if (pool->addrs != NULL) {
4552 			/* free() is used with copy_addrinfo_list() */
4553 			free(pool->addrs);
4554 			pool->addrs = NULL;
4555 		}
4556 		ZERO(hints);
4557 		hints.ai_family = AF(&pool->srcadr);
4558 		hints.ai_socktype = SOCK_DGRAM;
4559 		hints.ai_protocol = IPPROTO_UDP;
4560 		/* ignore getaddrinfo_sometime() errors, we will retry */
4561 		rc = getaddrinfo_sometime(
4562 			pool->hostname,
4563 			"ntp",
4564 			&hints,
4565 			0,			/* no retry */
4566 			&pool_name_resolved,
4567 			(void *)(intptr_t)pool->associd);
4568 		if (!rc)
4569 			DPRINTF(1, ("pool DNS lookup %s started\n",
4570 				pool->hostname));
4571 		else
4572 			msyslog(LOG_ERR,
4573 				"unable to start pool DNS %s: %m",
4574 				pool->hostname);
4575 		return;
4576 	}
4577 
4578 	do {
4579 		/* copy_addrinfo_list ai_addr points to a sockaddr_u */
4580 		rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4581 		pool->ai = pool->ai->ai_next;
4582 		p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0, NULL);
4583 	} while (p != NULL && pool->ai != NULL);
4584 	if (p != NULL)
4585 		return;	/* out of addresses, re-query DNS next poll */
4586 	restrictions(rmtadr, &r4a);
4587 	restrict_mask = r4a.rflags;
4588 	if (RES_FLAGS & restrict_mask)
4589 		restrict_source(rmtadr, 0,
4590 				current_time + POOL_SOLICIT_WINDOW + 1);
4591 	lcladr = findinterface(rmtadr);
4592 	memset(&xpkt, 0, sizeof(xpkt));
4593 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4594 					 MODE_CLIENT);
4595 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4596 	xpkt.ppoll = pool->hpoll;
4597 	xpkt.precision = sys_precision;
4598 	xpkt.refid = sys_refid;
4599 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4600 	xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4601 	HTONL_FP(&sys_reftime, &xpkt.reftime);
4602 	get_systime(&xmt_tx);
4603 	pool->aorg = xmt_tx;
4604 	HTONL_FP(&xmt_tx, &xpkt.xmt);
4605 	sendpkt(rmtadr, lcladr,
4606 		sys_ttl[(pool->ttl >= sys_ttlmax) ? sys_ttlmax : pool->ttl],
4607 		&xpkt, LEN_PKT_NOMAC);
4608 	pool->sent++;
4609 	pool->throttle += (1 << pool->minpoll) - 2;
4610 	DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4611 		    current_time, latoa(lcladr), stoa(rmtadr)));
4612 	msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4613 #endif	/* WORKER */
4614 }
4615 
4616 
4617 #ifdef AUTOKEY
4618 	/*
4619 	 * group_test - test if this is the same group
4620 	 *
4621 	 * host		assoc		return		action
4622 	 * none		none		0		mobilize *
4623 	 * none		group		0		mobilize *
4624 	 * group	none		0		mobilize *
4625 	 * group	group		1		mobilize
4626 	 * group	different	1		ignore
4627 	 * * ignore if notrust
4628 	 */
4629 int
4630 group_test(
4631 	char	*grp,
4632 	char	*ident
4633 	)
4634 {
4635 	if (grp == NULL)
4636 		return (0);
4637 
4638 	if (strcmp(grp, sys_groupname) == 0)
4639 		return (0);
4640 
4641 	if (ident == NULL)
4642 		return (1);
4643 
4644 	if (strcmp(grp, ident) == 0)
4645 		return (0);
4646 
4647 	return (1);
4648 }
4649 #endif /* AUTOKEY */
4650 
4651 
4652 #ifdef WORKER
4653 void
4654 pool_name_resolved(
4655 	int			rescode,
4656 	int			gai_errno,
4657 	void *			context,
4658 	const char *		name,
4659 	const char *		service,
4660 	const struct addrinfo *	hints,
4661 	const struct addrinfo *	res
4662 	)
4663 {
4664 	struct peer *	pool;	/* pool solicitor association */
4665 	associd_t	assoc;
4666 
4667 	if (rescode) {
4668 		msyslog(LOG_ERR,
4669 			"error resolving pool %s: %s (%d)",
4670 			name, gai_strerror(rescode), rescode);
4671 		return;
4672 	}
4673 
4674 	assoc = (associd_t)(intptr_t)context;
4675 	pool = findpeerbyassoc(assoc);
4676 	if (NULL == pool) {
4677 		msyslog(LOG_ERR,
4678 			"Could not find assoc %u for pool DNS %s",
4679 			assoc, name);
4680 		return;
4681 	}
4682 	DPRINTF(1, ("pool DNS %s completed\n", name));
4683 	pool->addrs = copy_addrinfo_list(res);
4684 	pool->ai = pool->addrs;
4685 	pool_xmit(pool);
4686 
4687 }
4688 #endif	/* WORKER */
4689 
4690 
4691 #ifdef AUTOKEY
4692 /*
4693  * key_expire - purge the key list
4694  */
4695 void
4696 key_expire(
4697 	struct peer *peer	/* peer structure pointer */
4698 	)
4699 {
4700 	int i;
4701 
4702 	if (peer->keylist != NULL) {
4703 		for (i = 0; i <= peer->keynumber; i++)
4704 			authtrust(peer->keylist[i], 0);
4705 		free(peer->keylist);
4706 		peer->keylist = NULL;
4707 	}
4708 	value_free(&peer->sndval);
4709 	peer->keynumber = 0;
4710 	peer->flags &= ~FLAG_ASSOC;
4711 	DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4712 		    peer->associd));
4713 }
4714 #endif	/* AUTOKEY */
4715 
4716 
4717 /*
4718  * local_refid(peer) - check peer refid to avoid selecting peers
4719  *		       currently synced to this ntpd.
4720  */
4721 static int
4722 local_refid(
4723 	struct peer *	p
4724 	)
4725 {
4726 	endpt *	unicast_ep;
4727 
4728 	if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4729 		unicast_ep = p->dstadr;
4730 	else
4731 		unicast_ep = findinterface(&p->srcadr);
4732 
4733 	if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4734 		return TRUE;
4735 	else
4736 		return FALSE;
4737 }
4738 
4739 
4740 /*
4741  * Determine if the peer is unfit for synchronization
4742  *
4743  * A peer is unfit for synchronization if
4744  * > TEST10 bad leap or stratum below floor or at or above ceiling
4745  * > TEST11 root distance exceeded for remote peer
4746  * > TEST12 a direct or indirect synchronization loop would form
4747  * > TEST13 unreachable or noselect
4748  */
4749 int				/* FALSE if fit, TRUE if unfit */
4750 peer_unfit(
4751 	struct peer *peer	/* peer structure pointer */
4752 	)
4753 {
4754 	int	rval = 0;
4755 
4756 	/*
4757 	 * A stratum error occurs if (1) the server has never been
4758 	 * synchronized, (2) the server stratum is below the floor or
4759 	 * greater than or equal to the ceiling.
4760 	 */
4761 	if (   peer->leap == LEAP_NOTINSYNC
4762 	    || peer->stratum < sys_floor
4763 	    || peer->stratum >= sys_ceiling) {
4764 		rval |= TEST10;		/* bad synch or stratum */
4765 	}
4766 
4767 	/*
4768 	 * A distance error for a remote peer occurs if the root
4769 	 * distance is greater than or equal to the distance threshold
4770 	 * plus the increment due to one host poll interval.
4771 	 */
4772 	if (   !(peer->flags & FLAG_REFCLOCK)
4773 	    && root_distance(peer) >= sys_maxdist
4774 				      + clock_phi * ULOGTOD(peer->hpoll)) {
4775 		rval |= TEST11;		/* distance exceeded */
4776 	}
4777 
4778 	/*
4779 	 * A loop error occurs if the remote peer is synchronized to the
4780 	 * local peer or if the remote peer is synchronized to the same
4781 	 * server as the local peer but only if the remote peer is
4782 	 * neither a reference clock nor an orphan.
4783 	 */
4784 	if (peer->stratum > 1 && local_refid(peer)) {
4785 		rval |= TEST12;		/* synchronization loop */
4786 	}
4787 
4788 	/*
4789 	 * An unreachable error occurs if the server is unreachable or
4790 	 * the noselect bit is set.
4791 	 */
4792 	if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
4793 		rval |= TEST13;		/* unreachable */
4794 	}
4795 
4796 	peer->flash &= ~PEER_TEST_MASK;
4797 	peer->flash |= rval;
4798 	return (rval);
4799 }
4800 
4801 
4802 /*
4803  * Find the precision of this particular machine
4804  */
4805 #define MINSTEP		20e-9	/* minimum clock increment (s) */
4806 #define MAXSTEP		1	/* maximum clock increment (s) */
4807 #define MINCHANGES	12	/* minimum number of step samples */
4808 #define MAXLOOPS	((int)(1. / MINSTEP))	/* avoid infinite loop */
4809 
4810 /*
4811  * This routine measures the system precision defined as the minimum of
4812  * a sequence of differences between successive readings of the system
4813  * clock. However, if a difference is less than MINSTEP, the clock has
4814  * been read more than once during a clock tick and the difference is
4815  * ignored. We set MINSTEP greater than zero in case something happens
4816  * like a cache miss, and to tolerate underlying system clocks which
4817  * ensure each reading is strictly greater than prior readings while
4818  * using an underlying stepping (not interpolated) clock.
4819  *
4820  * sys_tick and sys_precision represent the time to read the clock for
4821  * systems with high-precision clocks, and the tick interval or step
4822  * size for lower-precision stepping clocks.
4823  *
4824  * This routine also measures the time to read the clock on stepping
4825  * system clocks by counting the number of readings between changes of
4826  * the underlying clock.  With either type of clock, the minimum time
4827  * to read the clock is saved as sys_fuzz, and used to ensure the
4828  * get_systime() readings always increase and are fuzzed below sys_fuzz.
4829  */
4830 void
4831 measure_precision(void)
4832 {
4833 	/*
4834 	 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4835 	 * is effectively disabled.  trunc_os_clock is FALSE to disable
4836 	 * get_ostime() simulation of a low-precision system clock.
4837 	 */
4838 	set_sys_fuzz(0.);
4839 	trunc_os_clock = FALSE;
4840 	measured_tick = measure_tick_fuzz();
4841 	set_sys_tick_precision(measured_tick);
4842 	msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4843 		sys_tick * 1e6, sys_precision);
4844 	if (sys_fuzz < sys_tick) {
4845 		msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4846 			sys_fuzz * 1e6);
4847 	}
4848 }
4849 
4850 
4851 /*
4852  * measure_tick_fuzz()
4853  *
4854  * measures the minimum time to read the clock (stored in sys_fuzz)
4855  * and returns the tick, the larger of the minimum increment observed
4856  * between successive clock readings and the time to read the clock.
4857  */
4858 double
4859 measure_tick_fuzz(void)
4860 {
4861 	l_fp	minstep;	/* MINSTEP as l_fp */
4862 	l_fp	val;		/* current seconds fraction */
4863 	l_fp	last;		/* last seconds fraction */
4864 	l_fp	ldiff;		/* val - last */
4865 	double	tick;		/* computed tick value */
4866 	double	diff;
4867 	long	repeats;
4868 	long	max_repeats;
4869 	int	changes;
4870 	int	i;		/* log2 precision */
4871 
4872 	tick = MAXSTEP;
4873 	max_repeats = 0;
4874 	repeats = 0;
4875 	changes = 0;
4876 	DTOLFP(MINSTEP, &minstep);
4877 	get_systime(&last);
4878 	for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4879 		get_systime(&val);
4880 		ldiff = val;
4881 		L_SUB(&ldiff, &last);
4882 		last = val;
4883 		if (L_ISGT(&ldiff, &minstep)) {
4884 			max_repeats = max(repeats, max_repeats);
4885 			repeats = 0;
4886 			changes++;
4887 			LFPTOD(&ldiff, diff);
4888 			tick = min(diff, tick);
4889 		} else {
4890 			repeats++;
4891 		}
4892 	}
4893 	if (changes < MINCHANGES) {
4894 		msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4895 		exit(1);
4896 	}
4897 
4898 	if (0 == max_repeats) {
4899 		set_sys_fuzz(tick);
4900 	} else {
4901 		set_sys_fuzz(tick / max_repeats);
4902 	}
4903 
4904 	return tick;
4905 }
4906 
4907 
4908 void
4909 set_sys_tick_precision(
4910 	double tick
4911 	)
4912 {
4913 	int i;
4914 
4915 	if (tick > 1.) {
4916 		msyslog(LOG_ERR,
4917 			"unsupported tick %.3f > 1s ignored", tick);
4918 		return;
4919 	}
4920 	if (tick < measured_tick) {
4921 		msyslog(LOG_ERR,
4922 			"proto: tick %.3f less than measured tick %.3f, ignored",
4923 			tick, measured_tick);
4924 		return;
4925 	} else if (tick > measured_tick) {
4926 		trunc_os_clock = TRUE;
4927 		msyslog(LOG_NOTICE,
4928 			"proto: truncating system clock to multiples of %.9f",
4929 			tick);
4930 	}
4931 	sys_tick = tick;
4932 
4933 	/*
4934 	 * Find the nearest power of two.
4935 	 */
4936 	for (i = 0; tick <= 1; i--)
4937 		tick *= 2;
4938 	if (tick - 1 > 1 - tick / 2)
4939 		i++;
4940 
4941 	sys_precision = (s_char)i;
4942 }
4943 
4944 
4945 /*
4946  * init_proto - initialize the protocol module's data
4947  */
4948 void
4949 init_proto(void)
4950 {
4951 	l_fp	dummy;
4952 	int	i;
4953 
4954 	/*
4955 	 * Fill in the sys_* stuff.  Default is don't listen to
4956 	 * broadcasting, require authentication.
4957 	 */
4958 	set_sys_leap(LEAP_NOTINSYNC);
4959 	sys_stratum = STRATUM_UNSPEC;
4960 	memcpy(&sys_refid, "INIT", 4);
4961 	sys_peer = NULL;
4962 	sys_rootdelay = 0;
4963 	sys_rootdisp = 0;
4964 	L_CLR(&sys_reftime);
4965 	sys_jitter = 0;
4966 	measure_precision();
4967 	get_systime(&dummy);
4968 	sys_survivors = 0;
4969 	sys_manycastserver = 0;
4970 	sys_bclient = 0;
4971 	sys_bdelay = BDELAY_DEFAULT;	/*[Bug 3031] delay cutoff */
4972 	sys_authenticate = 1;
4973 	sys_stattime = current_time;
4974 	orphwait = current_time + sys_orphwait;
4975 	proto_clr_stats();
4976 	for (i = 0; i < MAX_TTL; ++i)
4977 		sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4978 	sys_ttlmax = (MAX_TTL - 1);
4979 	hardpps_enable = 0;
4980 	stats_control = 1;
4981 }
4982 
4983 
4984 /*
4985  * proto_config - configure the protocol module
4986  */
4987 void
4988 proto_config(
4989 	int	item,
4990 	u_long	value,
4991 	double	dvalue,
4992 	sockaddr_u *svalue
4993 	)
4994 {
4995 	/*
4996 	 * Figure out what he wants to change, then do it
4997 	 */
4998 	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4999 		    item, value, dvalue));
5000 
5001 	switch (item) {
5002 
5003 	/*
5004 	 * enable and disable commands - arguments are Boolean.
5005 	 */
5006 	case PROTO_AUTHENTICATE: /* authentication (auth) */
5007 		sys_authenticate = value;
5008 		break;
5009 
5010 	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
5011 		sys_bclient = (int)value;
5012 		if (sys_bclient == 0)
5013 			io_unsetbclient();
5014 		else
5015 			io_setbclient();
5016 		break;
5017 
5018 #ifdef REFCLOCK
5019 	case PROTO_CAL:		/* refclock calibrate (calibrate) */
5020 		cal_enable = value;
5021 		break;
5022 #endif /* REFCLOCK */
5023 
5024 	case PROTO_KERNEL:	/* kernel discipline (kernel) */
5025 		select_loop(value);
5026 		break;
5027 
5028 	case PROTO_MONITOR:	/* monitoring (monitor) */
5029 		if (value)
5030 			mon_start(MON_ON);
5031 		else {
5032 			mon_stop(MON_ON);
5033 			if (mon_enabled)
5034 				msyslog(LOG_WARNING,
5035 					"restrict: 'monitor' cannot be disabled while 'limited' is enabled");
5036 		}
5037 		break;
5038 
5039 	case PROTO_NTP:		/* NTP discipline (ntp) */
5040 		ntp_enable = value;
5041 		break;
5042 
5043 	case PROTO_MODE7:	/* mode7 management (ntpdc) */
5044 		ntp_mode7 = value;
5045 		break;
5046 
5047 	case PROTO_PPS:		/* PPS discipline (pps) */
5048 		hardpps_enable = value;
5049 		break;
5050 
5051 	case PROTO_FILEGEN:	/* statistics (stats) */
5052 		stats_control = value;
5053 		break;
5054 
5055 	/*
5056 	 * tos command - arguments are double, sometimes cast to int
5057 	 */
5058 
5059 	case PROTO_BCPOLLBSTEP:	/* Broadcast Poll Backstep gate (bcpollbstep) */
5060 		sys_bcpollbstep = (u_char)dvalue;
5061 		break;
5062 
5063 	case PROTO_BEACON:	/* manycast beacon (beacon) */
5064 		sys_beacon = (int)dvalue;
5065 		break;
5066 
5067 	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
5068 		sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
5069 		break;
5070 
5071 	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
5072 		sys_ceiling = (int)dvalue;
5073 		break;
5074 
5075 	case PROTO_COHORT:	/* cohort switch (cohort) */
5076 		sys_cohort = (int)dvalue;
5077 		break;
5078 
5079 	case PROTO_FLOOR:	/* stratum floor (floor) */
5080 		sys_floor = (int)dvalue;
5081 		break;
5082 
5083 	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
5084 		sys_maxclock = (int)dvalue;
5085 		break;
5086 
5087 	case PROTO_MAXDIST:	/* select threshold (maxdist) */
5088 		sys_maxdist = dvalue;
5089 		break;
5090 
5091 	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
5092 		break;		/* NOT USED */
5093 
5094 	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
5095 		sys_minclock = (int)dvalue;
5096 		break;
5097 
5098 	case PROTO_MINDISP:	/* minimum distance (mindist) */
5099 		sys_mindisp = dvalue;
5100 		break;
5101 
5102 	case PROTO_MINSANE:	/* minimum survivors (minsane) */
5103 		sys_minsane = (int)dvalue;
5104 		break;
5105 
5106 	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
5107 		sys_orphan = (int)dvalue;
5108 		break;
5109 
5110 	case PROTO_ORPHWAIT:	/* orphan wait (orphwait) */
5111 		orphwait -= sys_orphwait;
5112 		sys_orphwait = (int)dvalue;
5113 		orphwait += sys_orphwait;
5114 		break;
5115 
5116 	/*
5117 	 * Miscellaneous commands
5118 	 */
5119 	case PROTO_MULTICAST_ADD: /* add group address */
5120 		if (svalue != NULL)
5121 			io_multicast_add(svalue);
5122 		sys_bclient = 1;
5123 		break;
5124 
5125 	case PROTO_MULTICAST_DEL: /* delete group address */
5126 		if (svalue != NULL)
5127 			io_multicast_del(svalue);
5128 		break;
5129 
5130 	/*
5131 	 * Peer_clear Early policy choices
5132 	 */
5133 
5134 	case PROTO_PCEDIGEST:	/* Digest */
5135 		peer_clear_digest_early = value;
5136 		break;
5137 
5138 	/*
5139 	 * Unpeer Early policy choices
5140 	 */
5141 
5142 	case PROTO_UECRYPTO:	/* Crypto */
5143 		unpeer_crypto_early = value;
5144 		break;
5145 
5146 	case PROTO_UECRYPTONAK:	/* Crypto_NAK */
5147 		unpeer_crypto_nak_early = value;
5148 		break;
5149 
5150 	case PROTO_UEDIGEST:	/* Digest */
5151 		unpeer_digest_early = value;
5152 		break;
5153 
5154 	default:
5155 		msyslog(LOG_NOTICE,
5156 		    "proto: unsupported option %d", item);
5157 	}
5158 }
5159 
5160 
5161 /*
5162  * proto_clr_stats - clear protocol stat counters
5163  */
5164 void
5165 proto_clr_stats(void)
5166 {
5167 	sys_stattime = current_time;
5168 	sys_received = 0;
5169 	sys_processed = 0;
5170 	sys_newversion = 0;
5171 	sys_oldversion = 0;
5172 	sys_declined = 0;
5173 	sys_restricted = 0;
5174 	sys_badlength = 0;
5175 	sys_badauth = 0;
5176 	sys_limitrejected = 0;
5177 	sys_kodsent = 0;
5178 	sys_lamport = 0;
5179 	sys_tsrounding = 0;
5180 }
5181