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