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