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