Home | History | Annotate | Line # | Download | only in ntpd
      1 /*	$NetBSD: ntp_proto.c,v 1.20 2024/08/18 20:47:17 christos Exp $	*/
      2 
      3 /*
      4  * ntp_proto.c - NTP version 4 protocol machinery
      5  *
      6  * ATTENTION: Get approval from Harlan on all changes to this file!
      7  *	    (Harlan will be discussing these changes with Dave Mills.)
      8  *
      9  */
     10 #ifdef HAVE_CONFIG_H
     11 #include <config.h>
     12 #endif
     13 
     14 #include "ntpd.h"
     15 #include "ntp_stdlib.h"
     16 #include "ntp_unixtime.h"
     17 #include "ntp_control.h"
     18 #include "ntp_string.h"
     19 #include "ntp_leapsec.h"
     20 #include "ntp_psl.h"
     21 #include "refidsmear.h"
     22 
     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 
   2312 	/*
   2313 	 * Check for any kiss codes. Note this is only used when a server
   2314 	 * responds to a packet request.
   2315 	 */
   2316 
   2317 	/*
   2318 	 * Check to see if this is a RATE Kiss Code
   2319 	 * Currently this kiss code will accept whatever valid poll
   2320 	 * rate that the server sends
   2321 	 */
   2322 	if (   (NTP_MINPOLL > pkt->ppoll)
   2323 	    || (NTP_MAXPOLL < pkt->ppoll)
   2324 	   ) {
   2325 		DPRINTF(2, ("RATEKISS: Invalid ppoll (%d) from %s\n",
   2326 				pkt->ppoll, stoa(&rbufp->recv_srcadr)));
   2327 		sys_badlength++;
   2328 		return;			/* invalid packet poll */
   2329 	}
   2330 	peer->ppoll = max(peer->minpoll, pkt->ppoll);
   2331 	if (kissCode == RATEKISS) {
   2332 		peer->selbroken++;	/* Increment the KoD count */
   2333 		report_event(PEVNT_RATE, peer, NULL);
   2334 		if (pkt->ppoll > peer->minpoll)
   2335 			peer->minpoll = peer->ppoll;
   2336 		peer->burst = peer->retry = 0;
   2337 		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
   2338 		poll_update(peer, pkt->ppoll, 0);
   2339 		return;				/* kiss-o'-death */
   2340 	}
   2341 	if (kissCode != NOKISS) {
   2342 		peer->selbroken++;	/* Increment the KoD count */
   2343 		return;		/* Drop any other kiss code packets */
   2344 	}
   2345 
   2346 
   2347 	/*
   2348 	 * XXX
   2349 	 */
   2350 
   2351 
   2352 	/*
   2353 	 * If:
   2354 	 *	- this is a *cast (uni-, broad-, or m-) server packet
   2355 	 *	- and it's symmetric-key authenticated
   2356 	 * then see if the sender's IP is trusted for this keyid.
   2357 	 * If it is, great - nothing special to do here.
   2358 	 * Otherwise, we should report and bail.
   2359 	 *
   2360 	 * Autokey-authenticated packets are accepted.
   2361 	 */
   2362 
   2363 	switch (hismode) {
   2364 	    case MODE_SERVER:		/* server mode */
   2365 	    case MODE_BROADCAST:	/* broadcast mode */
   2366 	    case MODE_ACTIVE:		/* symmetric active mode */
   2367 	    case MODE_PASSIVE:		/* symmetric passive mode */
   2368 		if (   is_authentic == AUTH_OK
   2369 		    && skeyid
   2370 		    && skeyid <= NTP_MAXKEY
   2371 		    && !authistrustedip(skeyid, &peer->srcadr)) {
   2372 			report_event(PEVNT_AUTH, peer, "authIP");
   2373 			peer->badauth++;
   2374 			return;
   2375 		}
   2376 		break;
   2377 
   2378 	    case MODE_CLIENT:		/* client mode */
   2379 #if 0		/* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
   2380 	    case MODE_CONTROL:		/* control mode */
   2381 #endif
   2382 	    case MODE_PRIVATE:		/* private mode */
   2383 	    case MODE_BCLIENT:		/* broadcast client mode */
   2384 		break;
   2385 
   2386 	    case MODE_UNSPEC:		/* unspecified (old version) */
   2387 	    default:
   2388 		msyslog(LOG_INFO,
   2389 			"receive: Unexpected mode (%d) in packet from %s",
   2390 			hismode, ntoa(&peer->srcadr));
   2391 		break;
   2392 	}
   2393 
   2394 
   2395 	/*
   2396 	 * That was hard and I am sweaty, but the packet is squeaky
   2397 	 * clean. Get on with real work.
   2398 	 */
   2399 	peer->timereceived = current_time;
   2400 	peer->timelastrec = current_time;
   2401 	if (is_authentic == AUTH_OK)
   2402 		peer->flags |= FLAG_AUTHENTIC;
   2403 	else
   2404 		peer->flags &= ~FLAG_AUTHENTIC;
   2405 
   2406 #ifdef AUTOKEY
   2407 	/*
   2408 	 * More autokey dance. The rules of the cha-cha are as follows:
   2409 	 *
   2410 	 * 1. If there is no key or the key is not auto, do nothing.
   2411 	 *
   2412 	 * 2. If this packet is in response to the one just previously
   2413 	 *    sent or from a broadcast server, do the extension fields.
   2414 	 *    Otherwise, assume bogosity and bail out.
   2415 	 *
   2416 	 * 3. If an extension field contains a verified signature, it is
   2417 	 *    self-authenticated and we sit the dance.
   2418 	 *
   2419 	 * 4. If this is a server reply, check only to see that the
   2420 	 *    transmitted key ID matches the received key ID.
   2421 	 *
   2422 	 * 5. Check to see that one or more hashes of the current key ID
   2423 	 *    matches the previous key ID or ultimate original key ID
   2424 	 *    obtained from the broadcaster or symmetric peer. If no
   2425 	 *    match, sit the dance and call for new autokey values.
   2426 	 *
   2427 	 * In case of crypto error, fire the orchestra, stop dancing and
   2428 	 * restart the protocol.
   2429 	 */
   2430 	if (peer->flags & FLAG_SKEY) {
   2431 		/*
   2432 		 * Decrement remaining autokey hashes. This isn't
   2433 		 * perfect if a packet is lost, but results in no harm.
   2434 		 */
   2435 		ap = (struct autokey *)peer->recval.ptr;
   2436 		if (ap != NULL) {
   2437 			if (ap->seq > 0)
   2438 				ap->seq--;
   2439 		}
   2440 		peer->flash |= TEST8;
   2441 		rval = crypto_recv(peer, rbufp);
   2442 		if (rval == XEVNT_OK) {
   2443 			peer->unreach = 0;
   2444 		} else {
   2445 			if (rval == XEVNT_ERR) {
   2446 				report_event(PEVNT_RESTART, peer,
   2447 				    "crypto error");
   2448 				peer_clear(peer, "CRYP");
   2449 				peer->flash |= TEST9;	/* bad crypt */
   2450 				if (peer->flags & FLAG_PREEMPT) {
   2451 					if (unpeer_crypto_early) {
   2452 						unpeer(peer);
   2453 					}
   2454 				}
   2455 			}
   2456 			return;
   2457 		}
   2458 
   2459 		/*
   2460 		 * If server mode, verify the receive key ID matches
   2461 		 * the transmit key ID.
   2462 		 */
   2463 		if (hismode == MODE_SERVER) {
   2464 			if (skeyid == peer->keyid)
   2465 				peer->flash &= ~TEST8;
   2466 
   2467 		/*
   2468 		 * If an extension field is present, verify only that it
   2469 		 * has been correctly signed. We don't need a sequence
   2470 		 * check here, but the sequence continues.
   2471 		 */
   2472 		} else if (!(peer->flash & TEST8)) {
   2473 			peer->pkeyid = skeyid;
   2474 
   2475 		/*
   2476 		 * Now the fun part. Here, skeyid is the current ID in
   2477 		 * the packet, pkeyid is the ID in the last packet and
   2478 		 * tkeyid is the hash of skeyid. If the autokey values
   2479 		 * have not been received, this is an automatic error.
   2480 		 * If so, check that the tkeyid matches pkeyid. If not,
   2481 		 * hash tkeyid and try again. If the number of hashes
   2482 		 * exceeds the number remaining in the sequence, declare
   2483 		 * a successful failure and refresh the autokey values.
   2484 		 */
   2485 		} else if (ap != NULL) {
   2486 			int i;
   2487 
   2488 			for (i = 0; ; i++) {
   2489 				if (   tkeyid == peer->pkeyid
   2490 				    || tkeyid == ap->key) {
   2491 					peer->flash &= ~TEST8;
   2492 					peer->pkeyid = skeyid;
   2493 					ap->seq -= i;
   2494 					break;
   2495 				}
   2496 				if (i > ap->seq) {
   2497 					peer->crypto &=
   2498 					    ~CRYPTO_FLAG_AUTO;
   2499 					break;
   2500 				}
   2501 				tkeyid = session_key(
   2502 				    &rbufp->recv_srcadr, dstadr_sin,
   2503 				    tkeyid, pkeyid, 0);
   2504 			}
   2505 			if (peer->flash & TEST8)
   2506 				report_event(PEVNT_AUTH, peer, "keylist");
   2507 		}
   2508 		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
   2509 			peer->flash |= TEST8;	/* bad autokey */
   2510 
   2511 		/*
   2512 		 * The maximum lifetime of the protocol is about one
   2513 		 * week before restarting the Autokey protocol to
   2514 		 * refresh certificates and leapseconds values.
   2515 		 */
   2516 		if (current_time > peer->refresh) {
   2517 			report_event(PEVNT_RESTART, peer,
   2518 			    "crypto refresh");
   2519 			peer_clear(peer, "TIME");
   2520 			return;
   2521 		}
   2522 	}
   2523 #endif	/* AUTOKEY */
   2524 
   2525 	/*
   2526 	 * The dance is complete and the flash bits have been lit. Toss
   2527 	 * the packet over the fence for processing, which may light up
   2528 	 * more flashers. Leave if the packet is not good.
   2529 	 */
   2530 	process_packet(peer, pkt, rbufp->recv_length);
   2531 	/* Bug 2734: TEST3 prevents initial interleave sync */
   2532 	if ((~TEST3 & peer->flash) & PKT_TEST_MASK) {
   2533 		return;
   2534 	}
   2535 
   2536 	/* [bug 3592] Update poll. Ideally this should not happen in a
   2537 	 * receive branch, but too much is going on here... at least we
   2538 	 * do it only if the packet was good!
   2539 	 */
   2540 	poll_update(peer, peer->hpoll, (peer->hmode == MODE_CLIENT));
   2541 
   2542 	/*
   2543 	 * In interleaved mode update the state variables. Also adjust the
   2544 	 * transmit phase to avoid crossover.
   2545 	 */
   2546 	if (peer->flip != 0) {
   2547 		peer->rec = p_rec;
   2548 		peer->dst = rbufp->recv_time;
   2549 		if (peer->nextdate - current_time < (1U << min(peer->ppoll,
   2550 		    peer->hpoll)) / 2)
   2551 			peer->nextdate++;
   2552 		else
   2553 			peer->nextdate--;
   2554 	}
   2555 }
   2556 
   2557 
   2558 /*
   2559  * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
   2560  *	Or almost, at least.  If we're in here we have a reasonable
   2561  *	expectation that we will be having a long term
   2562  *	relationship with this host.
   2563  */
   2564 void
   2565 process_packet(
   2566 	register struct peer *peer,
   2567 	register struct pkt *pkt,
   2568 	u_int	len
   2569 	)
   2570 {
   2571 	double	t34, t21;
   2572 	double	p_offset, p_del, p_disp;
   2573 	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
   2574 	u_char	pmode, pleap, pversion, pstratum;
   2575 #ifdef ASSYM
   2576 	int	itemp;
   2577 	double	etemp, ftemp, td;
   2578 #endif /* ASSYM */
   2579 
   2580 	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
   2581 	p_offset = 0;
   2582 	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
   2583 	NTOHL_FP(&pkt->reftime, &p_reftime);
   2584 	NTOHL_FP(&pkt->org, &p_org);
   2585 	NTOHL_FP(&pkt->rec, &p_rec);
   2586 	NTOHL_FP(&pkt->xmt, &p_xmt);
   2587 	pmode = PKT_MODE(pkt->li_vn_mode);
   2588 	pleap = PKT_LEAP(pkt->li_vn_mode);
   2589 	pversion = PKT_VERSION(pkt->li_vn_mode);
   2590 	pstratum = PKT_TO_STRATUM(pkt->stratum);
   2591 
   2592 	/*
   2593 	 * Verify the server is synchronized; that is, the leap bits,
   2594 	 * stratum and root distance are valid.
   2595 	 */
   2596 	if (   pleap == LEAP_NOTINSYNC		/* test 6 */
   2597 	    || pstratum < sys_floor || pstratum >= sys_ceiling)
   2598 		peer->flash |= TEST6;		/* bad synch or strat */
   2599 	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
   2600 		peer->flash |= TEST7;		/* bad header */
   2601 
   2602 	/*
   2603 	 * If any tests fail at this point, the packet is discarded.
   2604 	 * Note that some flashers may have already been set in the
   2605 	 * receive() routine.
   2606 	 */
   2607 	if (peer->flash & PKT_TEST_MASK) {
   2608 		peer->seldisptoolarge++;
   2609 		DPRINTF(1, ("packet: flash header %04x\n",
   2610 			    peer->flash));
   2611 		/* [Bug 3592] do *not* update poll on bad packets! */
   2612 		return;
   2613 	}
   2614 
   2615 	/*
   2616 	 * update stats, now that we really handle this packet:
   2617 	 */
   2618 	sys_processed++;
   2619 	peer->processed++;
   2620 
   2621 	/*
   2622 	 * Capture the header values in the client/peer association..
   2623 	 */
   2624 	record_raw_stats(&peer->srcadr,
   2625 	    peer->dstadr ? &peer->dstadr->sin : NULL,
   2626 	    &p_org, &p_rec, &p_xmt, &peer->dst,
   2627 	    pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
   2628 	    p_del, p_disp, pkt->refid,
   2629 	    len - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
   2630 	peer->leap = pleap;
   2631 	peer->stratum = min(pstratum, STRATUM_UNSPEC);
   2632 	peer->pmode = pmode;
   2633 	peer->precision = pkt->precision;
   2634 	peer->rootdelay = p_del;
   2635 	peer->rootdisp = p_disp;
   2636 	peer->refid = pkt->refid;		/* network byte order */
   2637 	peer->reftime = p_reftime;
   2638 
   2639 	/*
   2640 	 * First, if either burst mode is armed, enable the burst.
   2641 	 * Compute the headway for the next packet and delay if
   2642 	 * necessary to avoid exceeding the threshold.
   2643 	 */
   2644 	if (peer->retry > 0) {
   2645 		peer->retry = 0;
   2646 		if (peer->reach)
   2647 			peer->burst = min(1 << (peer->hpoll -
   2648 			    peer->minpoll), NTP_SHIFT) - 1;
   2649 		else
   2650 			peer->burst = NTP_IBURST - 1;
   2651 		if (peer->burst > 0)
   2652 			peer->nextdate = current_time;
   2653 	}
   2654 
   2655 	/*
   2656 	 * If the peer was previously unreachable, raise a trap. In any
   2657 	 * case, mark it reachable.
   2658 	 */
   2659 	if (!peer->reach) {
   2660 		report_event(PEVNT_REACH, peer, NULL);
   2661 		peer->timereachable = current_time;
   2662 	}
   2663 	peer->reach |= 1;
   2664 
   2665 	/*
   2666 	 * For a client/server association, calculate the clock offset,
   2667 	 * roundtrip delay and dispersion. The equations are reordered
   2668 	 * from the spec for more efficient use of temporaries. For a
   2669 	 * broadcast association, offset the last measurement by the
   2670 	 * computed delay during the client/server volley. Note the
   2671 	 * computation of dispersion includes the system precision plus
   2672 	 * that due to the frequency error since the origin time.
   2673 	 *
   2674 	 * It is very important to respect the hazards of overflow. The
   2675 	 * only permitted operation on raw timestamps is subtraction,
   2676 	 * where the result is a signed quantity spanning from 68 years
   2677 	 * in the past to 68 years in the future. To avoid loss of
   2678 	 * precision, these calculations are done using 64-bit integer
   2679 	 * arithmetic. However, the offset and delay calculations are
   2680 	 * sums and differences of these first-order differences, which
   2681 	 * if done using 64-bit integer arithmetic, would be valid over
   2682 	 * only half that span. Since the typical first-order
   2683 	 * differences are usually very small, they are converted to 64-
   2684 	 * bit doubles and all remaining calculations done in floating-
   2685 	 * double arithmetic. This preserves the accuracy while
   2686 	 * retaining the 68-year span.
   2687 	 *
   2688 	 * There are three interleaving schemes, basic, interleaved
   2689 	 * symmetric and interleaved broadcast. The timestamps are
   2690 	 * idioscyncratically different. See the onwire briefing/white
   2691 	 * paper at www.eecis.udel.edu/~mills for details.
   2692 	 *
   2693 	 * Interleaved symmetric mode
   2694 	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
   2695 	 * t4 = peer->dst
   2696 	 */
   2697 	if (peer->flip != 0) {
   2698 		ci = p_xmt;				/* t3 - t4 */
   2699 		L_SUB(&ci, &peer->dst);
   2700 		LFPTOD(&ci, t34);
   2701 		ci = p_rec;				/* t2 - t1 */
   2702 		if (peer->flip > 0)
   2703 			L_SUB(&ci, &peer->borg);
   2704 		else
   2705 			L_SUB(&ci, &peer->aorg);
   2706 		LFPTOD(&ci, t21);
   2707 		p_del = t21 - t34;
   2708 		p_offset = (t21 + t34) / 2.;
   2709 		if (p_del < 0 || p_del > 1.) {
   2710 			mprintf_event(PEVNT_XERR, peer,
   2711 				      "t21 %.9f t34 %.9f", t21, t34);
   2712 			return;
   2713 		}
   2714 
   2715 	/*
   2716 	 * Broadcast modes
   2717 	 */
   2718 	} else if (peer->pmode == MODE_BROADCAST) {
   2719 
   2720 		/*
   2721 		 * Interleaved broadcast mode. Use interleaved timestamps.
   2722 		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
   2723 		 */
   2724 		if (peer->flags & FLAG_XB) {
   2725 			ci = p_org;			/* delay */
   2726 			L_SUB(&ci, &peer->aorg);
   2727 			LFPTOD(&ci, t34);
   2728 			ci = p_org;			/* t2 - t1 */
   2729 			L_SUB(&ci, &peer->borg);
   2730 			LFPTOD(&ci, t21);
   2731 			peer->aorg = p_xmt;
   2732 			peer->borg = peer->dst;
   2733 			if (t34 < 0 || t34 > 1.) {
   2734 				/* drop all if in the initial volley */
   2735 				if (FLAG_BC_VOL & peer->flags)
   2736 					goto bcc_init_volley_fail;
   2737 				mprintf_event(PEVNT_XERR, peer,
   2738 					      "offset %.9f delay %.9f",
   2739 					      t21, t34);
   2740 				return;
   2741 			}
   2742 			p_offset = t21;
   2743 			peer->xleave = t34;
   2744 
   2745 		/*
   2746 		 * Basic broadcast - use direct timestamps.
   2747 		 * t3 = p_xmt, t4 = peer->dst
   2748 		 */
   2749 		} else {
   2750 			ci = p_xmt;		/* t3 - t4 */
   2751 			L_SUB(&ci, &peer->dst);
   2752 			LFPTOD(&ci, t34);
   2753 			p_offset = t34;
   2754 		}
   2755 
   2756 		/*
   2757 		 * When calibration is complete and the clock is
   2758 		 * synchronized, the bias is calculated as the difference
   2759 		 * between the unicast timestamp and the broadcast
   2760 		 * timestamp. This works for both basic and interleaved
   2761 		 * modes.
   2762 		 * [Bug 3031] Don't keep this peer when the delay
   2763 		 * calculation gives reason to suspect clock steps.
   2764 		 * This is assumed for delays > 50ms.
   2765 		 */
   2766 		if (FLAG_BC_VOL & peer->flags) {
   2767 			peer->flags &= ~FLAG_BC_VOL;
   2768 			peer->delay = fabs(peer->offset - p_offset) * 2;
   2769 			DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
   2770 				peer->delay));
   2771 			if (peer->delay > fabs(sys_bdelay)) {
   2772 		bcc_init_volley_fail:
   2773 				DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
   2774 				unpeer(peer);
   2775 				return;
   2776 			}
   2777 		}
   2778 		peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
   2779 		p_del = peer->delay;
   2780 		p_offset += p_del / 2;
   2781 
   2782 
   2783 	/*
   2784 	 * Basic mode, otherwise known as the old fashioned way.
   2785 	 *
   2786 	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
   2787 	 */
   2788 	} else {
   2789 		ci = p_xmt;				/* t3 - t4 */
   2790 		L_SUB(&ci, &peer->dst);
   2791 		LFPTOD(&ci, t34);
   2792 		ci = p_rec;				/* t2 - t1 */
   2793 		L_SUB(&ci, &p_org);
   2794 		LFPTOD(&ci, t21);
   2795 		p_del = fabs(t21 - t34);
   2796 		p_offset = (t21 + t34) / 2.;
   2797 	}
   2798 	p_del = max(p_del, LOGTOD(sys_precision));
   2799 	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
   2800 	    clock_phi * p_del;
   2801 
   2802 #if ASSYM
   2803 	/*
   2804 	 * This code calculates the outbound and inbound data rates by
   2805 	 * measuring the differences between timestamps at different
   2806 	 * packet lengths. This is helpful in cases of large asymmetric
   2807 	 * delays commonly experienced on deep space communication
   2808 	 * links.
   2809 	 */
   2810 	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
   2811 		itemp = peer->t21_bytes - peer->t21_last;
   2812 		if (itemp > 25) {
   2813 			etemp = t21 - peer->t21;
   2814 			if (fabs(etemp) > 1e-6) {
   2815 				ftemp = itemp / etemp;
   2816 				if (ftemp > 1000.)
   2817 					peer->r21 = ftemp;
   2818 			}
   2819 		}
   2820 		itemp = len - peer->t34_bytes;
   2821 		if (itemp > 25) {
   2822 			etemp = -t34 - peer->t34;
   2823 			if (fabs(etemp) > 1e-6) {
   2824 				ftemp = itemp / etemp;
   2825 				if (ftemp > 1000.)
   2826 					peer->r34 = ftemp;
   2827 			}
   2828 		}
   2829 	}
   2830 
   2831 	/*
   2832 	 * The following section compensates for different data rates on
   2833 	 * the outbound (d21) and inbound (t34) directions. To do this,
   2834 	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
   2835 	 * the roundtrip delay. Then it calculates the correction as a
   2836 	 * fraction of d.
   2837 	 */
   2838 	peer->t21 = t21;
   2839 	peer->t21_last = peer->t21_bytes;
   2840 	peer->t34 = -t34;
   2841 	peer->t34_bytes = len;
   2842 	DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
   2843 		    peer->t21_bytes, peer->t34, peer->t34_bytes));
   2844 	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
   2845 		if (peer->pmode != MODE_BROADCAST)
   2846 			td = (peer->r34 / (peer->r21 + peer->r34) -
   2847 			    .5) * p_del;
   2848 		else
   2849 			td = 0;
   2850 
   2851 		/*
   2852 		 * Unfortunately, in many cases the errors are
   2853 		 * unacceptable, so for the present the rates are not
   2854 		 * used. In future, we might find conditions where the
   2855 		 * calculations are useful, so this should be considered
   2856 		 * a work in progress.
   2857 		 */
   2858 		t21 -= td;
   2859 		t34 -= td;
   2860 		DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
   2861 			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
   2862 			    td));
   2863 	}
   2864 #endif /* ASSYM */
   2865 
   2866 	/*
   2867 	 * That was awesome. Now hand off to the clock filter.
   2868 	 */
   2869 	clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
   2870 
   2871 	/*
   2872 	 * If we are in broadcast calibrate mode, return to broadcast
   2873 	 * client mode when the client is fit and the autokey dance is
   2874 	 * complete.
   2875 	 */
   2876 	if (   (FLAG_BC_VOL & peer->flags)
   2877 	    && MODE_CLIENT == peer->hmode
   2878 	    && !(TEST11 & peer_unfit(peer))) {	/* distance exceeded */
   2879 #ifdef AUTOKEY
   2880 		if (peer->flags & FLAG_SKEY) {
   2881 			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
   2882 				peer->hmode = MODE_BCLIENT;
   2883 		} else {
   2884 			peer->hmode = MODE_BCLIENT;
   2885 		}
   2886 #else	/* !AUTOKEY follows */
   2887 		peer->hmode = MODE_BCLIENT;
   2888 #endif	/* !AUTOKEY */
   2889 	}
   2890 }
   2891 
   2892 
   2893 /*
   2894  * clock_update - Called at system process update intervals.
   2895  */
   2896 static void
   2897 clock_update(
   2898 	struct peer *peer	/* peer structure pointer */
   2899 	)
   2900 {
   2901 	double	dtemp;
   2902 	l_fp	now;
   2903 #ifdef HAVE_LIBSCF_H
   2904 	char	*fmri;
   2905 #endif /* HAVE_LIBSCF_H */
   2906 
   2907 	/*
   2908 	 * Update the system state variables. We do this very carefully,
   2909 	 * as the poll interval might need to be clamped differently.
   2910 	 */
   2911 	sys_peer = peer;
   2912 	sys_epoch = peer->epoch;
   2913 	if (sys_poll < peer->minpoll)
   2914 		sys_poll = peer->minpoll;
   2915 	if (sys_poll > peer->maxpoll)
   2916 		sys_poll = peer->maxpoll;
   2917 	poll_update(peer, sys_poll, 0);
   2918 	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
   2919 	if (   peer->stratum == STRATUM_REFCLOCK
   2920 	    || peer->stratum == STRATUM_UNSPEC)
   2921 		sys_refid = peer->refid;
   2922 	else
   2923 		sys_refid = addr2refid(&peer->srcadr);
   2924 	/*
   2925 	 * Root Dispersion (E) is defined (in RFC 5905) as:
   2926 	 *
   2927 	 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
   2928 	 *
   2929 	 * where:
   2930 	 *  p.epsilon_r is the PollProc's root dispersion
   2931 	 *  p.epsilon   is the PollProc's dispersion
   2932 	 *  p.psi       is the PollProc's jitter
   2933 	 *  THETA       is the combined offset
   2934 	 *
   2935 	 * NB: Think Hard about where these numbers come from and
   2936 	 * what they mean.  When did peer->update happen?  Has anything
   2937 	 * interesting happened since then?  What values are the most
   2938 	 * defensible?  Why?
   2939 	 *
   2940 	 * DLM thinks this equation is probably the best of all worse choices.
   2941 	 */
   2942 	dtemp	= peer->rootdisp
   2943 		+ peer->disp
   2944 		+ sys_jitter
   2945 		+ clock_phi * (current_time - peer->update)
   2946 		+ fabs(sys_offset);
   2947 
   2948 	p2_rootdisp = prev_rootdisp;
   2949 	prev_rootdisp = sys_rootdisp;
   2950 	if (dtemp > sys_mindisp)
   2951 		sys_rootdisp = dtemp;
   2952 	else
   2953 		sys_rootdisp = sys_mindisp;
   2954 
   2955 	sys_rootdelay = peer->delay + peer->rootdelay;
   2956 
   2957 	p2_reftime = prev_reftime;
   2958 	p2_time = prev_time;
   2959 
   2960 	prev_reftime = sys_reftime;
   2961 	prev_time = current_time + 64 + (rand() & 0x3f);	/* 64-127 s */
   2962 
   2963 	sys_reftime = peer->dst;
   2964 
   2965 	DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
   2966 		    current_time, peer->epoch, peer->associd));
   2967 
   2968 	/*
   2969 	 * Comes now the moment of truth. Crank the clock discipline and
   2970 	 * see what comes out.
   2971 	 */
   2972 	switch (local_clock(peer, sys_offset)) {
   2973 
   2974 	/*
   2975 	 * Clock exceeds panic threshold. Life as we know it ends.
   2976 	 */
   2977 	case -1:
   2978 		msyslog(LOG_ERR, "Clock offset exceeds panic threshold.");
   2979 #ifdef HAVE_LIBSCF_H
   2980 		/*
   2981 		 * For Solaris enter the maintenance mode.
   2982 		 */
   2983 		if ((fmri = getenv("SMF_FMRI")) != NULL) {
   2984 			if (smf_maintain_instance(fmri, 0) < 0) {
   2985 				msyslog(LOG_ERR, "smf_maintain_instance: %s",
   2986 						 scf_strerror(scf_error()));
   2987 				exit(1);
   2988 			}
   2989 			/*
   2990 			 * Sleep until SMF kills us.
   2991 			 */
   2992 			msyslog(LOG_ERR, "%s placed into maintenance. "
   2993 				"Set system clock by hand before clearing.",
   2994 				fmri);
   2995 			for (;;)
   2996 				pause();
   2997 		}
   2998 #endif /* HAVE_LIBSCF_H */
   2999 		msyslog(LOG_ERR, "Set system clock by hand.");
   3000 		exit (-1);
   3001 		/* not reached */
   3002 
   3003 	/*
   3004 	 * Clock was stepped. Flush all time values of all peers.
   3005 	 */
   3006 	case 2:
   3007 		clear_all();
   3008 		set_sys_leap(LEAP_NOTINSYNC);
   3009 		sys_stratum = STRATUM_UNSPEC;
   3010 		memcpy(&sys_refid, "STEP", 4);
   3011 		sys_rootdelay = 0;
   3012 		p2_rootdisp = 0;
   3013 		prev_rootdisp = 0;
   3014 		sys_rootdisp = 0;
   3015 		L_CLR(&p2_reftime);	/* Should we clear p2_reftime? */
   3016 		L_CLR(&prev_reftime);	/* Should we clear prev_reftime? */
   3017 		L_CLR(&sys_reftime);
   3018 		sys_jitter = LOGTOD(sys_precision);
   3019 		leapsec_reset_frame();
   3020 		break;
   3021 
   3022 	/*
   3023 	 * Clock was slewed. Handle the leapsecond stuff.
   3024 	 */
   3025 	case 1:
   3026 
   3027 		/*
   3028 		 * If this is the first time the clock is set, reset the
   3029 		 * leap bits. If crypto, the timer will goose the setup
   3030 		 * process.
   3031 		 */
   3032 		if (sys_leap == LEAP_NOTINSYNC) {
   3033 			set_sys_leap(LEAP_NOWARNING);
   3034 #ifdef AUTOKEY
   3035 			if (crypto_flags)
   3036 				crypto_update();
   3037 #endif	/* AUTOKEY */
   3038 
   3039 		}
   3040 
   3041 		/*
   3042 		 * If there is no leap second pending and the number of
   3043 		 * survivor leap bits is greater than half the number of
   3044 		 * survivors, try to schedule a leap for the end of the
   3045 		 * current month. (This only works if no leap second for
   3046 		 * that range is in the table, so doing this more than
   3047 		 * once is mostly harmless.)
   3048 		 */
   3049 		if (leapsec == LSPROX_NOWARN) {
   3050 			if (   leap_vote_ins > leap_vote_del
   3051 			    && leap_vote_ins > sys_survivors / 2) {
   3052 				get_systime(&now);
   3053 				leapsec_add_dyn(TRUE, now.l_ui, NULL);
   3054 			}
   3055 			if (   leap_vote_del > leap_vote_ins
   3056 			    && leap_vote_del > sys_survivors / 2) {
   3057 				get_systime(&now);
   3058 				leapsec_add_dyn(FALSE, now.l_ui, NULL);
   3059 			}
   3060 		}
   3061 		break;
   3062 
   3063 	/*
   3064 	 * Popcorn spike or step threshold exceeded. Pretend it never
   3065 	 * happened.
   3066 	 */
   3067 	default:
   3068 		break;
   3069 	}
   3070 }
   3071 
   3072 
   3073 /*
   3074  * poll_update - update peer poll interval
   3075  */
   3076 void
   3077 poll_update(
   3078 	struct peer *peer,	/* peer structure pointer */
   3079 	u_char	mpoll,
   3080 	u_char  skewpoll
   3081 	)
   3082 {
   3083 	u_long	next, utemp, limit;
   3084 	u_char	hpoll;
   3085 
   3086 	/*
   3087 	 * This routine figures out when the next poll should be sent.
   3088 	 * That turns out to be wickedly complicated. One problem is
   3089 	 * that sometimes the time for the next poll is in the past when
   3090 	 * the poll interval is reduced. We watch out for races here
   3091 	 * between the receive process and the poll process.
   3092 	 *
   3093 	 * Clamp the poll interval between minpoll and maxpoll.
   3094 	 */
   3095 	hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
   3096 
   3097 #ifdef AUTOKEY
   3098 	/*
   3099 	 * If during the crypto protocol the poll interval has changed,
   3100 	 * the lifetimes in the key list are probably bogus. Purge the
   3101 	 * the key list and regenerate it later.
   3102 	 */
   3103 	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
   3104 		key_expire(peer);
   3105 #endif	/* AUTOKEY */
   3106 	peer->hpoll = hpoll;
   3107 
   3108 	/*
   3109 	 * There are three variables important for poll scheduling, the
   3110 	 * current time (current_time), next scheduled time (nextdate)
   3111 	 * and the earliest time (utemp). The earliest time is 2 s
   3112 	 * seconds, but could be more due to rate management. When
   3113 	 * sending in a burst, use the earliest time. When not in a
   3114 	 * burst but with a reply pending, send at the earliest time
   3115 	 * unless the next scheduled time has not advanced. This can
   3116 	 * only happen if multiple replies are pending in the same
   3117 	 * response interval. Otherwise, send at the later of the next
   3118 	 * scheduled time and the earliest time.
   3119 	 *
   3120 	 * Now we figure out if there is an override. If a burst is in
   3121 	 * progress and we get called from the receive process, just
   3122 	 * slink away. If called from the poll process, delay 1 s for a
   3123 	 * reference clock, otherwise 2 s.
   3124 	 */
   3125 	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
   3126 	    (1 << peer->minpoll), ntp_minpkt);
   3127 
   3128  	/*[Bug 3592] avoid unlimited postpone of next poll */
   3129 	limit = (2u << hpoll);
   3130 	if (limit > 64)
   3131 		limit -= (limit >> 2);
   3132 	limit += peer->outdate;
   3133 	if (limit < current_time)
   3134 		limit = current_time;
   3135 
   3136 	if (peer->burst > 0) {
   3137 		if (peer->nextdate > current_time)
   3138 			return;
   3139 #ifdef REFCLOCK
   3140 		else if (peer->flags & FLAG_REFCLOCK)
   3141 			peer->nextdate = current_time + RESP_DELAY;
   3142 #endif /* REFCLOCK */
   3143 		else
   3144 			peer->nextdate = utemp;
   3145 
   3146 #ifdef AUTOKEY
   3147 	/*
   3148 	 * If a burst is not in progress and a crypto response message
   3149 	 * is pending, delay 2 s, but only if this is a new interval.
   3150 	 */
   3151 	} else if (peer->cmmd != NULL) {
   3152 		if (peer->nextdate > current_time) {
   3153 			if (peer->nextdate + ntp_minpkt != utemp)
   3154 				peer->nextdate = utemp;
   3155 		} else {
   3156 			peer->nextdate = utemp;
   3157 		}
   3158 #endif	/* AUTOKEY */
   3159 
   3160 	/*
   3161 	 * The ordinary case. If a retry, use minpoll; if unreachable,
   3162 	 * use host poll; otherwise, use the minimum of host and peer
   3163 	 * polls; In other words, oversampling is okay but
   3164 	 * understampling is evil. Use the maximum of this value and the
   3165 	 * headway. If the average headway is greater than the headway
   3166 	 * threshold, increase the headway by the minimum interval.
   3167 	 */
   3168 	} else {
   3169 		if (peer->retry > 0)
   3170 			hpoll = peer->minpoll;
   3171 		else
   3172 			hpoll = min(peer->ppoll, peer->hpoll);
   3173 #ifdef REFCLOCK
   3174 		if (peer->flags & FLAG_REFCLOCK)
   3175 			next = 1 << hpoll;
   3176 		else
   3177 #endif /* REFCLOCK */
   3178 			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
   3179 			    hpoll) >> 12;
   3180 		next += peer->outdate;
   3181 		/* XXX: bug3596: Deal with poll skew list? */
   3182 		if (skewpoll) {
   3183 			psl_item psi;
   3184 
   3185 			if (0 == get_pollskew(hpoll, &psi)) {
   3186 				int sub = psi.sub;
   3187 				int qty = psi.qty;
   3188 				int msk = psi.msk;
   3189 				int val;
   3190 
   3191 				if (   0 != sub
   3192 				    || 0 != qty) {
   3193 					do {
   3194 						val = ntp_random() & msk;
   3195 					} while (val > qty);
   3196 
   3197 					next -= sub;
   3198 					next += val;
   3199 				}
   3200 			} else {
   3201 				/* get_pollskew() already logged this */
   3202 			}
   3203 		}
   3204 		if (next > utemp)
   3205 			peer->nextdate = next;
   3206 		else
   3207 			peer->nextdate = utemp;
   3208 		if (peer->throttle > (1 << peer->minpoll))
   3209 			peer->nextdate += ntp_minpkt;
   3210 	}
   3211 
   3212  	/*[Bug 3592] avoid unlimited postpone of next poll */
   3213 	if (peer->nextdate > limit) {
   3214 		DPRINTF(1, ("poll_update: clamp reached; limit %lu next %lu\n",
   3215 			    limit, peer->nextdate));
   3216 		peer->nextdate = limit;
   3217 	}
   3218 	DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
   3219 		    current_time, ntoa(&peer->srcadr), peer->hpoll,
   3220 		    peer->burst, peer->retry, peer->throttle,
   3221 		    utemp - current_time, peer->nextdate -
   3222 		    current_time));
   3223 }
   3224 
   3225 
   3226 /*
   3227  * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
   3228  * spec.
   3229  */
   3230 void
   3231 peer_clear(
   3232 	struct peer *peer,		/* peer structure */
   3233 	const char *ident		/* tally lights */
   3234 	)
   3235 {
   3236 	static u_long	earliest;
   3237 	u_char		u;
   3238 	l_fp		bxmt = peer->bxmt;	/* bcast clients retain this! */
   3239 
   3240 #ifdef AUTOKEY
   3241 	/*
   3242 	 * If cryptographic credentials have been acquired, toss them to
   3243 	 * Valhalla. Note that autokeys are ephemeral, in that they are
   3244 	 * tossed immediately upon use. Therefore, the keylist can be
   3245 	 * purged anytime without needing to preserve random keys. Note
   3246 	 * that, if the peer is purged, the cryptographic variables are
   3247 	 * purged, too. This makes it much harder to sneak in some
   3248 	 * unauthenticated data in the clock filter.
   3249 	 */
   3250 	key_expire(peer);
   3251 	if (peer->iffval != NULL)
   3252 		BN_free(peer->iffval);
   3253 	value_free(&peer->cookval);
   3254 	value_free(&peer->recval);
   3255 	value_free(&peer->encrypt);
   3256 	value_free(&peer->sndval);
   3257 	if (peer->cmmd != NULL)
   3258 		free(peer->cmmd);
   3259 	if (peer->subject != NULL)
   3260 		free(peer->subject);
   3261 	if (peer->issuer != NULL)
   3262 		free(peer->issuer);
   3263 #endif /* AUTOKEY */
   3264 
   3265 	/*
   3266 	 * Clear all values, including the optional crypto values above.
   3267 	 */
   3268 	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
   3269 	peer->ppoll = peer->maxpoll;
   3270 	peer->hpoll = peer->minpoll;
   3271 	peer->disp = MAXDISPERSE;
   3272 	peer->flash = peer_unfit(peer);
   3273 	peer->jitter = LOGTOD(sys_precision);
   3274 
   3275 	/* Don't throw away our broadcast replay protection */
   3276 	if (peer->hmode == MODE_BCLIENT)
   3277 		peer->bxmt = bxmt;
   3278 
   3279 	/*
   3280 	 * If interleave mode, initialize the alternate origin switch.
   3281 	 */
   3282 	if (peer->flags & FLAG_XLEAVE)
   3283 		peer->flip = 1;
   3284 	for (u = 0; u < NTP_SHIFT; u++) {
   3285 		peer->filter_order[u] = u;
   3286 		peer->filter_disp[u] = MAXDISPERSE;
   3287 	}
   3288 #ifdef REFCLOCK
   3289 	if (!(peer->flags & FLAG_REFCLOCK)) {
   3290 #endif
   3291 		peer->leap = LEAP_NOTINSYNC;
   3292 		peer->stratum = STRATUM_UNSPEC;
   3293 		memcpy(&peer->refid, ident, 4);
   3294 #ifdef REFCLOCK
   3295 	} else {
   3296 		/* Clear refclock sample filter */
   3297 		peer->procptr->codeproc = 0;
   3298 		peer->procptr->coderecv = 0;
   3299 	}
   3300 #endif
   3301 
   3302 	/*
   3303 	 * During initialization use the association count to spread out
   3304 	 * the polls at one-second intervals. Unconfigured associations'
   3305 	 * first poll is delayed by the "discard minimum" plus 1 to avoid
   3306 	 * rate limiting. Other post-startup new or cleared associations
   3307 	 * randomize the first poll over the minimum poll interval to
   3308 	 * avoid implosion.
   3309 	 */
   3310 	peer->nextdate = peer->update = peer->outdate = current_time;
   3311 	if (initializing) {
   3312 		peer->nextdate += peer_associations;
   3313 	} else if (!(FLAG_CONFIG & peer->flags)) {
   3314 		peer->nextdate += ntp_minpkt + 1;
   3315 		/* space out manycastclient first polls */
   3316 		if (peer->nextdate < earliest) {
   3317 			peer->nextdate = earliest;
   3318 		}
   3319 		earliest = peer->nextdate + 1;
   3320 	} else {
   3321 		peer->nextdate += ntp_random() % (1 << peer->minpoll);
   3322 	}
   3323 #ifdef AUTOKEY
   3324 	peer->refresh = current_time + (1 << NTP_REFRESH);
   3325 #endif	/* AUTOKEY */
   3326 	DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
   3327 		    current_time, peer->nextdate, peer->associd,
   3328 		    ident));
   3329 }
   3330 
   3331 
   3332 /*
   3333  * clock_filter - add incoming clock sample to filter register and run
   3334  *		  the filter procedure to find the best sample.
   3335  */
   3336 void
   3337 clock_filter(
   3338 	struct peer *peer,		/* peer structure pointer */
   3339 	double	sample_offset,		/* clock offset */
   3340 	double	sample_delay,		/* roundtrip delay */
   3341 	double	sample_disp		/* dispersion */
   3342 	)
   3343 {
   3344 	double	dst[NTP_SHIFT];		/* distance vector */
   3345 	u_char	ord[NTP_SHIFT];		/* index vector */
   3346 	short	i, j;
   3347 	u_char	k, m;
   3348 	double	dtemp, etemp;
   3349 
   3350 	/*
   3351 	 * A sample consists of the offset, delay, dispersion and epoch
   3352 	 * of arrival. The offset and delay are determined by the on-
   3353 	 * wire protocol. The dispersion grows from the last outbound
   3354 	 * packet to the arrival of this one increased by the sum of the
   3355 	 * peer precision and the system precision as required by the
   3356 	 * error budget. First, shift the new arrival into the shift
   3357 	 * register discarding the oldest one.
   3358 	 */
   3359 	j = peer->filter_nextpt;
   3360 	peer->filter_offset[j] = sample_offset;
   3361 	peer->filter_delay[j] = sample_delay;
   3362 	peer->filter_disp[j] = sample_disp;
   3363 	peer->filter_epoch[j] = current_time;
   3364 	j = (j + 1) % NTP_SHIFT;
   3365 	peer->filter_nextpt = (u_char)j;
   3366 
   3367 	/*
   3368 	 * Update dispersions since the last update and at the same
   3369 	 * time initialize the distance and index lists. Since samples
   3370 	 * become increasingly uncorrelated beyond the Allan intercept,
   3371 	 * only under exceptional cases will an older sample be used.
   3372 	 * Therefore, the distance list uses a compound metric. If the
   3373 	 * dispersion is greater than the maximum dispersion, clamp the
   3374 	 * distance at that value. If the time since the last update is
   3375 	 * less than the Allan intercept use the delay; otherwise, use
   3376 	 * the sum of the delay and dispersion.
   3377 	 */
   3378 	dtemp = clock_phi * (current_time - peer->update);
   3379 	peer->update = current_time;
   3380 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
   3381 		if (i != 0)
   3382 			peer->filter_disp[j] += dtemp;
   3383 		if (peer->filter_disp[j] >= MAXDISPERSE) {
   3384 			peer->filter_disp[j] = MAXDISPERSE;
   3385 			dst[i] = MAXDISPERSE;
   3386 		} else if (peer->update - peer->filter_epoch[j] >
   3387 		    (u_long)ULOGTOD(allan_xpt)) {
   3388 			dst[i] = peer->filter_delay[j] +
   3389 			    peer->filter_disp[j];
   3390 		} else {
   3391 			dst[i] = peer->filter_delay[j];
   3392 		}
   3393 		ord[i] = (u_char)j;
   3394 		j = (j + 1) % NTP_SHIFT;
   3395 	}
   3396 
   3397 	/*
   3398 	 * If the clock has stabilized, sort the samples by distance.
   3399 	 */
   3400 	if (freq_cnt == 0) {
   3401 		for (i = 1; i < NTP_SHIFT; i++) {
   3402 			for (j = 0; j < i; j++) {
   3403 				if (dst[j] > dst[i]) {
   3404 					k = ord[j];
   3405 					ord[j] = ord[i];
   3406 					ord[i] = k;
   3407 					etemp = dst[j];
   3408 					dst[j] = dst[i];
   3409 					dst[i] = etemp;
   3410 				}
   3411 			}
   3412 		}
   3413 	}
   3414 
   3415 	/*
   3416 	 * Copy the index list to the association structure so ntpq
   3417 	 * can see it later. Prune the distance list to leave only
   3418 	 * samples less than the maximum dispersion, which disfavors
   3419 	 * uncorrelated samples older than the Allan intercept. To
   3420 	 * further improve the jitter estimate, of the remainder leave
   3421 	 * only samples less than the maximum distance, but keep at
   3422 	 * least two samples for jitter calculation.
   3423 	 */
   3424 	m = 0;
   3425 	for (i = 0; i < NTP_SHIFT; i++) {
   3426 		peer->filter_order[i] = ord[i];
   3427 		if (   dst[i] >= MAXDISPERSE
   3428 		    || (m >= 2 && dst[i] >= sys_maxdist))
   3429 			continue;
   3430 		m++;
   3431 	}
   3432 
   3433 	/*
   3434 	 * Compute the dispersion and jitter. The dispersion is weighted
   3435 	 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
   3436 	 * to 1.0. The jitter is the RMS differences relative to the
   3437 	 * lowest delay sample.
   3438 	 */
   3439 	peer->disp = peer->jitter = 0;
   3440 	k = ord[0];
   3441 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
   3442 		j = ord[i];
   3443 		peer->disp = NTP_FWEIGHT * (  peer->disp
   3444 					    + peer->filter_disp[j]);
   3445 		if (i < m) {
   3446 			peer->jitter += DIFF(peer->filter_offset[j],
   3447 					     peer->filter_offset[k]);
   3448 		}
   3449 	}
   3450 
   3451 	/*
   3452 	 * If no acceptable samples remain in the shift register,
   3453 	 * quietly tiptoe home leaving only the dispersion. Otherwise,
   3454 	 * save the offset, delay and jitter. Note the jitter must not
   3455 	 * be less than the precision.
   3456 	 */
   3457 	if (0 == m) {
   3458 		clock_select();
   3459 		return;
   3460 	}
   3461 	etemp = fabs(peer->offset - peer->filter_offset[k]);
   3462 	peer->offset = peer->filter_offset[k];
   3463 	peer->delay = peer->filter_delay[k];
   3464 	if (m > 1) {
   3465 		peer->jitter /= m - 1;
   3466 	}
   3467 	peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
   3468 
   3469 	/*
   3470 	 * If the the new sample and the current sample are both valid
   3471 	 * and the difference between their offsets exceeds CLOCK_SGATE
   3472 	 * (3) times the jitter and the interval between them is less
   3473 	 * than twice the host poll interval, consider the new sample
   3474 	 * a popcorn spike and ignore it.
   3475 	 */
   3476 	if (   peer->disp < sys_maxdist
   3477 	    && peer->filter_disp[k] < sys_maxdist
   3478 	    && etemp > CLOCK_SGATE * peer->jitter
   3479 	    &&   peer->filter_epoch[k] - peer->epoch
   3480 	       < 2. * ULOGTOD(peer->hpoll)) {
   3481 		mprintf_event(PEVNT_POPCORN, peer, "%.9f s", etemp);
   3482 		return;
   3483 	}
   3484 
   3485 	/*
   3486 	 * A new minimum sample is useful only if it is later than the
   3487 	 * last one used. In this design the maximum lifetime of any
   3488 	 * sample is not greater than NTP_SHIFT (8) times the poll
   3489 	 * interval, so the maximum interval between minimum samples is
   3490 	 * NTP_SHIFT packets.
   3491 	 */
   3492 	if (peer->filter_epoch[k] <= peer->epoch) {
   3493 		DPRINTF(2, ("clock_filter: old sample %lu s\n",
   3494 			    current_time - peer->filter_epoch[k]));
   3495 		return;
   3496 	}
   3497 	peer->epoch = peer->filter_epoch[k];
   3498 
   3499 	/*
   3500 	 * The mitigated sample statistics are saved for later
   3501 	 * processing. If not synchronized or not in a burst, tickle the
   3502 	 * clock select algorithm.
   3503 	 */
   3504 	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer), peer->offset,
   3505 			  peer->delay, peer->disp, peer->jitter);
   3506 	DPRINTF(1, ("clock_filter: n %hu off %.9f del %.9f dsp %.9f jit %.9f\n",
   3507 		    (u_short)m, peer->offset, peer->delay, peer->disp,
   3508 		    peer->jitter));
   3509 	if (0 == peer->burst || LEAP_NOTINSYNC == sys_leap) {
   3510 		clock_select();
   3511 	}
   3512 }
   3513 
   3514 
   3515 /*
   3516  * clock_select - find the pick-of-the-litter clock
   3517  *
   3518  * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
   3519  * be enabled, even if declared falseticker, (2) only the prefer peer
   3520  * can be selected as the system peer, (3) if the external source is
   3521  * down, the system leap bits are set to 11 and the stratum set to
   3522  * infinity.
   3523  */
   3524 void
   3525 clock_select(void)
   3526 {
   3527 	struct peer *peer;
   3528 	int	i, j, k, n;
   3529 	int	nlist, nl2;
   3530 	int	allow;
   3531 	int	speer;
   3532 	double	d, e, f, g;
   3533 	double	high, low;
   3534 	double	speermet;
   3535 	double	lastresort_dist = MAXDISPERSE;
   3536 	double	orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
   3537 	struct endpoint endp;
   3538 	struct peer *osys_peer;
   3539 	struct peer *sys_prefer = NULL;	/* prefer peer */
   3540 	struct peer *typesystem = NULL;
   3541 	struct peer *typelastresort = NULL;
   3542 	struct peer *typeorphan = NULL;
   3543 #ifdef REFCLOCK
   3544 	struct peer *typeacts = NULL;
   3545 	struct peer *typelocal = NULL;
   3546 	struct peer *typepps = NULL;
   3547 #endif /* REFCLOCK */
   3548 	static struct endpoint *endpoint = NULL;
   3549 	static int *indx = NULL;
   3550 	static peer_select *peers = NULL;
   3551 	static u_int endpoint_size = 0;
   3552 	static u_int peers_size = 0;
   3553 	static u_int indx_size = 0;
   3554 	size_t octets;
   3555 
   3556 	/*
   3557 	 * Initialize and create endpoint, index and peer lists big
   3558 	 * enough to handle all associations.
   3559 	 */
   3560 	osys_peer = sys_peer;
   3561 	sys_survivors = 0;
   3562 #ifdef LOCKCLOCK
   3563 	set_sys_leap(LEAP_NOTINSYNC);
   3564 	sys_stratum = STRATUM_UNSPEC;
   3565 	memcpy(&sys_refid, "DOWN", 4);
   3566 #endif /* LOCKCLOCK */
   3567 
   3568 	/*
   3569 	 * Allocate dynamic space depending on the number of
   3570 	 * associations.
   3571 	 */
   3572 	nlist = 1;
   3573 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
   3574 		nlist++;
   3575 	endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
   3576 	peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
   3577 	indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
   3578 	octets = endpoint_size + peers_size + indx_size;
   3579 	endpoint = erealloc(endpoint, octets);
   3580 	peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
   3581 	indx = INC_ALIGNED_PTR(peers, peers_size);
   3582 
   3583 	/*
   3584 	 * Initially, we populate the island with all the rifraff peers
   3585 	 * that happen to be lying around. Those with seriously
   3586 	 * defective clocks are immediately booted off the island. Then,
   3587 	 * the falsetickers are culled and put to sea. The truechimers
   3588 	 * remaining are subject to repeated rounds where the most
   3589 	 * unpopular at each round is kicked off. When the population
   3590 	 * has dwindled to sys_minclock, the survivors split a million
   3591 	 * bucks and collectively crank the chimes.
   3592 	 */
   3593 	nlist = nl2 = 0;	/* none yet */
   3594 	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
   3595 		peer->new_status = CTL_PST_SEL_REJECT;
   3596 
   3597 		/*
   3598 		 * Leave the island immediately if the peer is
   3599 		 * unfit to synchronize.
   3600 		 */
   3601 		if (peer_unfit(peer)) {
   3602 			continue;
   3603 		}
   3604 
   3605 		/*
   3606 		 * If we have never been synchronised, look for any peer
   3607 		 * which has ever been synchronised and pick the one which
   3608 		 * has the lowest root distance. This can be used as a last
   3609 		 * resort if all else fails. Once we get an initial sync
   3610 		 * with this peer, sys_reftime gets set and so this
   3611 		 * function becomes disabled.
   3612 		 */
   3613 		if (L_ISZERO(&sys_reftime)) {
   3614 			d = root_distance(peer);
   3615 			if (!L_ISZERO(&peer->reftime) && d < lastresort_dist) {
   3616 				typelastresort = peer;
   3617 				lastresort_dist = d;
   3618 			}
   3619 		}
   3620 
   3621 		/*
   3622 		 * If this peer is an orphan parent, elect the
   3623 		 * one with the lowest metric defined as the
   3624 		 * IPv4 address or the first 64 bits of the
   3625 		 * hashed IPv6 address.  To ensure convergence
   3626 		 * on the same selected orphan, consider as
   3627 		 * well that this system may have the lowest
   3628 		 * metric and be the orphan parent.  If this
   3629 		 * system wins, sys_peer will be NULL to trigger
   3630 		 * orphan mode in timer().
   3631 		 */
   3632 		if (peer->stratum == sys_orphan) {
   3633 			u_int32	localmet;
   3634 			u_int32 peermet;
   3635 
   3636 			if (peer->dstadr != NULL)
   3637 				localmet = ntohl(peer->dstadr->addr_refid);
   3638 			else
   3639 				localmet = U_INT32_MAX;
   3640 			peermet = ntohl(addr2refid(&peer->srcadr));
   3641 			if (peermet < localmet && peermet < orphmet) {
   3642 				typeorphan = peer;
   3643 				orphmet = peermet;
   3644 			}
   3645 			continue;
   3646 		}
   3647 
   3648 		/*
   3649 		 * If this peer could have the orphan parent
   3650 		 * as a synchronization ancestor, exclude it
   3651 		 * from selection to avoid forming a
   3652 		 * synchronization loop within the orphan mesh,
   3653 		 * triggering stratum climb to infinity
   3654 		 * instability.  Peers at stratum higher than
   3655 		 * the orphan stratum could have the orphan
   3656 		 * parent in ancestry so are excluded.
   3657 		 * See http://bugs.ntp.org/2050
   3658 		 */
   3659 		if (peer->stratum > sys_orphan) {
   3660 			continue;
   3661 		}
   3662 #ifdef REFCLOCK
   3663 		/*
   3664 		 * The following are special cases. We deal
   3665 		 * with them later.
   3666 		 */
   3667 		if (!(peer->flags & FLAG_PREFER)) {
   3668 			switch (peer->refclktype) {
   3669 			case REFCLK_LOCALCLOCK:
   3670 				if (   current_time > orphwait
   3671 				    && typelocal == NULL)
   3672 					typelocal = peer;
   3673 				continue;
   3674 
   3675 			case REFCLK_ACTS:
   3676 				if (   current_time > orphwait
   3677 				    && typeacts == NULL)
   3678 					typeacts = peer;
   3679 				continue;
   3680 			}
   3681 		}
   3682 #endif /* REFCLOCK */
   3683 
   3684 		/*
   3685 		 * If we get this far, the peer can stay on the
   3686 		 * island, but does not yet have the immunity
   3687 		 * idol.
   3688 		 */
   3689 		peer->new_status = CTL_PST_SEL_SANE;
   3690 		f = root_distance(peer);
   3691 		peers[nlist].peer = peer;
   3692 		peers[nlist].error = peer->jitter;
   3693 		peers[nlist].synch = f;
   3694 		nlist++;
   3695 
   3696 		/*
   3697 		 * Insert each interval endpoint on the unsorted
   3698 		 * endpoint[] list.
   3699 		 */
   3700 		e = peer->offset;
   3701 		endpoint[nl2].type = -1;	/* lower end */
   3702 		endpoint[nl2].val = e - f;
   3703 		nl2++;
   3704 		endpoint[nl2].type = 1;		/* upper end */
   3705 		endpoint[nl2].val = e + f;
   3706 		nl2++;
   3707 	}
   3708 	/*
   3709 	 * Construct sorted indx[] of endpoint[] indexes ordered by
   3710 	 * offset.
   3711 	 */
   3712 	for (i = 0; i < nl2; i++)
   3713 		indx[i] = i;
   3714 	for (i = 0; i < nl2; i++) {
   3715 		endp = endpoint[indx[i]];
   3716 		e = endp.val;
   3717 		k = i;
   3718 		for (j = i + 1; j < nl2; j++) {
   3719 			endp = endpoint[indx[j]];
   3720 			if (endp.val < e) {
   3721 				e = endp.val;
   3722 				k = j;
   3723 			}
   3724 		}
   3725 		if (k != i) {
   3726 			j = indx[k];
   3727 			indx[k] = indx[i];
   3728 			indx[i] = j;
   3729 		}
   3730 	}
   3731 	for (i = 0; i < nl2; i++)
   3732 		DPRINTF(3, ("select: endpoint %2d %.6f\n",
   3733 			endpoint[indx[i]].type, endpoint[indx[i]].val));
   3734 
   3735 	/*
   3736 	 * This is the actual algorithm that cleaves the truechimers
   3737 	 * from the falsetickers. The original algorithm was described
   3738 	 * in Keith Marzullo's dissertation, but has been modified for
   3739 	 * better accuracy.
   3740 	 *
   3741 	 * Briefly put, we first assume there are no falsetickers, then
   3742 	 * scan the candidate list first from the low end upwards and
   3743 	 * then from the high end downwards. The scans stop when the
   3744 	 * number of intersections equals the number of candidates less
   3745 	 * the number of falsetickers. If this doesn't happen for a
   3746 	 * given number of falsetickers, we bump the number of
   3747 	 * falsetickers and try again. If the number of falsetickers
   3748 	 * becomes equal to or greater than half the number of
   3749 	 * candidates, the Albanians have won the Byzantine wars and
   3750 	 * correct synchronization is not possible.
   3751 	 *
   3752 	 * Here, nlist is the number of candidates and allow is the
   3753 	 * number of falsetickers. Upon exit, the truechimers are the
   3754 	 * survivors with offsets not less than low and not greater than
   3755 	 * high. There may be none of them.
   3756 	 */
   3757 	low = 1e9;
   3758 	high = -1e9;
   3759 	for (allow = 0; 2 * allow < nlist; allow++) {
   3760 
   3761 		/*
   3762 		 * Bound the interval (low, high) as the smallest
   3763 		 * interval containing points from the most sources.
   3764 		 */
   3765 		n = 0;
   3766 		for (i = 0; i < nl2; i++) {
   3767 			low = endpoint[indx[i]].val;
   3768 			n -= endpoint[indx[i]].type;
   3769 			if (n >= nlist - allow)
   3770 				break;
   3771 		}
   3772 		n = 0;
   3773 		for (j = nl2 - 1; j >= 0; j--) {
   3774 			high = endpoint[indx[j]].val;
   3775 			n += endpoint[indx[j]].type;
   3776 			if (n >= nlist - allow)
   3777 				break;
   3778 		}
   3779 
   3780 		/*
   3781 		 * If an interval containing truechimers is found, stop.
   3782 		 * If not, increase the number of falsetickers and go
   3783 		 * around again.
   3784 		 */
   3785 		if (high > low)
   3786 			break;
   3787 	}
   3788 
   3789 	/*
   3790 	 * Clustering algorithm. Whittle candidate list of falsetickers,
   3791 	 * who leave the island immediately. The TRUE peer is always a
   3792 	 * truechimer. We must leave at least one peer to collect the
   3793 	 * million bucks.
   3794 	 *
   3795 	 * We assert the correct time is contained in the interval, but
   3796 	 * the best offset estimate for the interval might not be
   3797 	 * contained in the interval. For this purpose, a truechimer is
   3798 	 * defined as the midpoint of an interval that overlaps the
   3799 	 * intersection interval.
   3800 	 */
   3801 	j = 0;
   3802 	for (i = 0; i < nlist; i++) {
   3803 		double	h;
   3804 
   3805 		peer = peers[i].peer;
   3806 		h = peers[i].synch;
   3807 		if ((   high <= low
   3808 		     || peer->offset + h < low
   3809 		     || peer->offset - h > high
   3810 		    ) && !(peer->flags & FLAG_TRUE))
   3811 			continue;
   3812 
   3813 #ifdef REFCLOCK
   3814 		/*
   3815 		 * Eligible PPS peers must survive the intersection
   3816 		 * algorithm. Use the first one found, but don't
   3817 		 * include any of them in the cluster population.
   3818 		 */
   3819 		if (peer->flags & FLAG_PPS) {
   3820 			if (typepps == NULL)
   3821 				typepps = peer;
   3822 			if (!(peer->flags & FLAG_TSTAMP_PPS))
   3823 				continue;
   3824 		}
   3825 #endif /* REFCLOCK */
   3826 
   3827 		if (j != i)
   3828 			peers[j] = peers[i];
   3829 		j++;
   3830 	}
   3831 	nlist = j;
   3832 
   3833 	/*
   3834 	 * If no survivors remain at this point, check if the modem
   3835 	 * driver, local driver or orphan parent in that order. If so,
   3836 	 * nominate the first one found as the only survivor.
   3837 	 * Otherwise, give up and leave the island to the rats.
   3838 	 */
   3839 	if (nlist == 0) {
   3840 		peers[0].error = 0;
   3841 		peers[0].synch = sys_mindisp;
   3842 #ifdef REFCLOCK
   3843 		if (typeacts != NULL) {
   3844 			peers[0].peer = typeacts;
   3845 			nlist = 1;
   3846 		} else if (typelocal != NULL) {
   3847 			peers[0].peer = typelocal;
   3848 			nlist = 1;
   3849 		} else
   3850 #endif /* REFCLOCK */
   3851 		if (typeorphan != NULL) {
   3852 			peers[0].peer = typeorphan;
   3853 			nlist = 1;
   3854 		} else if (typelastresort != NULL) {
   3855 			peers[0].peer = typelastresort;
   3856 			nlist = 1;
   3857 		}
   3858 	}
   3859 
   3860 	/*
   3861 	 * Mark the candidates at this point as truechimers.
   3862 	 */
   3863 	for (i = 0; i < nlist; i++) {
   3864 		peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
   3865 		DPRINTF(2, ("select: survivor %s %f\n",
   3866 			stoa(&peers[i].peer->srcadr), peers[i].synch));
   3867 	}
   3868 
   3869 	/*
   3870 	 * Now, vote outliers off the island by select jitter weighted
   3871 	 * by root distance. Continue voting as long as there are more
   3872 	 * than sys_minclock survivors and the select jitter of the peer
   3873 	 * with the worst metric is greater than the minimum peer
   3874 	 * jitter. Stop if we are about to discard a TRUE or PREFER
   3875 	 * peer, who of course have the immunity idol.
   3876 	 */
   3877 	while (1) {
   3878 		d = 1e9;
   3879 		e = -1e9;
   3880 		g = 0;
   3881 		k = 0;
   3882 		for (i = 0; i < nlist; i++) {
   3883 			if (peers[i].error < d)
   3884 				d = peers[i].error;
   3885 			peers[i].seljit = 0;
   3886 			if (nlist > 1) {
   3887 				f = 0;
   3888 				for (j = 0; j < nlist; j++)
   3889 					f += DIFF(peers[j].peer->offset,
   3890 					    peers[i].peer->offset);
   3891 				peers[i].seljit = SQRT(f / (nlist - 1));
   3892 			}
   3893 			if (peers[i].seljit * peers[i].synch > e) {
   3894 				g = peers[i].seljit;
   3895 				e = peers[i].seljit * peers[i].synch;
   3896 				k = i;
   3897 			}
   3898 		}
   3899 		g = max(g, LOGTOD(sys_precision));
   3900 		if (   nlist <= max(1, sys_minclock)
   3901 		    || g <= d
   3902 		    || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
   3903 			break;
   3904 
   3905 		DPRINTF(3, ("select: drop %s seljit %.9f jit %.9f\n",
   3906 			ntoa(&peers[k].peer->srcadr), g, d));
   3907 		if (nlist > sys_maxclock)
   3908 			peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
   3909 		for (j = k + 1; j < nlist; j++)
   3910 			peers[j - 1] = peers[j];
   3911 		nlist--;
   3912 	}
   3913 
   3914 	/*
   3915 	 * What remains is a list usually not greater than sys_minclock
   3916 	 * peers. Note that unsynchronized peers cannot survive this
   3917 	 * far.  Count and mark these survivors.
   3918 	 *
   3919 	 * While at it, count the number of leap warning bits found.
   3920 	 * This will be used later to vote the system leap warning bit.
   3921 	 * If a leap warning bit is found on a reference clock, the vote
   3922 	 * is always won.
   3923 	 *
   3924 	 * Choose the system peer using a hybrid metric composed of the
   3925 	 * selection jitter scaled by the root distance augmented by
   3926 	 * stratum scaled by sys_mindisp (.001 by default). The goal of
   3927 	 * the small stratum factor is to avoid clockhop between a
   3928 	 * reference clock and a network peer which has a refclock and
   3929 	 * is using an older ntpd, which does not floor sys_rootdisp at
   3930 	 * sys_mindisp.
   3931 	 *
   3932 	 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
   3933 	 * in selecting the system peer, using a weight of 1 second of
   3934 	 * additional root distance per stratum.  This heavy bias is no
   3935 	 * longer appropriate, as the scaled root distance provides a
   3936 	 * more rational metric carrying the cumulative error budget.
   3937 	 */
   3938 	e = 1e9;
   3939 	speer = 0;
   3940 	leap_vote_ins = 0;
   3941 	leap_vote_del = 0;
   3942 	for (i = 0; i < nlist; i++) {
   3943 		peer = peers[i].peer;
   3944 		peer->unreach = 0;
   3945 		peer->new_status = CTL_PST_SEL_SYNCCAND;
   3946 		sys_survivors++;
   3947 		if (peer->leap == LEAP_ADDSECOND) {
   3948 			if (peer->flags & FLAG_REFCLOCK)
   3949 				leap_vote_ins = nlist;
   3950 			else if (leap_vote_ins < nlist)
   3951 				leap_vote_ins++;
   3952 		}
   3953 		if (peer->leap == LEAP_DELSECOND) {
   3954 			if (peer->flags & FLAG_REFCLOCK)
   3955 				leap_vote_del = nlist;
   3956 			else if (leap_vote_del < nlist)
   3957 				leap_vote_del++;
   3958 		}
   3959 		if (peer->flags & FLAG_PREFER)
   3960 			sys_prefer = peer;
   3961 		speermet = peers[i].seljit * peers[i].synch +
   3962 		    peer->stratum * sys_mindisp;
   3963 		if (speermet < e) {
   3964 			e = speermet;
   3965 			speer = i;
   3966 		}
   3967 	}
   3968 
   3969 	/*
   3970 	 * Unless there are at least sys_misane survivors, leave the
   3971 	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
   3972 	 * use the selected survivor speer. However, if the current
   3973 	 * system peer is not speer, stay with the current system peer
   3974 	 * as long as it doesn't get too old or too ugly.
   3975 	 */
   3976 	if (nlist > 0 && nlist >= sys_minsane) {
   3977 		double	x;
   3978 
   3979 		typesystem = peers[speer].peer;
   3980 		if (osys_peer == NULL || osys_peer == typesystem) {
   3981 			sys_clockhop = 0;
   3982 		} else if ((x = fabs(typesystem->offset -
   3983 		    osys_peer->offset)) < sys_mindisp) {
   3984 			if (0 == sys_clockhop)
   3985 				sys_clockhop = sys_mindisp;
   3986 			else
   3987 				sys_clockhop *= .5;
   3988 			DPRINTF(1, ("select: clockhop %d %.9f %.9f\n",
   3989 				j, x, sys_clockhop));
   3990 			if (x < sys_clockhop)
   3991 				typesystem = osys_peer;
   3992 			else
   3993 				sys_clockhop = 0;
   3994 		} else {
   3995 			sys_clockhop = 0;
   3996 		}
   3997 	}
   3998 
   3999 	/*
   4000 	 * Mitigation rules of the game. We have the pick of the
   4001 	 * litter in typesystem if any survivors are left. If
   4002 	 * there is a prefer peer, use its offset and jitter.
   4003 	 * Otherwise, use the combined offset and jitter of all kitters.
   4004 	 */
   4005 	if (typesystem != NULL) {
   4006 		if (sys_prefer == NULL) {
   4007 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
   4008 			clock_combine(peers, sys_survivors, speer);
   4009 		} else {
   4010 			typesystem = sys_prefer;
   4011 			sys_clockhop = 0;
   4012 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
   4013 			sys_offset = typesystem->offset;
   4014 			sys_jitter = typesystem->jitter;
   4015 		}
   4016 		DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
   4017 			sys_offset, sys_jitter));
   4018 	}
   4019 #ifdef REFCLOCK
   4020 	/*
   4021 	 * If a PPS driver is lit and the combined offset is less than
   4022 	 * 0.4 s, select the driver as the PPS peer and use its offset
   4023 	 * and jitter. However, if this is the atom driver, use it only
   4024 	 * if there is a prefer peer or there are no survivors and none
   4025 	 * are required.
   4026 	 */
   4027 	if (   typepps != NULL
   4028 	    && fabs(sys_offset) < 0.4
   4029 	    && (   typepps->refclktype != REFCLK_ATOM_PPS
   4030 		|| (   typepps->refclktype == REFCLK_ATOM_PPS
   4031 		    && (   sys_prefer != NULL
   4032 			|| (typesystem == NULL && sys_minsane == 0))))) {
   4033 		typesystem = typepps;
   4034 		sys_clockhop = 0;
   4035 		typesystem->new_status = CTL_PST_SEL_PPS;
   4036 		sys_offset = typesystem->offset;
   4037 		sys_jitter = typesystem->jitter;
   4038 		DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
   4039 			sys_offset, sys_jitter));
   4040 	}
   4041 #endif /* REFCLOCK */
   4042 
   4043 	/*
   4044 	 * If there are no survivors at this point, there is no
   4045 	 * system peer. If so and this is an old update, keep the
   4046 	 * current statistics, but do not update the clock.
   4047 	 */
   4048 	if (typesystem == NULL) {
   4049 		if (osys_peer != NULL) {
   4050 			orphwait = current_time + sys_orphwait;
   4051 			report_event(EVNT_NOPEER, NULL, NULL);
   4052 		}
   4053 		sys_peer = NULL;
   4054 		for (peer = peer_list; peer != NULL; peer = peer->p_link)
   4055 			peer->status = peer->new_status;
   4056 		return;
   4057 	}
   4058 
   4059 	/*
   4060 	 * Do not use old data, as this may mess up the clock discipline
   4061 	 * stability.
   4062 	 */
   4063 	if (typesystem->epoch <= sys_epoch)
   4064 		return;
   4065 
   4066 	/*
   4067 	 * We have found the alpha male. Wind the clock.
   4068 	 */
   4069 	if (osys_peer != typesystem)
   4070 		report_event(PEVNT_NEWPEER, typesystem, NULL);
   4071 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
   4072 		peer->status = peer->new_status;
   4073 	clock_update(typesystem);
   4074 }
   4075 
   4076 
   4077 static void
   4078 clock_combine(
   4079 	peer_select *	peers,	/* survivor list */
   4080 	int		npeers,	/* number of survivors */
   4081 	int		syspeer	/* index of sys.peer */
   4082 	)
   4083 {
   4084 	int	i;
   4085 	double	x, y, z, w;
   4086 
   4087 	y = z = w = 0;
   4088 	for (i = 0; i < npeers; i++) {
   4089 		x = 1. / peers[i].synch;
   4090 		y += x;
   4091 		z += x * peers[i].peer->offset;
   4092 		w += x * DIFF(peers[i].peer->offset,
   4093 		    peers[syspeer].peer->offset);
   4094 	}
   4095 	sys_offset = z / y;
   4096 	sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
   4097 }
   4098 
   4099 
   4100 /*
   4101  * root_distance - compute synchronization distance from peer to root
   4102  */
   4103 static double
   4104 root_distance(
   4105 	struct peer *peer	/* peer structure pointer */
   4106 	)
   4107 {
   4108 	double	dtemp;
   4109 
   4110 	/*
   4111 	 * Root Distance (LAMBDA) is defined as:
   4112 	 * (delta + DELTA)/2 + epsilon + EPSILON + D
   4113 	 *
   4114 	 * where:
   4115 	 *  delta   is the round-trip delay
   4116 	 *  DELTA   is the root delay
   4117 	 *  epsilon is the peer dispersion
   4118 	 *	    + (15 usec each second)
   4119 	 *  EPSILON is the root dispersion
   4120 	 *  D       is sys_jitter
   4121 	 *
   4122 	 * NB: Think hard about why we are using these values, and what
   4123 	 * the alternatives are, and the various pros/cons.
   4124 	 *
   4125 	 * DLM thinks these are probably the best choices from any of the
   4126 	 * other worse choices.
   4127 	 */
   4128 	dtemp = (peer->delay + peer->rootdelay) / 2
   4129 		+ peer->disp
   4130 		  + clock_phi * (current_time - peer->update)
   4131 		+ peer->rootdisp
   4132 		+ peer->jitter;
   4133 	/*
   4134 	 * Careful squeak here. The value returned must be greater than
   4135 	 * the minimum root dispersion in order to avoid clockhop with
   4136 	 * highly precise reference clocks. Note that the root distance
   4137 	 * cannot exceed the sys_maxdist, as this is the cutoff by the
   4138 	 * selection algorithm.
   4139 	 */
   4140 	if (dtemp < sys_mindisp)
   4141 		dtemp = sys_mindisp;
   4142 	return (dtemp);
   4143 }
   4144 
   4145 
   4146 /*
   4147  * peer_xmit - send packet for persistent association.
   4148  */
   4149 static void
   4150 peer_xmit(
   4151 	struct peer *peer	/* peer structure pointer */
   4152 	)
   4153 {
   4154 	struct pkt xpkt;	/* transmit packet */
   4155 	size_t	sendlen, authlen;
   4156 	keyid_t	xkeyid = 0;	/* transmit key ID */
   4157 	l_fp	xmt_tx, xmt_ty;
   4158 
   4159 	if (!peer->dstadr) {	/* can't send */
   4160 		return;
   4161 	}
   4162 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
   4163 	    peer->hmode);
   4164 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
   4165 	xpkt.ppoll = peer->hpoll;
   4166 	xpkt.precision = sys_precision;
   4167 	xpkt.refid = sys_refid;
   4168 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
   4169 	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
   4170 	/* Use sys_reftime for peer exchanges */
   4171 	HTONL_FP(&sys_reftime, &xpkt.reftime);
   4172 	HTONL_FP(&peer->rec, &xpkt.org);
   4173 	HTONL_FP(&peer->dst, &xpkt.rec);
   4174 
   4175 	/*
   4176 	 * If the received packet contains a MAC, the transmitted packet
   4177 	 * is authenticated and contains a MAC. If not, the transmitted
   4178 	 * packet is not authenticated.
   4179 	 *
   4180 	 * It is most important when autokey is in use that the local
   4181 	 * interface IP address be known before the first packet is
   4182 	 * sent. Otherwise, it is not possible to compute a correct MAC
   4183 	 * the recipient will accept. Thus, the I/O semantics have to do
   4184 	 * a little more work. In particular, the wildcard interface
   4185 	 * might not be usable.
   4186 	 */
   4187 	sendlen = LEN_PKT_NOMAC;
   4188 	if (
   4189 #ifdef AUTOKEY
   4190 	    !(peer->flags & FLAG_SKEY) &&
   4191 #endif	/* !AUTOKEY */
   4192 	    peer->keyid == 0) {
   4193 
   4194 		/*
   4195 		 * Transmit a-priori timestamps
   4196 		 */
   4197 		get_systime(&xmt_tx);
   4198 		if (peer->flip == 0) {	/* basic mode */
   4199 			peer->aorg = xmt_tx;
   4200 			HTONL_FP(&xmt_tx, &xpkt.xmt);
   4201 		} else {		/* interleaved modes */
   4202 			if (peer->hmode == MODE_BROADCAST) { /* bcst */
   4203 				HTONL_FP(&xmt_tx, &xpkt.xmt);
   4204 				if (peer->flip > 0)
   4205 					HTONL_FP(&peer->borg,
   4206 					    &xpkt.org);
   4207 				else
   4208 					HTONL_FP(&peer->aorg,
   4209 					    &xpkt.org);
   4210 			} else {	/* symmetric */
   4211 				if (peer->flip > 0)
   4212 					HTONL_FP(&peer->borg,
   4213 					    &xpkt.xmt);
   4214 				else
   4215 					HTONL_FP(&peer->aorg,
   4216 					    &xpkt.xmt);
   4217 			}
   4218 		}
   4219 		peer->t21_bytes = sendlen;
   4220 		sendpkt(&peer->srcadr, peer->dstadr,
   4221 			sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
   4222 			&xpkt, sendlen);
   4223 		peer->sent++;
   4224 		peer->throttle += (1 << peer->minpoll) - 2;
   4225 
   4226 		/*
   4227 		 * Capture a-posteriori timestamps
   4228 		 */
   4229 		get_systime(&xmt_ty);
   4230 		if (peer->flip != 0) {		/* interleaved modes */
   4231 			if (peer->flip > 0)
   4232 				peer->aorg = xmt_ty;
   4233 			else
   4234 				peer->borg = xmt_ty;
   4235 			peer->flip = -peer->flip;
   4236 		}
   4237 		L_SUB(&xmt_ty, &xmt_tx);
   4238 		LFPTOD(&xmt_ty, peer->xleave);
   4239 		DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt 0x%x.%08x\n",
   4240 			    current_time, latoa(peer->dstadr),
   4241 			    stoa(&peer->srcadr), peer->hmode, sendlen,
   4242 			    xmt_tx.l_ui, xmt_tx.l_uf));
   4243 		return;
   4244 	}
   4245 
   4246 	/*
   4247 	 * Authentication is enabled, so the transmitted packet must be
   4248 	 * authenticated. If autokey is enabled, fuss with the various
   4249 	 * modes; otherwise, symmetric key cryptography is used.
   4250 	 */
   4251 #ifdef AUTOKEY
   4252 	if (peer->flags & FLAG_SKEY) {
   4253 		struct exten *exten;	/* extension field */
   4254 
   4255 		/*
   4256 		 * The Public Key Dance (PKD): Cryptographic credentials
   4257 		 * are contained in extension fields, each including a
   4258 		 * 4-octet length/code word followed by a 4-octet
   4259 		 * association ID and optional additional data. Optional
   4260 		 * data includes a 4-octet data length field followed by
   4261 		 * the data itself. Request messages are sent from a
   4262 		 * configured association; response messages can be sent
   4263 		 * from a configured association or can take the fast
   4264 		 * path without ever matching an association. Response
   4265 		 * messages have the same code as the request, but have
   4266 		 * a response bit and possibly an error bit set. In this
   4267 		 * implementation, a message may contain no more than
   4268 		 * one command and one or more responses.
   4269 		 *
   4270 		 * Cryptographic session keys include both a public and
   4271 		 * a private componet. Request and response messages
   4272 		 * using extension fields are always sent with the
   4273 		 * private component set to zero. Packets without
   4274 		 * extension fields indlude the private component when
   4275 		 * the session key is generated.
   4276 		 */
   4277 		while (1) {
   4278 
   4279 			/*
   4280 			 * Allocate and initialize a keylist if not
   4281 			 * already done. Then, use the list in inverse
   4282 			 * order, discarding keys once used. Keep the
   4283 			 * latest key around until the next one, so
   4284 			 * clients can use client/server packets to
   4285 			 * compute propagation delay.
   4286 			 *
   4287 			 * Note that once a key is used from the list,
   4288 			 * it is retained in the key cache until the
   4289 			 * next key is used. This is to allow a client
   4290 			 * to retrieve the encrypted session key
   4291 			 * identifier to verify authenticity.
   4292 			 *
   4293 			 * If for some reason a key is no longer in the
   4294 			 * key cache, a birthday has happened or the key
   4295 			 * has expired, so the pseudo-random sequence is
   4296 			 * broken. In that case, purge the keylist and
   4297 			 * regenerate it.
   4298 			 */
   4299 			if (peer->keynumber == 0)
   4300 				make_keylist(peer, peer->dstadr);
   4301 			else
   4302 				peer->keynumber--;
   4303 			xkeyid = peer->keylist[peer->keynumber];
   4304 			if (authistrusted(xkeyid))
   4305 				break;
   4306 			else
   4307 				key_expire(peer);
   4308 		}
   4309 		peer->keyid = xkeyid;
   4310 		exten = NULL;
   4311 		switch (peer->hmode) {
   4312 
   4313 		/*
   4314 		 * In broadcast server mode the autokey values are
   4315 		 * required by the broadcast clients. Push them when a
   4316 		 * new keylist is generated; otherwise, push the
   4317 		 * association message so the client can request them at
   4318 		 * other times.
   4319 		 */
   4320 		case MODE_BROADCAST:
   4321 			if (peer->flags & FLAG_ASSOC)
   4322 				exten = crypto_args(peer, CRYPTO_AUTO |
   4323 				    CRYPTO_RESP, peer->associd, NULL);
   4324 			else
   4325 				exten = crypto_args(peer, CRYPTO_ASSOC |
   4326 				    CRYPTO_RESP, peer->associd, NULL);
   4327 			break;
   4328 
   4329 		/*
   4330 		 * In symmetric modes the parameter, certificate,
   4331 		 * identity, cookie and autokey exchanges are
   4332 		 * required. The leapsecond exchange is optional. But, a
   4333 		 * peer will not believe the other peer until the other
   4334 		 * peer has synchronized, so the certificate exchange
   4335 		 * might loop until then. If a peer finds a broken
   4336 		 * autokey sequence, it uses the autokey exchange to
   4337 		 * retrieve the autokey values. In any case, if a new
   4338 		 * keylist is generated, the autokey values are pushed.
   4339 		 */
   4340 		case MODE_ACTIVE:
   4341 		case MODE_PASSIVE:
   4342 
   4343 			/*
   4344 			 * Parameter, certificate and identity.
   4345 			 */
   4346 			if (!peer->crypto)
   4347 				exten = crypto_args(peer, CRYPTO_ASSOC,
   4348 				    peer->associd, hostval.ptr);
   4349 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
   4350 				exten = crypto_args(peer, CRYPTO_CERT,
   4351 				    peer->associd, peer->issuer);
   4352 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
   4353 				exten = crypto_args(peer,
   4354 				    crypto_ident(peer), peer->associd,
   4355 				    NULL);
   4356 
   4357 			/*
   4358 			 * Cookie and autokey. We request the cookie
   4359 			 * only when the this peer and the other peer
   4360 			 * are synchronized. But, this peer needs the
   4361 			 * autokey values when the cookie is zero. Any
   4362 			 * time we regenerate the key list, we offer the
   4363 			 * autokey values without being asked. If for
   4364 			 * some reason either peer finds a broken
   4365 			 * autokey sequence, the autokey exchange is
   4366 			 * used to retrieve the autokey values.
   4367 			 */
   4368 			else if (   sys_leap != LEAP_NOTINSYNC
   4369 				 && peer->leap != LEAP_NOTINSYNC
   4370 				 && !(peer->crypto & CRYPTO_FLAG_COOK))
   4371 				exten = crypto_args(peer, CRYPTO_COOK,
   4372 				    peer->associd, NULL);
   4373 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
   4374 				exten = crypto_args(peer, CRYPTO_AUTO,
   4375 				    peer->associd, NULL);
   4376 			else if (   peer->flags & FLAG_ASSOC
   4377 				 && peer->crypto & CRYPTO_FLAG_SIGN)
   4378 				exten = crypto_args(peer, CRYPTO_AUTO |
   4379 				    CRYPTO_RESP, peer->assoc, NULL);
   4380 
   4381 			/*
   4382 			 * Wait for clock sync, then sign the
   4383 			 * certificate and retrieve the leapsecond
   4384 			 * values.
   4385 			 */
   4386 			else if (sys_leap == LEAP_NOTINSYNC)
   4387 				break;
   4388 
   4389 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
   4390 				exten = crypto_args(peer, CRYPTO_SIGN,
   4391 				    peer->associd, hostval.ptr);
   4392 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
   4393 				exten = crypto_args(peer, CRYPTO_LEAP,
   4394 				    peer->associd, NULL);
   4395 			break;
   4396 
   4397 		/*
   4398 		 * In client mode the parameter, certificate, identity,
   4399 		 * cookie and sign exchanges are required. The
   4400 		 * leapsecond exchange is optional. If broadcast client
   4401 		 * mode the same exchanges are required, except that the
   4402 		 * autokey exchange is substitutes for the cookie
   4403 		 * exchange, since the cookie is always zero. If the
   4404 		 * broadcast client finds a broken autokey sequence, it
   4405 		 * uses the autokey exchange to retrieve the autokey
   4406 		 * values.
   4407 		 */
   4408 		case MODE_CLIENT:
   4409 
   4410 			/*
   4411 			 * Parameter, certificate and identity.
   4412 			 */
   4413 			if (!peer->crypto)
   4414 				exten = crypto_args(peer, CRYPTO_ASSOC,
   4415 				    peer->associd, hostval.ptr);
   4416 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
   4417 				exten = crypto_args(peer, CRYPTO_CERT,
   4418 				    peer->associd, peer->issuer);
   4419 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
   4420 				exten = crypto_args(peer,
   4421 				    crypto_ident(peer), peer->associd,
   4422 				    NULL);
   4423 
   4424 			/*
   4425 			 * Cookie and autokey. These are requests, but
   4426 			 * we use the peer association ID with autokey
   4427 			 * rather than our own.
   4428 			 */
   4429 			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
   4430 				exten = crypto_args(peer, CRYPTO_COOK,
   4431 				    peer->associd, NULL);
   4432 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
   4433 				exten = crypto_args(peer, CRYPTO_AUTO,
   4434 				    peer->assoc, NULL);
   4435 
   4436 			/*
   4437 			 * Wait for clock sync, then sign the
   4438 			 * certificate and retrieve the leapsecond
   4439 			 * values.
   4440 			 */
   4441 			else if (sys_leap == LEAP_NOTINSYNC)
   4442 				break;
   4443 
   4444 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
   4445 				exten = crypto_args(peer, CRYPTO_SIGN,
   4446 				    peer->associd, hostval.ptr);
   4447 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
   4448 				exten = crypto_args(peer, CRYPTO_LEAP,
   4449 				    peer->associd, NULL);
   4450 			break;
   4451 		}
   4452 
   4453 		/*
   4454 		 * Add a queued extension field if present. This is
   4455 		 * always a request message, so the reply ID is already
   4456 		 * in the message. If an error occurs, the error bit is
   4457 		 * lit in the response.
   4458 		 */
   4459 		if (peer->cmmd != NULL) {
   4460 			u_int32 temp32;
   4461 
   4462 			temp32 = CRYPTO_RESP;
   4463 			peer->cmmd->opcode |= htonl(temp32);
   4464 			sendlen += crypto_xmit(peer, &xpkt, NULL,
   4465 			    sendlen, peer->cmmd, 0);
   4466 			free(peer->cmmd);
   4467 			peer->cmmd = NULL;
   4468 		}
   4469 
   4470 		/*
   4471 		 * Add an extension field created above. All but the
   4472 		 * autokey response message are request messages.
   4473 		 */
   4474 		if (exten != NULL) {
   4475 			if (exten->opcode != 0)
   4476 				sendlen += crypto_xmit(peer, &xpkt,
   4477 				    NULL, sendlen, exten, 0);
   4478 			free(exten);
   4479 		}
   4480 
   4481 		/*
   4482 		 * Calculate the next session key. Since extension
   4483 		 * fields are present, the cookie value is zero.
   4484 		 */
   4485 		if (sendlen > (int)LEN_PKT_NOMAC) {
   4486 			session_key(&peer->dstadr->sin, &peer->srcadr,
   4487 			    xkeyid, 0, 2);
   4488 		}
   4489 	}
   4490 #endif	/* AUTOKEY */
   4491 
   4492 	/*
   4493 	 * Transmit a-priori timestamps
   4494 	 */
   4495 	get_systime(&xmt_tx);
   4496 	if (peer->flip == 0) {		/* basic mode */
   4497 		peer->aorg = xmt_tx;
   4498 		HTONL_FP(&xmt_tx, &xpkt.xmt);
   4499 	} else {			/* interleaved modes */
   4500 		if (peer->hmode == MODE_BROADCAST) { /* bcst */
   4501 			HTONL_FP(&xmt_tx, &xpkt.xmt);
   4502 			if (peer->flip > 0)
   4503 				HTONL_FP(&peer->borg, &xpkt.org);
   4504 			else
   4505 				HTONL_FP(&peer->aorg, &xpkt.org);
   4506 		} else {		/* symmetric */
   4507 			if (peer->flip > 0)
   4508 				HTONL_FP(&peer->borg, &xpkt.xmt);
   4509 			else
   4510 				HTONL_FP(&peer->aorg, &xpkt.xmt);
   4511 		}
   4512 	}
   4513 	xkeyid = peer->keyid;
   4514 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
   4515 	if (authlen == 0) {
   4516 		report_event(PEVNT_AUTH, peer, "no key");
   4517 		peer->flash |= TEST5;		/* auth error */
   4518 		peer->badauth++;
   4519 		return;
   4520 	}
   4521 	sendlen += authlen;
   4522 #ifdef AUTOKEY
   4523 	if (xkeyid > NTP_MAXKEY)
   4524 		authtrust(xkeyid, 0);
   4525 #endif	/* AUTOKEY */
   4526 	if (sendlen > sizeof(xpkt)) {
   4527 		msyslog(LOG_ERR, "peer_xmit: buffer overflow %u", (u_int)sendlen);
   4528 		exit(EX_SOFTWARE);
   4529 	}
   4530 	peer->t21_bytes = sendlen;
   4531 	sendpkt(&peer->srcadr, peer->dstadr,
   4532 		sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
   4533 		&xpkt, sendlen);
   4534 	peer->sent++;
   4535 	peer->throttle += (1 << peer->minpoll) - 2;
   4536 
   4537 	/*
   4538 	 * Capture a-posteriori timestamps
   4539 	 */
   4540 	get_systime(&xmt_ty);
   4541 	if (peer->flip != 0) {			/* interleaved modes */
   4542 		if (peer->flip > 0)
   4543 			peer->aorg = xmt_ty;
   4544 		else
   4545 			peer->borg = xmt_ty;
   4546 		peer->flip = -peer->flip;
   4547 	}
   4548 	L_SUB(&xmt_ty, &xmt_tx);
   4549 	LFPTOD(&xmt_ty, peer->xleave);
   4550 #ifdef AUTOKEY
   4551 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
   4552 		    current_time, latoa(peer->dstadr), stoa(&peer->srcadr),
   4553 		    peer->hmode, xkeyid, sendlen, peer->keynumber));
   4554 #else	/* !AUTOKEY follows */
   4555 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu\n",
   4556 		    current_time, peer->dstadr ?
   4557 		    ntoa(&peer->dstadr->sin) : "-",
   4558 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
   4559 #endif	/* !AUTOKEY */
   4560 
   4561 	return;
   4562 }
   4563 
   4564 
   4565 #ifdef LEAP_SMEAR
   4566 
   4567 static void
   4568 leap_smear_add_offs(
   4569 	l_fp *t,
   4570 	l_fp *t_recv
   4571 	)
   4572 {
   4573 
   4574 	L_ADD(t, &leap_smear.offset);
   4575 
   4576 	/*
   4577 	** XXX: Should the smear be added to the root dispersion?
   4578 	*/
   4579 
   4580 	return;
   4581 }
   4582 
   4583 #endif /* LEAP_SMEAR */
   4584 
   4585 
   4586 /*
   4587  * fast_xmit - Send packet for nonpersistent association. Note that
   4588  * neither the source or destination can be a broadcast address.
   4589  */
   4590 static void
   4591 fast_xmit(
   4592 	struct recvbuf* rbufp,	/* receive packet pointer */
   4593 	int	xmode,		/* receive mode */  /* XXX: HMS: really? */
   4594 	keyid_t	xkeyid,		/* transmit key ID */
   4595 	int	flags		/* restrict mask */
   4596 )
   4597 {
   4598 	struct pkt xpkt;	/* transmit packet structure */
   4599 	struct pkt* rpkt;	/* receive packet structure */
   4600 	l_fp	xmt_tx, xmt_ty;
   4601 	size_t	sendlen;
   4602 #ifdef AUTOKEY
   4603 	u_int32	temp32;
   4604 #endif
   4605 
   4606 	/*
   4607 	 * Initialize transmit packet header fields from the receive
   4608 	 * buffer provided. We leave the fields intact as received, but
   4609 	 * set the peer poll at the maximum of the receive peer poll and
   4610 	 * the system minimum poll (ntp_minpoll). This is for KoD rate
   4611 	 * control and not strictly specification compliant, but doesn't
   4612 	 * break anything.
   4613 	 */
   4614 	rpkt = &rbufp->recv_pkt;
   4615 	/*
   4616 	 * If the packet was received on an endpoint open only on
   4617 	 * a multicast address, the response needs to go out from
   4618 	 * a unicast endpoint.
   4619 	 */
   4620 #ifndef MULTICAST_NONEWSOCKET
   4621 	if (rbufp->dstadr->flags & INT_MCASTOPEN) {
   4622 		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
   4623 		if (NULL == rbufp->dstadr ||
   4624 		    ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr) /* wildcard */
   4625 		      == rbufp->dstadr) {
   4626 			DPRINTF(2, ("No unicast local address found for"
   4627 				    " reply to %s mcast.",
   4628 				    stoa(&rbufp->recv_srcadr)));
   4629 			return;
   4630 		}
   4631 	}
   4632 #endif
   4633 
   4634 	/*
   4635 	 * If this is a kiss-o'-death (KoD) packet, show leap
   4636 	 * unsynchronized, stratum zero, reference ID the four-character
   4637 	 * kiss code and (???) system root delay. Note we don't reveal
   4638 	 * the local time, so these packets can't be used for
   4639 	 * synchronization.
   4640 	 */
   4641 	if (flags & RES_KOD) {
   4642 		sys_kodsent++;
   4643 		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
   4644 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
   4645 		xpkt.stratum = STRATUM_PKT_UNSPEC;
   4646 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
   4647 		xpkt.precision = rpkt->precision;
   4648 		memcpy(&xpkt.refid, "RATE", 4);
   4649 		xpkt.rootdelay = rpkt->rootdelay;
   4650 		xpkt.rootdisp = rpkt->rootdisp;
   4651 		xpkt.reftime = rpkt->reftime;
   4652 		xpkt.org = rpkt->xmt;
   4653 		xpkt.rec = rpkt->xmt;
   4654 		xpkt.xmt = rpkt->xmt;
   4655 
   4656 	/*
   4657 	 * This is a normal packet. Use the system variables.
   4658 	 */
   4659 	} else {
   4660 		double this_rootdisp;
   4661 		l_fp this_ref_time;
   4662 
   4663 #ifdef LEAP_SMEAR
   4664 		/*
   4665 		 * Make copies of the variables which can be affected by smearing.
   4666 		 */
   4667 		l_fp this_recv_time;
   4668 #endif
   4669 
   4670 		/*
   4671 		 * If we are inside the leap smear interval we add
   4672 		 * the current smear offset to:
   4673 		 * - the packet receive time,
   4674 		 * - the packet transmit time,
   4675 		 * - and eventually to the reftime to make sure the
   4676 		 *   reftime isn't later than the transmit/receive times.
   4677 		 */
   4678 		xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
   4679 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
   4680 
   4681 		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
   4682 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
   4683 		xpkt.precision = sys_precision;
   4684 		xpkt.refid = sys_refid;
   4685 		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
   4686 
   4687 		/*
   4688 		** Server Response Fuzzing
   4689 		**
   4690 		** Which values do we want to use for reftime and rootdisp?
   4691 		*/
   4692 
   4693 		if (   MODE_SERVER == xmode
   4694 		    && RES_SRVRSPFUZ & flags) {
   4695 			if (current_time < p2_time) {
   4696 				this_ref_time = p2_reftime;
   4697 				this_rootdisp = p2_rootdisp;
   4698 			} else if (current_time < prev_time) {
   4699 				this_ref_time = prev_reftime;
   4700 				this_rootdisp = prev_rootdisp;
   4701 			} else {
   4702 				this_ref_time = sys_reftime;
   4703 				this_rootdisp = sys_rootdisp;
   4704 			}
   4705 
   4706 			SRVRSP_FUZZ(this_ref_time);
   4707 		} else {
   4708 			this_ref_time = sys_reftime;
   4709 			this_rootdisp = sys_rootdisp;
   4710 		}
   4711 
   4712 		/*
   4713 		** ROOT DISPERSION
   4714 		*/
   4715 
   4716 		xpkt.rootdisp = HTONS_FP(DTOUFP(this_rootdisp));
   4717 
   4718 		/*
   4719 		** REFTIME
   4720 		*/
   4721 
   4722 #ifdef LEAP_SMEAR
   4723 		if (leap_smear.in_progress) {
   4724 			/* adjust the reftime by the same amount as the
   4725 			 * leap smear, as we don't want to risk the
   4726 			 * reftime being later than the transmit time.
   4727 			 */
   4728 			leap_smear_add_offs(&this_ref_time, NULL);
   4729 		}
   4730 #endif
   4731 
   4732 		HTONL_FP(&this_ref_time, &xpkt.reftime);
   4733 
   4734 		/*
   4735 		** REFID
   4736 		*/
   4737 
   4738 #ifdef LEAP_SMEAR
   4739 		if (leap_smear.in_progress) {
   4740 			xpkt.refid = convertLFPToRefID(leap_smear.offset);
   4741 			DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
   4742 				ntohl(xpkt.refid),
   4743 				lfptoa(&leap_smear.offset, 8)
   4744 				));
   4745 		}
   4746 #endif
   4747 
   4748 		/*
   4749 		** ORIGIN
   4750 		*/
   4751 
   4752 		xpkt.org = rpkt->xmt;
   4753 
   4754 		/*
   4755 		** RECEIVE
   4756 		*/
   4757 #ifdef LEAP_SMEAR
   4758 		this_recv_time = rbufp->recv_time;
   4759 		if (leap_smear.in_progress)
   4760 			leap_smear_add_offs(&this_recv_time, NULL);
   4761 		HTONL_FP(&this_recv_time, &xpkt.rec);
   4762 #else
   4763 		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
   4764 #endif
   4765 
   4766 		/*
   4767 		** TRANSMIT
   4768 		*/
   4769 
   4770 		get_systime(&xmt_tx);
   4771 #ifdef LEAP_SMEAR
   4772 		if (leap_smear.in_progress)
   4773 			leap_smear_add_offs(&xmt_tx, &this_recv_time);
   4774 #endif
   4775 		HTONL_FP(&xmt_tx, &xpkt.xmt);
   4776 	}
   4777 
   4778 #ifdef HAVE_NTP_SIGND
   4779 	if (flags & RES_MSSNTP) {
   4780 		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
   4781 		return;
   4782 	}
   4783 #endif /* HAVE_NTP_SIGND */
   4784 
   4785 	/*
   4786 	 * If the received packet contains a MAC, the transmitted packet
   4787 	 * is authenticated and contains a MAC. If not, the transmitted
   4788 	 * packet is not authenticated.
   4789 	 */
   4790 	sendlen = LEN_PKT_NOMAC;
   4791 	if ((size_t)rbufp->recv_length == sendlen) {
   4792 		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
   4793 		    sendlen);
   4794 		DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
   4795 			    current_time, stoa(&rbufp->dstadr->sin),
   4796 			    stoa(&rbufp->recv_srcadr), xmode,
   4797 			    (u_long)sendlen));
   4798 		return;
   4799 	}
   4800 
   4801 	/*
   4802 	 * The received packet contains a MAC, so the transmitted packet
   4803 	 * must be authenticated. For symmetric key cryptography, use
   4804 	 * the predefined and trusted symmetric keys to generate the
   4805 	 * cryptosum. For autokey cryptography, use the server private
   4806 	 * value to generate the cookie, which is unique for every
   4807 	 * source-destination-key ID combination.
   4808 	 */
   4809 #ifdef AUTOKEY
   4810 	if (xkeyid > NTP_MAXKEY) {
   4811 		keyid_t cookie;
   4812 
   4813 		/*
   4814 		 * The only way to get here is a reply to a legitimate
   4815 		 * client request message, so the mode must be
   4816 		 * MODE_SERVER. If an extension field is present, there
   4817 		 * can be only one and that must be a command. Do what
   4818 		 * needs, but with private value of zero so the poor
   4819 		 * jerk can decode it. If no extension field is present,
   4820 		 * use the cookie to generate the session key.
   4821 		 */
   4822 		cookie = session_key(&rbufp->recv_srcadr,
   4823 		    &rbufp->dstadr->sin, 0, sys_private, 0);
   4824 		if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
   4825 			session_key(&rbufp->dstadr->sin,
   4826 			    &rbufp->recv_srcadr, xkeyid, 0, 2);
   4827 			temp32 = CRYPTO_RESP;
   4828 			rpkt->exten[0] |= htonl(temp32);
   4829 			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
   4830 			    sendlen, (struct exten *)rpkt->exten,
   4831 			    cookie);
   4832 		} else {
   4833 			session_key(&rbufp->dstadr->sin,
   4834 			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
   4835 		}
   4836 	}
   4837 #endif	/* AUTOKEY */
   4838 	get_systime(&xmt_tx);
   4839 	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
   4840 #ifdef AUTOKEY
   4841 	if (xkeyid > NTP_MAXKEY)
   4842 		authtrust(xkeyid, 0);
   4843 #endif	/* AUTOKEY */
   4844 	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
   4845 	get_systime(&xmt_ty);
   4846 	L_SUB(&xmt_ty, &xmt_tx);
   4847 	sys_authdelay = xmt_ty;
   4848 	DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
   4849 		    current_time, ntoa(&rbufp->dstadr->sin),
   4850 		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
   4851 		    (u_long)sendlen));
   4852 }
   4853 
   4854 
   4855 /*
   4856  * pool_xmit - resolve hostname or send unicast solicitation for pool.
   4857  */
   4858 static void
   4859 pool_xmit(
   4860 	struct peer *pool	/* pool solicitor association */
   4861 	)
   4862 {
   4863 #ifdef WORKER
   4864 	struct pkt	xpkt;	/* transmit packet structure */
   4865 	struct addrinfo	hints;
   4866 	int		rc;
   4867 	endpt *		lcladr;
   4868 	sockaddr_u *	rmtadr;
   4869 	u_short		af;
   4870 	struct peer *	p;
   4871 	l_fp		xmt_tx;
   4872 
   4873 	DEBUG_REQUIRE(pool);
   4874 	if (NULL == pool->ai) {
   4875 		if (pool->addrs != NULL) {
   4876 			/* free() is used with copy_addrinfo_list() */
   4877 			free(pool->addrs);
   4878 			pool->addrs = NULL;
   4879 		}
   4880 		af = AF(&pool->srcadr);
   4881 		if (   (AF_INET == af && !nonlocal_v4_addr_up)
   4882 		    || (AF_INET6 == af && !nonlocal_v6_addr_up)
   4883 		    || (   AF_UNSPEC == af
   4884 			&& !nonlocal_v4_addr_up
   4885 			&& !nonlocal_v6_addr_up)) {
   4886 
   4887 			/* POOL DNS query would be useless [Bug 3845] */
   4888 			return;
   4889 		}
   4890 		ZERO(hints);
   4891 		hints.ai_family = AF(&pool->srcadr);
   4892 		hints.ai_socktype = SOCK_DGRAM;
   4893 		hints.ai_protocol = IPPROTO_UDP;
   4894 		/* ignore getaddrinfo_sometime() errors, we will retry */
   4895 		rc = getaddrinfo_sometime(
   4896 			pool->hostname,
   4897 			"ntp",
   4898 			&hints,
   4899 			0,			/* no retry */
   4900 			&pool_name_resolved,
   4901 			(void *)(intptr_t)pool->associd);
   4902 		if (!rc)
   4903 			DPRINTF(1, ("pool DNS lookup %s started\n",
   4904 				pool->hostname));
   4905 		else
   4906 			msyslog(LOG_ERR,
   4907 				"unable to start pool DNS %s: %m",
   4908 				pool->hostname);
   4909 		return;
   4910 	}
   4911 
   4912 	do {
   4913 		/* copy_addrinfo_list ai_addr points to a sockaddr_u */
   4914 		rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
   4915 		pool->ai = pool->ai->ai_next;
   4916 		/* do not solicit when hopeless [Bug 3845] */
   4917 		if (   (IS_IPV4(rmtadr) && !nonlocal_v4_addr_up)
   4918 		    || (IS_IPV6(rmtadr) && !nonlocal_v6_addr_up)) {
   4919 			continue;
   4920 		}
   4921 		p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0, NULL);
   4922 	} while (p != NULL && pool->ai != NULL);
   4923 	if (p != NULL) {
   4924 		return;	/* out of addresses, re-query DNS next poll */
   4925 	}
   4926 	restrict_source(rmtadr, FALSE, 1 + POOL_SOLICIT_WINDOW);
   4927 	lcladr = findinterface(rmtadr);
   4928 	memset(&xpkt, 0, sizeof(xpkt));
   4929 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
   4930 					 MODE_CLIENT);
   4931 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
   4932 	xpkt.ppoll = pool->hpoll;
   4933 	xpkt.precision = sys_precision;
   4934 	xpkt.refid = sys_refid;
   4935 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
   4936 	xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
   4937 	/* Bug 3596: What are the pros/cons of using sys_reftime here? */
   4938 	HTONL_FP(&sys_reftime, &xpkt.reftime);
   4939 
   4940 	get_systime(&xmt_tx);
   4941 	pool->aorg = xmt_tx;
   4942 
   4943 	if (FLAG_LOOPNONCE & pool->flags) {
   4944 		l_fp nonce;
   4945 
   4946 		do {
   4947 			nonce.l_ui = ntp_random();
   4948 		} while (0 == nonce.l_ui);
   4949 		do {
   4950 			nonce.l_uf = ntp_random();
   4951 		} while (0 == nonce.l_uf);
   4952 		pool->nonce = nonce;
   4953 		HTONL_FP(&nonce, &xpkt.xmt);
   4954 	} else {
   4955 		L_CLR(&pool->nonce);
   4956 		HTONL_FP(&xmt_tx, &xpkt.xmt);
   4957 	}
   4958 	pool->sent++;
   4959 	pool->throttle += (1 << pool->minpoll) - 2;
   4960 	DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
   4961 		    current_time, latoa(lcladr), stoa(rmtadr)));
   4962 	msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
   4963 	sendpkt(rmtadr, lcladr,
   4964 		sys_ttl[(pool->ttl >= sys_ttlmax) ? sys_ttlmax : pool->ttl],
   4965 		&xpkt, LEN_PKT_NOMAC);
   4966 #endif	/* WORKER */
   4967 }
   4968 
   4969 
   4970 #ifdef AUTOKEY
   4971 	/*
   4972 	 * group_test - test if this is the same group
   4973 	 *
   4974 	 * host		assoc		return		action
   4975 	 * none		none		0		mobilize *
   4976 	 * none		group		0		mobilize *
   4977 	 * group	none		0		mobilize *
   4978 	 * group	group		1		mobilize
   4979 	 * group	different	1		ignore
   4980 	 * * ignore if notrust
   4981 	 */
   4982 int
   4983 group_test(
   4984 	char	*grp,
   4985 	char	*ident
   4986 	)
   4987 {
   4988 	if (grp == NULL)
   4989 		return (0);
   4990 
   4991 	if (strcmp(grp, sys_groupname) == 0)
   4992 		return (0);
   4993 
   4994 	if (ident == NULL)
   4995 		return (1);
   4996 
   4997 	if (strcmp(grp, ident) == 0)
   4998 		return (0);
   4999 
   5000 	return (1);
   5001 }
   5002 #endif /* AUTOKEY */
   5003 
   5004 
   5005 #ifdef WORKER
   5006 void
   5007 pool_name_resolved(
   5008 	int			rescode,
   5009 	int			gai_errno,
   5010 	void *			context,
   5011 	const char *		name,
   5012 	const char *		service,
   5013 	const struct addrinfo *	hints,
   5014 	const struct addrinfo *	res
   5015 	)
   5016 {
   5017 	struct peer *	pool;	/* pool solicitor association */
   5018 	associd_t	assoc;
   5019 
   5020 	if (rescode) {
   5021 		msyslog(LOG_ERR,
   5022 			"error resolving pool %s: %s (%d)",
   5023 			name, gai_strerror(rescode), rescode);
   5024 		return;
   5025 	}
   5026 
   5027 	assoc = (associd_t)(intptr_t)context;
   5028 	pool = findpeerbyassoc(assoc);
   5029 	if (NULL == pool) {
   5030 		msyslog(LOG_ERR,
   5031 			"Could not find assoc %u for pool DNS %s",
   5032 			assoc, name);
   5033 		return;
   5034 	}
   5035 	DPRINTF(1, ("pool DNS %s completed\n", name));
   5036 	pool->addrs = copy_addrinfo_list(res);
   5037 	pool->ai = pool->addrs;
   5038 	pool_xmit(pool);
   5039 
   5040 }
   5041 #endif	/* WORKER */
   5042 
   5043 
   5044 #ifdef AUTOKEY
   5045 /*
   5046  * key_expire - purge the key list
   5047  */
   5048 void
   5049 key_expire(
   5050 	struct peer *peer	/* peer structure pointer */
   5051 	)
   5052 {
   5053 	int i;
   5054 
   5055 	if (peer->keylist != NULL) {
   5056 		for (i = 0; i <= peer->keynumber; i++)
   5057 			authtrust(peer->keylist[i], 0);
   5058 		free(peer->keylist);
   5059 		peer->keylist = NULL;
   5060 	}
   5061 	value_free(&peer->sndval);
   5062 	peer->keynumber = 0;
   5063 	peer->flags &= ~FLAG_ASSOC;
   5064 	DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
   5065 		    peer->associd));
   5066 }
   5067 #endif	/* AUTOKEY */
   5068 
   5069 
   5070 /*
   5071  * local_refid(peer) - Check peer refid to avoid selecting peers
   5072  *		       currently synced to this ntpd.
   5073  * Note that until 4.2.8p18 and 4.3.1XX ntpd calculated the IPv6
   5074  * refid differently on different-endian systems.  It now calculates
   5075  * the refid the same on both, the same way it did on little-endian
   5076  * in the past.  On big-endian systems, ntpd also calculates a
   5077  * byte-swapped version of each of its IPv6 local addresses' refids,
   5078  * as endpt.old_refid and also detects a loop when seeing it.  This
   5079  * ensures new BE ntpd will detect loops interoperating with older
   5080  * BE ntpd, and keeps the more-common LE old ntpd code detecting
   5081  * loops with IPv6 refids correctly.  Thanks to Hal Murray for
   5082  * the byte-swapping idea.
   5083  */
   5084 static int
   5085 local_refid(
   5086 	struct peer *	p
   5087 	)
   5088 {
   5089 	endpt *	unicast_ep;
   5090 
   5091 	if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
   5092 		unicast_ep = p->dstadr;
   5093 	else
   5094 		unicast_ep = findinterface(&p->srcadr);
   5095 
   5096 	if (unicast_ep != NULL
   5097 	    && (   p->refid == unicast_ep->addr_refid
   5098 #ifdef WORDS_BIGENDIAN
   5099 		|| (   IS_IPV6(&unicast_ep->sin)
   5100 		    && p->refid == unicast_ep->old_refid)
   5101 #endif
   5102 							 )) {
   5103 		return TRUE;
   5104 	} else {
   5105 		return FALSE;
   5106 	}
   5107 }
   5108 
   5109 
   5110 /*
   5111  * Determine if the peer is unfit for synchronization
   5112  *
   5113  * A peer is unfit for synchronization if
   5114  * > TEST10 bad leap or stratum below floor or at or above ceiling
   5115  * > TEST11 root distance exceeded for remote peer
   5116  * > TEST12 a direct or indirect synchronization loop would form
   5117  * > TEST13 unreachable or noselect
   5118  */
   5119 int				/* FALSE if fit, TRUE if unfit */
   5120 peer_unfit(
   5121 	struct peer *peer	/* peer structure pointer */
   5122 	)
   5123 {
   5124 	int	rval = 0;
   5125 
   5126 	/*
   5127 	 * A stratum error occurs if (1) the server has never been
   5128 	 * synchronized, (2) the server stratum is below the floor or
   5129 	 * greater than or equal to the ceiling.
   5130 	 */
   5131 	if (   peer->leap == LEAP_NOTINSYNC
   5132 	    || peer->stratum < sys_floor
   5133 	    || peer->stratum >= sys_ceiling) {
   5134 		rval |= TEST10;		/* bad synch or stratum */
   5135 	}
   5136 
   5137 	/*
   5138 	 * A distance error for a remote peer occurs if the root
   5139 	 * distance is greater than or equal to the distance threshold
   5140 	 * plus the increment due to one host poll interval.
   5141 	 */
   5142 	if (   !(peer->flags & FLAG_REFCLOCK)
   5143 	    && root_distance(peer) >= sys_maxdist
   5144 				      + clock_phi * ULOGTOD(peer->hpoll)) {
   5145 		rval |= TEST11;		/* distance exceeded */
   5146 	}
   5147 
   5148 	/*
   5149 	 * A loop error occurs if the remote peer is synchronized to the
   5150 	 * local peer or if the remote peer is synchronized to the same
   5151 	 * server as the local peer but only if the remote peer is
   5152 	 * neither a reference clock nor an orphan.
   5153 	 */
   5154 	if (peer->stratum > 1 && local_refid(peer)) {
   5155 		rval |= TEST12;		/* synchronization loop */
   5156 	}
   5157 
   5158 	/*
   5159 	 * An unreachable error occurs if the server is unreachable or
   5160 	 * the noselect bit is set.
   5161 	 */
   5162 	if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
   5163 		rval |= TEST13;		/* unreachable */
   5164 	}
   5165 
   5166 	peer->flash &= ~PEER_TEST_MASK;
   5167 	peer->flash |= rval;
   5168 	return (rval);
   5169 }
   5170 
   5171 
   5172 /*
   5173  * Find the precision of this particular machine
   5174  */
   5175 #define MINSTEP		20e-9	/* minimum clock increment (s) */
   5176 #define MAXSTEP		1	/* maximum clock increment (s) */
   5177 #define MINCHANGES	12	/* minimum number of step samples */
   5178 #define MAXLOOPS	((int)(1. / MINSTEP))	/* avoid infinite loop */
   5179 
   5180 /*
   5181  * This routine measures the system precision defined as the minimum of
   5182  * a sequence of differences between successive readings of the system
   5183  * clock. However, if a difference is less than MINSTEP, the clock has
   5184  * been read more than once during a clock tick and the difference is
   5185  * ignored. We set MINSTEP greater than zero in case something happens
   5186  * like a cache miss, and to tolerate underlying system clocks which
   5187  * ensure each reading is strictly greater than prior readings while
   5188  * using an underlying stepping (not interpolated) clock.
   5189  *
   5190  * sys_tick and sys_precision represent the time to read the clock for
   5191  * systems with high-precision clocks, and the tick interval or step
   5192  * size for lower-precision stepping clocks.
   5193  *
   5194  * This routine also measures the time to read the clock on stepping
   5195  * system clocks by counting the number of readings between changes of
   5196  * the underlying clock.  With either type of clock, the minimum time
   5197  * to read the clock is saved as sys_fuzz, and used to ensure the
   5198  * get_systime() readings always increase and are fuzzed below sys_fuzz.
   5199  */
   5200 void
   5201 measure_precision(void)
   5202 {
   5203 	/*
   5204 	 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
   5205 	 * is effectively disabled.  trunc_os_clock is FALSE to disable
   5206 	 * get_ostime() simulation of a low-precision system clock.
   5207 	 */
   5208 	set_sys_fuzz(0.);
   5209 	trunc_os_clock = FALSE;
   5210 	measured_tick = measure_tick_fuzz();
   5211 	set_sys_tick_precision(measured_tick);
   5212 	msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
   5213 		sys_tick * 1e6, sys_precision);
   5214 	if (sys_fuzz < sys_tick) {
   5215 		msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
   5216 			sys_fuzz * 1e6);
   5217 	}
   5218 }
   5219 
   5220 
   5221 /*
   5222  * measure_tick_fuzz()
   5223  *
   5224  * measures the minimum time to read the clock (stored in sys_fuzz)
   5225  * and returns the tick, the larger of the minimum increment observed
   5226  * between successive clock readings and the time to read the clock.
   5227  */
   5228 double
   5229 measure_tick_fuzz(void)
   5230 {
   5231 	l_fp	minstep;	/* MINSTEP as l_fp */
   5232 	l_fp	val;		/* current seconds fraction */
   5233 	l_fp	last;		/* last seconds fraction */
   5234 	l_fp	ldiff;		/* val - last */
   5235 	double	tick;		/* computed tick value */
   5236 	double	diff;
   5237 	long	repeats;
   5238 	long	max_repeats;
   5239 	int	changes;
   5240 	int	i;		/* log2 precision */
   5241 
   5242 	tick = MAXSTEP;
   5243 	max_repeats = 0;
   5244 	repeats = 0;
   5245 	changes = 0;
   5246 	DTOLFP(MINSTEP, &minstep);
   5247 	get_systime(&last);
   5248 	for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
   5249 		get_systime(&val);
   5250 		ldiff = val;
   5251 		L_SUB(&ldiff, &last);
   5252 		last = val;
   5253 		if (L_ISGT(&ldiff, &minstep)) {
   5254 			max_repeats = max(repeats, max_repeats);
   5255 			repeats = 0;
   5256 			changes++;
   5257 			LFPTOD(&ldiff, diff);
   5258 			tick = min(diff, tick);
   5259 		} else {
   5260 			repeats++;
   5261 		}
   5262 	}
   5263 	if (changes < MINCHANGES) {
   5264 		msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
   5265 		exit(1);
   5266 	}
   5267 
   5268 	if (0 == max_repeats) {
   5269 		set_sys_fuzz(tick);
   5270 	} else {
   5271 		set_sys_fuzz(tick / max_repeats);
   5272 	}
   5273 
   5274 	return tick;
   5275 }
   5276 
   5277 
   5278 void
   5279 set_sys_tick_precision(
   5280 	double tick
   5281 	)
   5282 {
   5283 	int i;
   5284 
   5285 	if (tick > 1.) {
   5286 		msyslog(LOG_ERR,
   5287 			"unsupported tick %.3f > 1s ignored", tick);
   5288 		return;
   5289 	}
   5290 	if (tick < measured_tick) {
   5291 		msyslog(LOG_ERR,
   5292 			"proto: tick %.3f less than measured tick %.3f, ignored",
   5293 			tick, measured_tick);
   5294 		return;
   5295 	} else if (tick > measured_tick) {
   5296 		trunc_os_clock = TRUE;
   5297 		msyslog(LOG_NOTICE,
   5298 			"proto: truncating system clock to multiples of %.9f",
   5299 			tick);
   5300 	}
   5301 	sys_tick = tick;
   5302 
   5303 	/*
   5304 	 * Find the nearest power of two.
   5305 	 */
   5306 	for (i = 0; tick <= 1; i--)
   5307 		tick *= 2;
   5308 	if (tick - 1 > 1 - tick / 2)
   5309 		i++;
   5310 
   5311 	sys_precision = (s_char)i;
   5312 }
   5313 
   5314 
   5315 /*
   5316  * init_proto - initialize the protocol module's data
   5317  */
   5318 void
   5319 init_proto(void)
   5320 {
   5321 	l_fp	dummy;
   5322 	int	i;
   5323 
   5324 	/*
   5325 	 * Fill in the sys_* stuff.  Default is don't listen to
   5326 	 * broadcasting, require authentication.
   5327 	 */
   5328 	set_sys_leap(LEAP_NOTINSYNC);
   5329 	sys_stratum = STRATUM_UNSPEC;
   5330 	memcpy(&sys_refid, "INIT", 4);
   5331 	sys_peer = NULL;
   5332 	sys_rootdelay = 0;
   5333 	sys_rootdisp = 0;
   5334 	L_CLR(&sys_reftime);
   5335 	sys_jitter = 0;
   5336 	measure_precision();
   5337 	get_systime(&dummy);
   5338 	sys_survivors = 0;
   5339 	sys_manycastserver = 0;
   5340 	sys_bclient = 0;
   5341 	sys_mclient = 0;
   5342 	sys_bdelay = BDELAY_DEFAULT;	/*[Bug 3031] delay cutoff */
   5343 	sys_authenticate = 1;
   5344 	sys_stattime = current_time;
   5345 	orphwait = current_time + sys_orphwait;
   5346 	proto_clr_stats();
   5347 	for (i = 0; i < MAX_TTL; ++i)
   5348 		sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
   5349 	sys_ttlmax = (MAX_TTL - 1);
   5350 	hardpps_enable = 0;
   5351 	stats_control = 1;
   5352 }
   5353 
   5354 
   5355 /*
   5356  * proto_config - configure the protocol module
   5357  */
   5358 void
   5359 proto_config(
   5360 	int	item,
   5361 	u_long	value,
   5362 	double	dvalue,
   5363 	sockaddr_u *svalue
   5364 	)
   5365 {
   5366 	/*
   5367 	 * Figure out what he wants to change, then do it
   5368 	 */
   5369 	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
   5370 		    item, value, dvalue));
   5371 
   5372 	switch (item) {
   5373 
   5374 	/*
   5375 	 * enable and disable commands - arguments are Boolean.
   5376 	 */
   5377 	case PROTO_AUTHENTICATE: /* authentication (auth) */
   5378 		sys_authenticate = value;
   5379 		break;
   5380 
   5381 	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
   5382 		sys_bclient = (int)value;
   5383 		if (!sys_bclient)
   5384 			io_unsetbclient();
   5385 		else
   5386 			io_setbclient();
   5387 		break;
   5388 
   5389 #ifdef REFCLOCK
   5390 	case PROTO_CAL:		/* refclock calibrate (calibrate) */
   5391 		cal_enable = value;
   5392 		break;
   5393 #endif /* REFCLOCK */
   5394 
   5395 	case PROTO_KERNEL:	/* kernel discipline (kernel) */
   5396 		select_loop(value);
   5397 		break;
   5398 
   5399 	case PROTO_MONITOR:	/* monitoring (monitor) */
   5400 		if (value)
   5401 			mon_start(MON_ON);
   5402 		else {
   5403 			mon_stop(MON_ON);
   5404 			if (mon_enabled)
   5405 				msyslog(LOG_WARNING,
   5406 					"restrict: 'monitor' cannot be disabled while 'limited' is enabled");
   5407 		}
   5408 		break;
   5409 
   5410 	case PROTO_NTP:		/* NTP discipline (ntp) */
   5411 		ntp_enable = value;
   5412 		break;
   5413 
   5414 	case PROTO_MODE7:	/* mode7 management (ntpdc) */
   5415 		ntp_mode7 = value;
   5416 		break;
   5417 
   5418 	case PROTO_PPS:		/* PPS discipline (pps) */
   5419 		hardpps_enable = value;
   5420 		break;
   5421 
   5422 	case PROTO_FILEGEN:	/* statistics (stats) */
   5423 		stats_control = value;
   5424 		break;
   5425 
   5426 	/*
   5427 	 * tos command - arguments are double, sometimes cast to int
   5428 	 */
   5429 
   5430 	case PROTO_BCPOLLBSTEP:	/* Broadcast Poll Backstep gate (bcpollbstep) */
   5431 		sys_bcpollbstep = (u_char)dvalue;
   5432 		break;
   5433 
   5434 	case PROTO_BEACON:	/* manycast beacon (beacon) */
   5435 		sys_beacon = (int)dvalue;
   5436 		break;
   5437 
   5438 	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
   5439 		sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
   5440 		break;
   5441 
   5442 	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
   5443 		sys_ceiling = (int)dvalue;
   5444 		break;
   5445 
   5446 	case PROTO_COHORT:	/* cohort switch (cohort) */
   5447 		sys_cohort = (int)dvalue;
   5448 		break;
   5449 
   5450 	case PROTO_FLOOR:	/* stratum floor (floor) */
   5451 		sys_floor = (int)dvalue;
   5452 		break;
   5453 
   5454 	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
   5455 		sys_maxclock = (int)dvalue;
   5456 		break;
   5457 
   5458 	case PROTO_MAXDIST:	/* select threshold (maxdist) */
   5459 		sys_maxdist = dvalue;
   5460 		break;
   5461 
   5462 	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
   5463 		break;		/* NOT USED */
   5464 
   5465 	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
   5466 		sys_minclock = (int)dvalue;
   5467 		break;
   5468 
   5469 	case PROTO_MINDISP:	/* minimum distance (mindist) */
   5470 		sys_mindisp = dvalue;
   5471 		break;
   5472 
   5473 	case PROTO_MINSANE:	/* minimum survivors (minsane) */
   5474 		sys_minsane = (int)dvalue;
   5475 		break;
   5476 
   5477 	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
   5478 		sys_orphan = (int)dvalue;
   5479 		break;
   5480 
   5481 	case PROTO_ORPHWAIT:	/* orphan wait (orphwait) */
   5482 		orphwait -= sys_orphwait;
   5483 		sys_orphwait = (dvalue >= 1) ? (int)dvalue : NTP_ORPHWAIT;
   5484 		orphwait += sys_orphwait;
   5485 		break;
   5486 
   5487 	/*
   5488 	 * Miscellaneous commands
   5489 	 */
   5490 	case PROTO_MULTICAST_ADD: /* add group address */
   5491 		if (svalue != NULL)
   5492 			io_multicast_add(svalue);
   5493 		sys_mclient = 1;
   5494 		break;
   5495 
   5496 	case PROTO_MULTICAST_DEL: /* delete group address */
   5497 		if (svalue != NULL)
   5498 			io_multicast_del(svalue);
   5499 		break;
   5500 
   5501 	/*
   5502 	 * Peer_clear Early policy choices
   5503 	 */
   5504 
   5505 	case PROTO_PCEDIGEST:	/* Digest */
   5506 		peer_clear_digest_early = value;
   5507 		break;
   5508 
   5509 	/*
   5510 	 * Unpeer Early policy choices
   5511 	 */
   5512 
   5513 	case PROTO_UECRYPTO:	/* Crypto */
   5514 		unpeer_crypto_early = value;
   5515 		break;
   5516 
   5517 	case PROTO_UECRYPTONAK:	/* Crypto_NAK */
   5518 		unpeer_crypto_nak_early = value;
   5519 		break;
   5520 
   5521 	case PROTO_UEDIGEST:	/* Digest */
   5522 		unpeer_digest_early = value;
   5523 		break;
   5524 
   5525 	default:
   5526 		msyslog(LOG_NOTICE,
   5527 		    "proto: unsupported option %d", item);
   5528 	}
   5529 }
   5530 
   5531 
   5532 /*
   5533  * proto_clr_stats - clear protocol stat counters
   5534  */
   5535 void
   5536 proto_clr_stats(void)
   5537 {
   5538 	sys_stattime = current_time;
   5539 	sys_received = 0;
   5540 	sys_processed = 0;
   5541 	sys_newversion = 0;
   5542 	sys_oldversion = 0;
   5543 	sys_declined = 0;
   5544 	sys_restricted = 0;
   5545 	sys_badlength = 0;
   5546 	sys_badauth = 0;
   5547 	sys_limitrejected = 0;
   5548 	sys_kodsent = 0;
   5549 	sys_lamport = 0;
   5550 	sys_tsrounding = 0;
   5551 }
   5552