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