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