xref: /netbsd-src/external/bsd/ntp/dist/ntpd/ntp_proto.c (revision c2f76ff004a2cb67efe5b12d97bd3ef7fe89e18d)
1 /*	$NetBSD: ntp_proto.c,v 1.2 2010/12/04 23:08:35 christos Exp $	*/
2 
3 /*
4  * ntp_proto.c - NTP version 4 protocol machinery
5  *
6  * ATTENTION: Get approval from Dave Mills on all changes to this file!
7  *
8  */
9 #ifdef HAVE_CONFIG_H
10 #include <config.h>
11 #endif
12 
13 #include "ntpd.h"
14 #include "ntp_stdlib.h"
15 #include "ntp_unixtime.h"
16 #include "ntp_control.h"
17 #include "ntp_string.h"
18 
19 #include <stdio.h>
20 #ifdef HAVE_LIBSCF_H
21 #include <libscf.h>
22 #include <unistd.h>
23 #endif /* HAVE_LIBSCF_H */
24 
25 
26 #if defined(VMS) && defined(VMS_LOCALUNIT)	/*wjm*/
27 #include "ntp_refclock.h"
28 #endif
29 
30 /*
31  * This macro defines the authentication state. If x is 1 authentication
32  * is required; othewise it is optional.
33  */
34 #define	AUTH(x, y)	((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
35 			    (y) == AUTH_NONE)
36 
37 #define	AUTH_NONE	0	/* authentication not required */
38 #define	AUTH_OK		1	/* authentication OK */
39 #define	AUTH_ERROR	2	/* authentication error */
40 #define	AUTH_CRYPTO	3	/* crypto_NAK */
41 
42 /*
43  * traffic shaping parameters
44  */
45 #define	NTP_IBURST	6	/* packets in iburst */
46 #define	RESP_DELAY	1	/* refclock burst delay (s) */
47 
48 /*
49  * System variables are declared here. Unless specified otherwise, all
50  * times are in seconds.
51  */
52 u_char	sys_leap;		/* system leap indicator */
53 u_char	sys_stratum;		/* system stratum */
54 s_char	sys_precision;		/* local clock precision (log2 s) */
55 double	sys_rootdelay;		/* roundtrip delay to primary source */
56 double	sys_rootdisp;		/* dispersion to primary source */
57 u_int32 sys_refid;		/* reference id (network byte order) */
58 l_fp	sys_reftime;		/* last update time */
59 struct	peer *sys_peer;		/* current peer */
60 
61 /*
62  * Rate controls. Leaky buckets are used to throttle the packet
63  * transmission rates in order to protect busy servers such as at NIST
64  * and USNO. There is a counter for each association and another for KoD
65  * packets. The association counter decrements each second, but not
66  * below zero. Each time a packet is sent the counter is incremented by
67  * a configurable value representing the average interval between
68  * packets. A packet is delayed as long as the counter is greater than
69  * zero. Note this does not affect the time value computations.
70  */
71 /*
72  * Nonspecified system state variables
73  */
74 int	sys_bclient;		/* broadcast client enable */
75 double	sys_bdelay;		/* broadcast client default delay */
76 int	sys_authenticate;	/* requre authentication for config */
77 l_fp	sys_authdelay;		/* authentication delay */
78 double	sys_offset;	/* current local clock offset */
79 double	sys_mindisp = MINDISPERSE; /* minimum distance (s) */
80 double	sys_maxdist = MAXDISTANCE; /* selection threshold */
81 double	sys_jitter;		/* system jitter */
82 u_long 	sys_epoch;		/* last clock update time */
83 static	double sys_clockhop;	/* clockhop threshold */
84 int	leap_tai;		/* TAI at next next leap */
85 u_long	leap_sec;		/* next scheduled leap from file */
86 u_long	leap_peers;		/* next scheduled leap from peers */
87 u_long	leap_expire;		/* leap information expiration */
88 static int leap_vote;		/* leap consensus */
89 keyid_t	sys_private;		/* private value for session seed */
90 int	sys_manycastserver;	/* respond to manycast client pkts */
91 int	peer_ntpdate;		/* active peers in ntpdate mode */
92 int	sys_survivors;		/* truest of the truechimers */
93 
94 /*
95  * TOS and multicast mapping stuff
96  */
97 int	sys_floor = 0;		/* cluster stratum floor */
98 int	sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling */
99 int	sys_minsane = 1;	/* minimum candidates */
100 int	sys_minclock = NTP_MINCLOCK; /* minimum candidates */
101 int	sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
102 int	sys_cohort = 0;		/* cohort switch */
103 int	sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
104 int	sys_beacon = BEACON;	/* manycast beacon interval */
105 int	sys_ttlmax;		/* max ttl mapping vector index */
106 u_char	sys_ttl[MAX_TTL];	/* ttl mapping vector */
107 
108 /*
109  * Statistics counters - first the good, then the bad
110  */
111 u_long	sys_stattime;		/* elapsed time */
112 u_long	sys_received;		/* packets received */
113 u_long	sys_processed;		/* packets for this host */
114 u_long	sys_newversion;		/* current version */
115 u_long	sys_oldversion;		/* old version */
116 u_long	sys_restricted;		/* access denied */
117 u_long	sys_badlength;		/* bad length or format */
118 u_long	sys_badauth;		/* bad authentication */
119 u_long	sys_declined;		/* declined */
120 u_long	sys_limitrejected;	/* rate exceeded */
121 u_long	sys_kodsent;		/* KoD sent */
122 
123 static	double	root_distance	(struct peer *);
124 static	void	clock_combine	(struct peer **, int);
125 static	void	peer_xmit	(struct peer *);
126 static	void	fast_xmit	(struct recvbuf *, int, keyid_t,
127 				    int);
128 static	void	clock_update	(struct peer *);
129 static	int	default_get_precision (void);
130 static	int	peer_unfit	(struct peer *);
131 
132 
133 /*
134  * transmit - transmit procedure called by poll timeout
135  */
136 void
137 transmit(
138 	struct peer *peer	/* peer structure pointer */
139 	)
140 {
141 	int	hpoll;
142 
143 	/*
144 	 * The polling state machine. There are two kinds of machines,
145 	 * those that never expect a reply (broadcast and manycast
146 	 * server modes) and those that do (all other modes). The dance
147 	 * is intricate...
148 	 */
149 	hpoll = peer->hpoll;
150 
151 	/*
152 	 * In broadcast mode the poll interval is never changed from
153 	 * minpoll.
154 	 */
155 	if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
156 		peer->outdate = current_time;
157 		if (sys_leap != LEAP_NOTINSYNC)
158 			peer_xmit(peer);
159 		poll_update(peer, hpoll);
160 		return;
161 	}
162 
163 	/*
164 	 * In manycast mode we start with unity ttl. The ttl is
165 	 * increased by one for each poll until either sys_maxclock
166 	 * servers have been found or the maximum ttl is reached. When
167 	 * sys_maxclock servers are found we stop polling until one or
168 	 * more servers have timed out or until less than minpoll
169 	 * associations turn up. In this case additional better servers
170 	 * are dragged in and preempt the existing ones.
171 	 */
172 	if (peer->cast_flags & MDF_ACAST) {
173 		peer->outdate = current_time;
174 		if (peer->unreach > sys_beacon) {
175 			peer->unreach = 0;
176 			peer->ttl = 0;
177 			peer_xmit(peer);
178 		} else if (sys_survivors < sys_minclock ||
179 		    peer_associations < sys_maxclock) {
180 			if (peer->ttl < sys_ttlmax)
181 				peer->ttl++;
182 			peer_xmit(peer);
183 		}
184 		peer->unreach++;
185 		poll_update(peer, hpoll);
186 		return;
187 	}
188 
189 	/*
190 	 * In unicast modes the dance is much more intricate. It is
191 	 * desigmed to back off whenever possible to minimize network
192 	 * traffic.
193 	 */
194 	if (peer->burst == 0) {
195 		u_char oreach;
196 
197 		/*
198 		 * Update the reachability status. If not heard for
199 		 * three consecutive polls, stuff infinity in the clock
200 		 * filter.
201 		 */
202 		oreach = peer->reach;
203 		peer->outdate = current_time;
204 		peer->unreach++;
205 		peer->reach <<= 1;
206 		if (!(peer->reach & 0x0f))
207 			clock_filter(peer, 0., 0., MAXDISPERSE);
208 		if (!peer->reach) {
209 
210 			/*
211 			 * Here the peer is unreachable. If it was
212 			 * previously reachable raise a trap. Send a
213 			 * burst if enabled.
214 			 */
215 			if (oreach)
216 				report_event(PEVNT_UNREACH, peer, NULL);
217 			if ((peer->flags & FLAG_IBURST) &&
218 			    peer->retry == 0)
219 				peer->retry = NTP_RETRY;
220 		} else {
221 
222 			/*
223 			 * Here the peer is reachable. Send a burst if
224 			 * enabled and the peer is fit.
225 			 */
226 			hpoll = sys_poll;
227 			if (!(peer->flags & FLAG_PREEMPT &&
228 			    peer->hmode == MODE_CLIENT))
229 				peer->unreach = 0;
230 			if ((peer->flags & FLAG_BURST) && peer->retry ==
231 			    0 && !peer_unfit(peer))
232 				peer->retry = NTP_RETRY;
233 		}
234 
235 		/*
236 		 * Watch for timeout. If preemptable, toss the rascal;
237 		 * otherwise, bump the poll interval. Note the
238 		 * poll_update() routine will clamp it to maxpoll.
239 		 */
240 		if (peer->unreach >= NTP_UNREACH) {
241 			hpoll++;
242 			if (peer->flags & FLAG_PREEMPT) {
243 				report_event(PEVNT_RESTART, peer,
244 				    "timeout");
245 				if (peer->hmode != MODE_CLIENT) {
246 					peer_clear(peer, "TIME");
247 					unpeer(peer);
248 					return;
249 				}
250 				if (peer_associations > sys_maxclock &&
251 				    score_all(peer)) {
252 					peer_clear(peer, "TIME");
253 					unpeer(peer);
254 					return;
255 				}
256 			}
257 		}
258 	} else {
259 		peer->burst--;
260 		if (peer->burst == 0) {
261 
262 			/*
263 			 * If ntpdate mode and the clock has not been
264 			 * set and all peers have completed the burst,
265 			 * we declare a successful failure.
266 			 */
267 			if (mode_ntpdate) {
268 				peer_ntpdate--;
269 				if (peer_ntpdate == 0) {
270 					msyslog(LOG_NOTICE,
271 					    "ntpd: no servers found");
272 					printf(
273 					    "ntpd: no servers found\n");
274 					exit (0);
275 				}
276 			}
277 		}
278 	}
279 	if (peer->retry > 0)
280 		peer->retry--;
281 
282 	/*
283 	 * Do not transmit if in broadcast client mode.
284 	 */
285 	if (peer->hmode != MODE_BCLIENT)
286 		peer_xmit(peer);
287 	poll_update(peer, hpoll);
288 }
289 
290 
291 /*
292  * receive - receive procedure called for each packet received
293  */
294 void
295 receive(
296 	struct recvbuf *rbufp
297 	)
298 {
299 	register struct peer *peer;	/* peer structure pointer */
300 	register struct pkt *pkt;	/* receive packet pointer */
301 	int	hisversion;		/* packet version */
302 	int	hisleap;		/* packet leap indicator */
303 	int	hismode;		/* packet mode */
304 	int	hisstratum;		/* packet stratum */
305 	int	restrict_mask;		/* restrict bits */
306 	int	has_mac;		/* length of MAC field */
307 	int	authlen;		/* offset of MAC field */
308 	int	is_authentic = 0;	/* cryptosum ok */
309 	int	retcode = AM_NOMATCH;	/* match code */
310 	keyid_t	skeyid = 0;		/* key IDs */
311 	u_int32	opcode = 0;		/* extension field opcode */
312 	sockaddr_u *dstadr_sin; 	/* active runway */
313 	struct peer *peer2;		/* aux peer structure pointer */
314 	l_fp	p_org;			/* origin timestamp */
315 	l_fp	p_rec;			/* receive timestamp */
316 	l_fp	p_xmt;			/* transmit timestamp */
317 #ifdef OPENSSL
318 	struct autokey *ap;		/* autokey structure pointer */
319 	int	rval;			/* cookie snatcher */
320 	keyid_t	pkeyid = 0, tkeyid = 0;	/* key IDs */
321 #endif /* OPENSSL */
322 #ifdef HAVE_NTP_SIGND
323 	static unsigned char zero_key[16];
324 #endif /* HAVE_NTP_SIGND */
325 
326 	/*
327 	 * Monitor the packet and get restrictions. Note that the packet
328 	 * length for control and private mode packets must be checked
329 	 * by the service routines. Some restrictions have to be handled
330 	 * later in order to generate a kiss-o'-death packet.
331 	 */
332 	/*
333 	 * Bogus port check is before anything, since it probably
334 	 * reveals a clogging attack.
335 	 */
336 	sys_received++;
337 	if (SRCPORT(&rbufp->recv_srcadr) < NTP_PORT) {
338 		sys_badlength++;
339 		return;				/* bogus port */
340 	}
341 	restrict_mask = restrictions(&rbufp->recv_srcadr);
342 #ifdef DEBUG
343 	if (debug > 1)
344 		printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
345 		    current_time, stoa(&rbufp->dstadr->sin),
346 		    stoa(&rbufp->recv_srcadr),
347 		    rbufp->dstadr->flags, restrict_mask);
348 #endif
349 	pkt = &rbufp->recv_pkt;
350 	hisversion = PKT_VERSION(pkt->li_vn_mode);
351 	hisleap = PKT_LEAP(pkt->li_vn_mode);
352 	hismode = (int)PKT_MODE(pkt->li_vn_mode);
353 	hisstratum = PKT_TO_STRATUM(pkt->stratum);
354 	if (restrict_mask & RES_IGNORE) {
355 		sys_restricted++;
356 		return;				/* ignore everything */
357 	}
358 	if (hismode == MODE_PRIVATE) {
359 		if (restrict_mask & RES_NOQUERY) {
360 			sys_restricted++;
361 			return;			/* no query private */
362 		}
363 		process_private(rbufp, ((restrict_mask &
364 		    RES_NOMODIFY) == 0));
365 		return;
366 	}
367 	if (hismode == MODE_CONTROL) {
368 		if (restrict_mask & RES_NOQUERY) {
369 			sys_restricted++;
370 			return;			/* no query control */
371 		}
372 		process_control(rbufp, restrict_mask);
373 		return;
374 	}
375 	if (restrict_mask & RES_DONTSERVE) {
376 		sys_restricted++;
377 		return;				/* no time serve */
378 	}
379 
380 	/*
381 	 * This is for testing. If restricted drop ten percent of
382 	 * surviving packets.
383 	 */
384 	if (restrict_mask & RES_TIMEOUT) {
385 		if ((double)ntp_random() / 0x7fffffff < .1) {
386 			sys_restricted++;
387 			return;			/* no flakeway */
388 		}
389 	}
390 
391 	/*
392 	 * Version check must be after the query packets, since they
393 	 * intentionally use an early version.
394 	 */
395 	if (hisversion == NTP_VERSION) {
396 		sys_newversion++;		/* new version */
397 	} else if (!(restrict_mask & RES_VERSION) && hisversion >=
398 	    NTP_OLDVERSION) {
399 		sys_oldversion++;		/* previous version */
400 	} else {
401 		sys_badlength++;
402 		return;				/* old version */
403 	}
404 
405 	/*
406 	 * Figure out his mode and validate the packet. This has some
407 	 * legacy raunch that probably should be removed. In very early
408 	 * NTP versions mode 0 was equivalent to what later versions
409 	 * would interpret as client mode.
410 	 */
411 	if (hismode == MODE_UNSPEC) {
412 		if (hisversion == NTP_OLDVERSION) {
413 			hismode = MODE_CLIENT;
414 		} else {
415 			sys_badlength++;
416 			return;                 /* invalid mode */
417 		}
418 	}
419 
420 	/*
421 	 * Parse the extension field if present. We figure out whether
422 	 * an extension field is present by measuring the MAC size. If
423 	 * the number of words following the packet header is 0, no MAC
424 	 * is present and the packet is not authenticated. If 1, the
425 	 * packet is a crypto-NAK; if 3, the packet is authenticated
426 	 * with DES; if 5, the packet is authenticated with MD5; if 6,
427 	 * the packet is authenticated with SHA. If 2 or * 4, the packet
428 	 * is a runt and discarded forthwith. If greater than 6, an
429 	 * extension field is present, so we subtract the length of the
430 	 * field and go around again.
431 	 */
432 	authlen = LEN_PKT_NOMAC;
433 	has_mac = rbufp->recv_length - authlen;
434 	while (has_mac != 0) {
435 		u_int32	len;
436 
437 		if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
438 			sys_badlength++;
439 			return;			/* bad length */
440 		}
441 		if (has_mac <= (int)MAX_MAC_LEN) {
442 			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
443 			break;
444 
445 		} else {
446 			opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
447  			len = opcode & 0xffff;
448 			if (len % 4 != 0 || len < 4 || (int)(len + authlen) >
449 			    rbufp->recv_length) {
450 				sys_badlength++;
451 				return;		/* bad length */
452 			}
453 			authlen += len;
454 			has_mac -= len;
455 		}
456 	}
457 
458 	/*
459 	 * If authentication required, a MAC must be present.
460 	 */
461 	if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
462 		sys_restricted++;
463 		return;				/* access denied */
464 	}
465 
466 	/*
467 	 * Update the MRU list and finger the cloggers. It can be a
468 	 * little expensive, so turn it off for production use.
469 	 */
470 	restrict_mask = ntp_monitor(rbufp, restrict_mask);
471 	if (restrict_mask & RES_LIMITED) {
472 		sys_limitrejected++;
473 		if (!(restrict_mask & RES_KOD) || hismode ==
474 		    MODE_BROADCAST)
475 			return;			/* rate exceeded */
476 
477 		if (hismode == MODE_CLIENT)
478 			fast_xmit(rbufp, MODE_SERVER, skeyid,
479 			    restrict_mask);
480 		else
481 			fast_xmit(rbufp, MODE_ACTIVE, skeyid,
482 			    restrict_mask);
483 		return;				/* rate exceeded */
484 	}
485 	restrict_mask &= ~RES_KOD;
486 
487 	/*
488 	 * We have tossed out as many buggy packets as possible early in
489 	 * the game to reduce the exposure to a clogging attack. now we
490 	 * have to burn some cycles to find the association and
491 	 * authenticate the packet if required. Note that we burn only
492 	 * MD5 cycles, again to reduce exposure. There may be no
493 	 * matching association and that's okay.
494 	 *
495 	 * More on the autokey mambo. Normally the local interface is
496 	 * found when the association was mobilized with respect to a
497 	 * designated remote address. We assume packets arriving from
498 	 * the remote address arrive via this interface and the local
499 	 * address used to construct the autokey is the unicast address
500 	 * of the interface. However, if the sender is a broadcaster,
501 	 * the interface broadcast address is used instead.
502 	 * Notwithstanding this technobabble, if the sender is a
503 	 * multicaster, the broadcast address is null, so we use the
504 	 * unicast address anyway. Don't ask.
505 	 */
506 	peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr,  hismode,
507 	    &retcode);
508 	dstadr_sin = &rbufp->dstadr->sin;
509 	NTOHL_FP(&pkt->org, &p_org);
510 	NTOHL_FP(&pkt->rec, &p_rec);
511 	NTOHL_FP(&pkt->xmt, &p_xmt);
512 
513 	/*
514 	 * Authentication is conditioned by three switches:
515 	 *
516 	 * NOPEER  (RES_NOPEER) do not mobilize an association unless
517 	 *         authenticated
518 	 * NOTRUST (RES_DONTTRUST) do not allow access unless
519 	 *         authenticated (implies NOPEER)
520 	 * enable  (sys_authenticate) master NOPEER switch, by default
521 	 *         on
522 	 *
523 	 * The NOPEER and NOTRUST can be specified on a per-client basis
524 	 * using the restrict command. The enable switch if on implies
525 	 * NOPEER for all clients. There are four outcomes:
526 	 *
527 	 * NONE    The packet has no MAC.
528 	 * OK      the packet has a MAC and authentication succeeds
529 	 * ERROR   the packet has a MAC and authentication fails
530 	 * CRYPTO  crypto-NAK. The MAC has four octets only.
531 	 *
532 	 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
533 	 * is zero, acceptable outcomes of y are NONE and OK. If x is
534 	 * one, the only acceptable outcome of y is OK.
535 	 */
536 
537 	if (has_mac == 0) {
538 		restrict_mask &= ~RES_MSSNTP;
539 		is_authentic = AUTH_NONE; /* not required */
540 #ifdef DEBUG
541 		if (debug)
542 			printf(
543 			    "receive: at %ld %s<-%s mode %d len %d\n",
544 			    current_time, stoa(dstadr_sin),
545 			    stoa(&rbufp->recv_srcadr), hismode,
546 			    authlen);
547 #endif
548 	} else if (has_mac == 4) {
549 		restrict_mask &= ~RES_MSSNTP;
550 		is_authentic = AUTH_CRYPTO; /* crypto-NAK */
551 #ifdef DEBUG
552 		if (debug)
553 			printf(
554 			    "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
555 			    current_time, stoa(dstadr_sin),
556 			    stoa(&rbufp->recv_srcadr), hismode, skeyid,
557 			    authlen + has_mac, is_authentic);
558 #endif
559 
560 #ifdef HAVE_NTP_SIGND
561 		/*
562 		 * If the signature is 20 bytes long, the last 16 of
563 		 * which are zero, then this is a Microsoft client
564 		 * wanting AD-style authentication of the server's
565 		 * reply.
566 		 *
567 		 * This is described in Microsoft's WSPP docs, in MS-SNTP:
568 		 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
569 		 */
570 	} else if (has_mac == MAX_MD5_LEN && (restrict_mask & RES_MSSNTP) &&
571 	   (retcode == AM_FXMIT || retcode == AM_NEWPASS) &&
572 	   (memcmp(zero_key, (char *)pkt + authlen + 4, MAX_MD5_LEN - 4) ==
573 	   0)) {
574 		is_authentic = AUTH_NONE;
575 #endif /* HAVE_NTP_SIGND */
576 
577 	} else {
578 		restrict_mask &= ~RES_MSSNTP;
579 #ifdef OPENSSL
580 		/*
581 		 * For autokey modes, generate the session key
582 		 * and install in the key cache. Use the socket
583 		 * broadcast or unicast address as appropriate.
584 		 */
585 		if (crypto_flags && skeyid > NTP_MAXKEY) {
586 
587 			/*
588 			 * More on the autokey dance (AKD). A cookie is
589 			 * constructed from public and private values.
590 			 * For broadcast packets, the cookie is public
591 			 * (zero). For packets that match no
592 			 * association, the cookie is hashed from the
593 			 * addresses and private value. For server
594 			 * packets, the cookie was previously obtained
595 			 * from the server. For symmetric modes, the
596 			 * cookie was previously constructed using an
597 			 * agreement protocol; however, should PKI be
598 			 * unavailable, we construct a fake agreement as
599 			 * the EXOR of the peer and host cookies.
600 			 *
601 			 * hismode	ephemeral	persistent
602 			 * =======================================
603 			 * active	0		cookie#
604 			 * passive	0%		cookie#
605 			 * client	sys cookie	0%
606 			 * server	0%		sys cookie
607 			 * broadcast	0		0
608 			 *
609 			 * # if unsync, 0
610 			 * % can't happen
611 			 */
612 			if (has_mac < (int)MAX_MD5_LEN) {
613 				sys_badauth++;
614 				return;
615 			}
616 			if (hismode == MODE_BROADCAST) {
617 
618 				/*
619 				 * For broadcaster, use the interface
620 				 * broadcast address when available;
621 				 * otherwise, use the unicast address
622 				 * found when the association was
623 				 * mobilized. However, if this is from
624 				 * the wildcard interface, game over.
625 				 */
626 				if (crypto_flags && rbufp->dstadr ==
627 				    any_interface) {
628 					sys_restricted++;
629 					return;	     /* no wildcard */
630 				}
631 				pkeyid = 0;
632 				if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
633 					dstadr_sin =
634 					    &rbufp->dstadr->bcast;
635 			} else if (peer == NULL) {
636 				pkeyid = session_key(
637 				    &rbufp->recv_srcadr, dstadr_sin, 0,
638 				    sys_private, 0);
639 			} else {
640 				pkeyid = peer->pcookie;
641 			}
642 
643 			/*
644 			 * The session key includes both the public
645 			 * values and cookie. In case of an extension
646 			 * field, the cookie used for authentication
647 			 * purposes is zero. Note the hash is saved for
648 			 * use later in the autokey mambo.
649 			 */
650 			if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
651 				session_key(&rbufp->recv_srcadr,
652 				    dstadr_sin, skeyid, 0, 2);
653 				tkeyid = session_key(
654 				    &rbufp->recv_srcadr, dstadr_sin,
655 				    skeyid, pkeyid, 0);
656 			} else {
657 				tkeyid = session_key(
658 				    &rbufp->recv_srcadr, dstadr_sin,
659 				    skeyid, pkeyid, 2);
660 			}
661 
662 		}
663 #endif /* OPENSSL */
664 
665 		/*
666 		 * Compute the cryptosum. Note a clogging attack may
667 		 * succeed in bloating the key cache. If an autokey,
668 		 * purge it immediately, since we won't be needing it
669 		 * again. If the packet is authentic, it can mobilize an
670 		 * association. Note that there is no key zero.
671 		 */
672 		if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
673 		    has_mac))
674 			is_authentic = AUTH_ERROR;
675 		else
676 			is_authentic = AUTH_OK;
677 #ifdef OPENSSL
678 		if (crypto_flags && skeyid > NTP_MAXKEY)
679 			authtrust(skeyid, 0);
680 #endif /* OPENSSL */
681 #ifdef DEBUG
682 		if (debug)
683 			printf(
684 			    "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
685 			    current_time, stoa(dstadr_sin),
686 			    stoa(&rbufp->recv_srcadr), hismode, skeyid,
687 			    authlen + has_mac, is_authentic);
688 #endif
689 	}
690 
691 	/*
692 	 * The association matching rules are implemented by a set of
693 	 * routines and an association table. A packet matching an
694 	 * association is processed by the peer process for that
695 	 * association. If there are no errors, an ephemeral association
696 	 * is mobilized: a broadcast packet mobilizes a broadcast client
697 	 * aassociation; a manycast server packet mobilizes a manycast
698 	 * client association; a symmetric active packet mobilizes a
699 	 * symmetric passive association.
700 	 */
701 	switch (retcode) {
702 
703 	/*
704 	 * This is a client mode packet not matching any association. If
705 	 * an ordinary client, simply toss a server mode packet back
706 	 * over the fence. If a manycast client, we have to work a
707 	 * little harder.
708 	 */
709 	case AM_FXMIT:
710 
711 		/*
712 		 * If authentication OK, send a server reply; otherwise,
713 		 * send a crypto-NAK.
714 		 */
715 		if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
716 			if (AUTH(restrict_mask & RES_DONTTRUST,
717 			   is_authentic)) {
718 				fast_xmit(rbufp, MODE_SERVER, skeyid,
719 				    restrict_mask);
720 			} else if (is_authentic == AUTH_ERROR) {
721 				fast_xmit(rbufp, MODE_SERVER, 0,
722 				    restrict_mask);
723 				sys_badauth++;
724 			} else {
725 				sys_restricted++;
726 			}
727 			return;			/* hooray */
728 		}
729 
730 		/*
731 		 * This must be manycast. Do not respond if not
732 		 * configured as a manycast server.
733 		 */
734 		if (!sys_manycastserver) {
735 			sys_restricted++;
736 			return;			/* not enabled */
737 		}
738 
739 		/*
740 		 * Do not respond if we are not synchronized or our
741 		 * stratum is greater than the manycaster or the
742 		 * manycaster has already synchronized to us.
743 		 */
744 		if (sys_leap == LEAP_NOTINSYNC || sys_stratum >=
745 		    hisstratum || (!sys_cohort && sys_stratum ==
746 		    hisstratum + 1) || rbufp->dstadr->addr_refid ==
747 		    pkt->refid) {
748 			sys_declined++;
749 			return;			/* no help */
750 		}
751 
752 		/*
753 		 * Respond only if authentication succeeds. Don't do a
754 		 * crypto-NAK, as that would not be useful.
755 		 */
756 		if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
757 			fast_xmit(rbufp, MODE_SERVER, skeyid,
758 			    restrict_mask);
759 		return;				/* hooray */
760 
761 	/*
762 	 * This is a server mode packet returned in response to a client
763 	 * mode packet sent to a multicast group address. The origin
764 	 * timestamp is a good nonce to reliably associate the reply
765 	 * with what was sent. If there is no match, that's curious and
766 	 * could be an intruder attempting to clog, so we just ignore
767 	 * it.
768 	 *
769 	 * If the packet is authentic and the manycast association is
770 	 * found, we mobilize a client association and copy pertinent
771 	 * variables from the manycast association to the new client
772 	 * association. If not, just ignore the packet.
773 	 *
774 	 * There is an implosion hazard at the manycast client, since
775 	 * the manycast servers send the server packet immediately. If
776 	 * the guy is already here, don't fire up a duplicate.
777 	 */
778 	case AM_MANYCAST:
779 		if (!AUTH(sys_authenticate | (restrict_mask &
780 		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
781 			sys_restricted++;
782 			return;			/* access denied */
783 		}
784 
785 		/*
786 		 * Do not respond if unsynchronized or stratum is below
787 		 * the floor or at or above the ceiling.
788 		 */
789 		if (hisleap == LEAP_NOTINSYNC || hisstratum <
790 		    sys_floor || hisstratum >= sys_ceiling) {
791 			sys_declined++;
792 			return;			/* no help */
793 		}
794 		if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
795 			sys_restricted++;
796 			return;			/* not enabled */
797 		}
798 		if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
799 		    MODE_CLIENT, hisversion, NTP_MINDPOLL, NTP_MAXDPOLL,
800 		    FLAG_PREEMPT, MDF_UCAST | MDF_ACLNT, 0, skeyid)) ==
801 		    NULL) {
802 			sys_declined++;
803 			return;			/* ignore duplicate  */
804 		}
805 
806 		/*
807 		 * We don't need these, but it warms the billboards.
808 		 */
809 		if (peer2->flags & FLAG_IBURST)
810 			peer->flags |= FLAG_IBURST;
811 		peer->minpoll = peer2->minpoll;
812 		peer->maxpoll = peer2->maxpoll;
813 		break;
814 
815 	/*
816 	 * This is the first packet received from a broadcast server. If
817 	 * the packet is authentic and we are enabled as broadcast
818 	 * client, mobilize a broadcast client association. We don't
819 	 * kiss any frogs here.
820 	 */
821 	case AM_NEWBCL:
822 		if (sys_bclient == 0) {
823 			sys_restricted++;
824 			return;			/* not enabled */
825 		}
826 		if (!AUTH(sys_authenticate | (restrict_mask &
827 		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
828 			sys_restricted++;
829 			return;			/* access denied */
830 		}
831 
832 		/*
833 		 * Do not respond if unsynchronized or stratum is below
834 		 * the floor or at or above the ceiling.
835 		 */
836 		if (hisleap == LEAP_NOTINSYNC || hisstratum <
837 		    sys_floor || hisstratum >= sys_ceiling) {
838 			sys_declined++;
839 			return;			/* no help */
840 		}
841 
842 #ifdef OPENSSL
843 		/*
844 		 * Do not respond if Autokey and the opcode is not a
845 		 * CRYPTO_ASSOC response with associationn ID.
846 		 */
847 		if (crypto_flags && skeyid > NTP_MAXKEY && (opcode &
848 		    0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
849 			sys_declined++;
850 			return;			/* protocol error */
851 		}
852 #endif /* OPENSSL */
853 
854 		/*
855 		 * Determine whether to execute the initial volley.
856 		 */
857 		if (sys_bdelay != 0) {
858 #ifdef OPENSSL
859 			/*
860 			 * If a two-way exchange is not possible,
861 			 * neither is Autokey.
862 			 */
863 			if (crypto_flags && skeyid > NTP_MAXKEY) {
864 				sys_restricted++;
865 				return;		/* no autokey */
866 			}
867 #endif /* OPENSSL */
868 
869 			/*
870 			 * Do not execute the volley. Start out in
871 			 * broadcast client mode.
872 			 */
873 			if ((peer = newpeer(&rbufp->recv_srcadr,
874 			    rbufp->dstadr, MODE_BCLIENT, hisversion,
875 			    pkt->ppoll, pkt->ppoll, 0, 0, 0,
876 			    skeyid)) == NULL) {
877 				sys_restricted++;
878 				return;		/* ignore duplicate */
879 
880 			} else {
881 				peer->delay = sys_bdelay;
882 				peer->bias = -sys_bdelay / 2.;
883 			}
884 			break;
885 		}
886 
887 		/*
888 		 * Execute the initial volley in order to calibrate the
889 		 * propagation delay and run the Autokey protocol.
890 		 *
891 		 * Note that the minpoll is taken from the broadcast
892 		 * packet, normally 6 (64 s) and that the poll interval
893 		 * is fixed at this value.
894 		 */
895 		if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
896 		    MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
897 		    FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT, 0,
898 		    skeyid)) == NULL) {
899 			sys_restricted++;
900 			return;			/* ignore duplicate */
901 		}
902 #ifdef OPENSSL
903 		if (skeyid > NTP_MAXKEY)
904 			crypto_recv(peer, rbufp);
905 #endif /* OPENSSL */
906 
907 		return;				/* hooray */
908 
909 	/*
910 	 * This is the first packet received from a symmetric active
911 	 * peer. If the packet is authentic and the first he sent,
912 	 * mobilize a passive association. If not, kiss the frog.
913 	 */
914 	case AM_NEWPASS:
915 		if (!AUTH(sys_authenticate | (restrict_mask &
916 		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
917 
918 			/*
919 			 * If authenticated but cannot mobilize an
920 			 * association, send a symmetric passive
921 			 * response without mobilizing an association.
922 			 * This is for drat broken Windows clients. See
923 			 * Microsoft KB 875424 for preferred workaround.
924 			 */
925 			if (AUTH(restrict_mask & RES_DONTTRUST,
926 			    is_authentic)) {
927 				fast_xmit(rbufp, MODE_PASSIVE, skeyid,
928 				    restrict_mask);
929 				return;			/* hooray */
930 			}
931 			if (is_authentic == AUTH_ERROR) {
932 				fast_xmit(rbufp, MODE_ACTIVE, 0,
933 				    restrict_mask);
934 				sys_restricted++;
935 			}
936 		}
937 
938 		/*
939 		 * Do not respond if synchronized and stratum is either
940 		 * below the floor or at or above the ceiling. Note,
941 		 * this allows an unsynchronized peer to synchronize to
942 		 * us. It would be very strange if he did and then was
943 		 * nipped, but that could only happen if we were
944 		 * operating at the top end of the range.
945 		 */
946 		if (hisleap != LEAP_NOTINSYNC && (hisstratum <
947 		    sys_floor || hisstratum >= sys_ceiling)) {
948 			sys_declined++;
949 			return;			/* no help */
950 		}
951 
952 		/*
953 		 * The message is correctly authenticated and
954 		 * allowed. Mobiliae a symmetric passive association.
955 		 */
956 		if ((peer = newpeer(&rbufp->recv_srcadr,
957 		    rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
958 		    NTP_MAXDPOLL, FLAG_PREEMPT, MDF_UCAST, 0,
959 		    skeyid)) == NULL) {
960 			sys_declined++;
961 			return;			/* ignore duplicate */
962 		}
963 		break;
964 
965 
966 	/*
967 	 * Process regular packet. Nothing special.
968 	 */
969 	case AM_PROCPKT:
970 		break;
971 
972 	/*
973 	 * A passive packet matches a passive association. This is
974 	 * usually the result of reconfiguring a client on the fly. As
975 	 * this association might be legitamate and this packet an
976 	 * attempt to deny service, just ignore it.
977 	 */
978 	case AM_ERR:
979 		sys_declined++;
980 		return;
981 
982 	/*
983 	 * For everything else there is the bit bucket.
984 	 */
985 	default:
986 		sys_declined++;
987 		return;
988 	}
989 
990 #ifdef OPENSSL
991 	/*
992 	 * If the association is configured for Autokey, the packet must
993 	 * have a public key ID; if not, the packet must have a
994 	 * symmetric key ID.
995 	 */
996 	if (is_authentic != AUTH_CRYPTO && (((peer->flags &
997 	    FLAG_SKEY) && skeyid <= NTP_MAXKEY) || (!(peer->flags &
998 	    FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
999 		sys_badauth++;
1000 		return;
1001 	}
1002 #endif /* OPENSSL */
1003 	peer->received++;
1004 	peer->flash &= ~PKT_TEST_MASK;
1005 	if (peer->flags & FLAG_XBOGUS) {
1006 		peer->flags &= ~FLAG_XBOGUS;
1007 		peer->flash |= TEST3;
1008 	}
1009 
1010 	/*
1011 	 * Next comes a rigorous schedule of timestamp checking. If the
1012 	 * transmit timestamp is zero, the server has not initialized in
1013 	 * interleaved modes or is horribly broken.
1014 	 */
1015 	if (L_ISZERO(&p_xmt)) {
1016 		peer->flash |= TEST3;			/* unsynch */
1017 
1018 	/*
1019 	 * If the transmit timestamp duplicates a previous one, the
1020 	 * packet is a replay. This prevents the bad guys from replaying
1021 	 * the most recent packet, authenticated or not.
1022 	 */
1023 	} else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1024 		peer->flash |= TEST1;			/* duplicate */
1025 		peer->oldpkt++;
1026 		return;
1027 
1028 	/*
1029 	 * If this is a broadcast mode packet, skip further checking. If
1030 	 * an intial volley, bail out now and let the client do its
1031 	 * stuff. If the origin timestamp is nonzero, this is an
1032 	 * interleaved broadcast. so restart the protocol.
1033 	 */
1034 	} else if (hismode == MODE_BROADCAST) {
1035 		if (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) {
1036 			peer->flags |= FLAG_XB;
1037 			peer->aorg = p_xmt;
1038 			peer->borg = rbufp->recv_time;
1039 			report_event(PEVNT_XLEAVE, peer, NULL);
1040 			return;
1041 		}
1042 
1043 	/*
1044 	 * Check for bogus packet in basic mode. If found, switch to
1045 	 * interleaved mode and resynchronize, but only after confirming
1046 	 * the packet is not bogus in symmetric interleaved mode.
1047 	 */
1048 	} else if (peer->flip == 0) {
1049 		if (!L_ISEQU(&p_org, &peer->aorg)) {
1050 			peer->bogusorg++;
1051 			peer->flash |= TEST2;	/* bogus */
1052 			if (!L_ISZERO(&peer->dst) && L_ISEQU(&p_org,
1053 			    &peer->dst)) {
1054 				peer->flip = 1;
1055 				report_event(PEVNT_XLEAVE, peer, NULL);
1056 			}
1057 		} else {
1058 			L_CLR(&peer->aorg);
1059 		}
1060 
1061 	/*
1062 	 * Check for valid nonzero timestamp fields.
1063 	 */
1064 	} else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) ||
1065 	    L_ISZERO(&peer->dst)) {
1066 		peer->flash |= TEST3;		/* unsynch */
1067 
1068 	/*
1069 	 * Check for bogus packet in interleaved symmetric mode. This
1070 	 * can happen if a packet is lost, duplicat or crossed. If
1071 	 * found, flip and resynchronize.
1072 	 */
1073 	} else if (!L_ISZERO(&peer->dst) && !L_ISEQU(&p_org,
1074 		    &peer->dst)) {
1075 			peer->bogusorg++;
1076 			peer->flags |= FLAG_XBOGUS;
1077 			peer->flash |= TEST2;		/* bogus */
1078 	}
1079 
1080 	/*
1081 	 * Update the state variables.
1082 	 */
1083 	if (peer->flip == 0) {
1084 		if (hismode != MODE_BROADCAST)
1085 			peer->rec = p_xmt;
1086 		peer->dst = rbufp->recv_time;
1087 	}
1088 	peer->xmt = p_xmt;
1089 
1090 	/*
1091 	 * If this is a crypto_NAK, the server cannot authenticate a
1092 	 * client packet. The server might have just changed keys. Clear
1093 	 * the association and restart the protocol.
1094 	 */
1095 	if (is_authentic == AUTH_CRYPTO) {
1096 		report_event(PEVNT_AUTH, peer, "crypto_NAK");
1097 		peer->flash |= TEST5;		/* bad auth */
1098 		peer->badauth++;
1099 		if (peer->flags & FLAG_PREEMPT) {
1100 			unpeer(peer);
1101 			return;
1102 		}
1103 #ifdef OPENSSL
1104 		if (peer->crypto)
1105 			peer_clear(peer, "AUTH");
1106 #endif /* OPENSSL */
1107 		return;
1108 
1109 	/*
1110 	 * If the digest fails, the client cannot authenticate a server
1111 	 * reply to a client packet previously sent. The loopback check
1112 	 * is designed to avoid a bait-and-switch attack, which was
1113 	 * possible in past versions. If symmetric modes, return a
1114 	 * crypto-NAK. The peer should restart the protocol.
1115 	 */
1116 	} else if (!AUTH(has_mac || (restrict_mask & RES_DONTTRUST),
1117 	    is_authentic)) {
1118 		report_event(PEVNT_AUTH, peer, "digest");
1119 		peer->flash |= TEST5;		/* bad auth */
1120 		peer->badauth++;
1121 		if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)
1122 			fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1123 		if (peer->flags & FLAG_PREEMPT) {
1124 			unpeer(peer);
1125 			return;
1126 		}
1127 #ifdef OPENSSL
1128 		if (peer->crypto)
1129 			peer_clear(peer, "AUTH");
1130 #endif /* OPENSSL */
1131 		return;
1132 	}
1133 
1134 	/*
1135 	 * Set the peer ppoll to the maximum of the packet ppoll and the
1136 	 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1137 	 * this maximumn and advance the headway to give the sender some
1138 	 * headroom. Very intricate.
1139 	 */
1140 	peer->ppoll = max(peer->minpoll, pkt->ppoll);
1141 	if (hismode == MODE_SERVER && hisleap == LEAP_NOTINSYNC &&
1142 	    hisstratum == STRATUM_UNSPEC && memcmp(&pkt->refid,
1143 	    "RATE", 4) == 0) {
1144 		peer->selbroken++;
1145 		report_event(PEVNT_RATE, peer, NULL);
1146 		if (pkt->ppoll > peer->minpoll)
1147 			peer->minpoll = peer->ppoll;
1148 		peer->burst = peer->retry = 0;
1149 		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1150 		poll_update(peer, pkt->ppoll);
1151 		return;				/* kiss-o'-death */
1152 	}
1153 
1154 	/*
1155 	 * That was hard and I am sweaty, but the packet is squeaky
1156 	 * clean. Get on with real work.
1157 	 */
1158 	peer->timereceived = current_time;
1159 	if (is_authentic == AUTH_OK)
1160 		peer->flags |= FLAG_AUTHENTIC;
1161 	else
1162 		peer->flags &= ~FLAG_AUTHENTIC;
1163 
1164 #ifdef OPENSSL
1165 	/*
1166 	 * More autokey dance. The rules of the cha-cha are as follows:
1167 	 *
1168 	 * 1. If there is no key or the key is not auto, do nothing.
1169 	 *
1170 	 * 2. If this packet is in response to the one just previously
1171 	 *    sent or from a broadcast server, do the extension fields.
1172 	 *    Otherwise, assume bogosity and bail out.
1173 	 *
1174 	 * 3. If an extension field contains a verified signature, it is
1175 	 *    self-authenticated and we sit the dance.
1176 	 *
1177 	 * 4. If this is a server reply, check only to see that the
1178 	 *    transmitted key ID matches the received key ID.
1179 	 *
1180 	 * 5. Check to see that one or more hashes of the current key ID
1181 	 *    matches the previous key ID or ultimate original key ID
1182 	 *    obtained from the broadcaster or symmetric peer. If no
1183 	 *    match, sit the dance and call for new autokey values.
1184 	 *
1185 	 * In case of crypto error, fire the orchestra, stop dancing and
1186 	 * restart the protocol.
1187 	 */
1188 	if (peer->flags & FLAG_SKEY) {
1189 		/*
1190 		 * Decrement remaining audokey hashes. This isn't
1191 		 * perfect if a packet is lost, but results in no harm.
1192 		 */
1193 		ap = (struct autokey *)peer->recval.ptr;
1194 		if (ap != NULL) {
1195 			if (ap->seq > 0)
1196 				ap->seq--;
1197 		}
1198 		peer->flash |= TEST8;
1199 		rval = crypto_recv(peer, rbufp);
1200 		if (rval == XEVNT_OK) {
1201 			peer->unreach = 0;
1202 		} else {
1203 			if (rval == XEVNT_ERR) {
1204 				report_event(PEVNT_RESTART, peer,
1205 				    "crypto error");
1206 				peer_clear(peer, "CRYP");
1207 				peer->flash |= TEST9;	/* bad crypt */
1208 				if (peer->flags & FLAG_PREEMPT)
1209 					unpeer(peer);
1210 			}
1211 			return;
1212 		}
1213 
1214 		/*
1215 		 * If server mode, verify the receive key ID matches
1216 		 * the transmit key ID.
1217 		 */
1218 		if (hismode == MODE_SERVER) {
1219 			if (skeyid == peer->keyid)
1220 				peer->flash &= ~TEST8;
1221 
1222 		/*
1223 		 * If an extension field is present, verify only that it
1224 		 * has been correctly signed. We don't need a sequence
1225 		 * check here, but the sequence continues.
1226 		 */
1227 		} else if (!(peer->flash & TEST8)) {
1228 			peer->pkeyid = skeyid;
1229 
1230 		/*
1231 		 * Now the fun part. Here, skeyid is the current ID in
1232 		 * the packet, pkeyid is the ID in the last packet and
1233 		 * tkeyid is the hash of skeyid. If the autokey values
1234 		 * have not been received, this is an automatic error.
1235 		 * If so, check that the tkeyid matches pkeyid. If not,
1236 		 * hash tkeyid and try again. If the number of hashes
1237 		 * exceeds the number remaining in the sequence, declare
1238 		 * a successful failure and refresh the autokey values.
1239 		 */
1240 		} else if (ap != NULL) {
1241 			int i;
1242 
1243 			for (i = 0; ; i++) {
1244 				if (tkeyid == peer->pkeyid ||
1245 				    tkeyid == ap->key) {
1246 					peer->flash &= ~TEST8;
1247 					peer->pkeyid = skeyid;
1248 					ap->seq -= i;
1249 					break;
1250 				}
1251 				if (i > ap->seq) {
1252 					peer->crypto &=
1253 					    ~CRYPTO_FLAG_AUTO;
1254 					break;
1255 				}
1256 				tkeyid = session_key(
1257 				    &rbufp->recv_srcadr, dstadr_sin,
1258 				    tkeyid, pkeyid, 0);
1259 			}
1260 			if (peer->flash & TEST8)
1261 				report_event(PEVNT_AUTH, peer, "keylist");
1262 		}
1263 		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
1264 			peer->flash |= TEST8;	/* bad autokey */
1265 
1266 		/*
1267 		 * The maximum lifetime of the protocol is about one
1268 		 * week before restarting the Autokey protocol to
1269 		 * refreshed certificates and leapseconds values.
1270 		 */
1271 		if (current_time > peer->refresh) {
1272 			report_event(PEVNT_RESTART, peer,
1273 			    "crypto refresh");
1274 			peer_clear(peer, "TIME");
1275 			return;
1276 		}
1277 	}
1278 #endif /* OPENSSL */
1279 
1280 	/*
1281 	 * The dance is complete and the flash bits have been lit. Toss
1282 	 * the packet over the fence for processing, which may light up
1283 	 * more flashers.
1284 	 */
1285 	process_packet(peer, pkt, rbufp->recv_length);
1286 
1287 	/*
1288 	 * In interleaved mode update the state variables. Also adjust the
1289 	 * transmit phase to avoid crossover.
1290 	 */
1291 	if (peer->flip != 0) {
1292 		peer->rec = p_rec;
1293 		peer->dst = rbufp->recv_time;
1294 		if ((int)(peer->nextdate - current_time) < (1 << min(peer->ppoll,
1295 		    peer->hpoll)) / 2)
1296 			peer->nextdate++;
1297 		else
1298 			peer->nextdate--;
1299 	}
1300 }
1301 
1302 
1303 /*
1304  * process_packet - Packet Procedure, a la Section 3.4.4 of the
1305  *	specification. Or almost, at least. If we're in here we have a
1306  *	reasonable expectation that we will be having a long term
1307  *	relationship with this host.
1308  */
1309 void
1310 process_packet(
1311 	register struct peer *peer,
1312 	register struct pkt *pkt,
1313 	u_int	len
1314 	)
1315 {
1316 	double	t34, t21;
1317 	double	p_offset, p_del, p_disp;
1318 	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
1319 	u_char	pmode, pleap, pstratum;
1320 	char	statstr[NTP_MAXSTRLEN];
1321 #ifdef ASSYM
1322 	int	itemp;
1323 	double	etemp, ftemp, td;
1324 #endif /* ASSYM */
1325 
1326 	sys_processed++;
1327 	peer->processed++;
1328 	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1329 	p_offset = 0;
1330 	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
1331 	NTOHL_FP(&pkt->reftime, &p_reftime);
1332 	NTOHL_FP(&pkt->org, &p_org);
1333 	NTOHL_FP(&pkt->rec, &p_rec);
1334 	NTOHL_FP(&pkt->xmt, &p_xmt);
1335 	pmode = PKT_MODE(pkt->li_vn_mode);
1336 	pleap = PKT_LEAP(pkt->li_vn_mode);
1337 	pstratum = PKT_TO_STRATUM(pkt->stratum);
1338 
1339 	/*
1340 	 * Capture the header values in the client/peer association..
1341 	 */
1342 	record_raw_stats(&peer->srcadr, peer->dstadr ?
1343 	    &peer->dstadr->sin : NULL, &p_org, &p_rec, &p_xmt,
1344 	    &peer->dst);
1345 	peer->leap = pleap;
1346 	peer->stratum = min(pstratum, STRATUM_UNSPEC);
1347 	peer->pmode = pmode;
1348 	peer->precision = pkt->precision;
1349 	peer->rootdelay = p_del;
1350 	peer->rootdisp = p_disp;
1351 	peer->refid = pkt->refid;		/* network byte order */
1352 	peer->reftime = p_reftime;
1353 
1354 	/*
1355 	 * First, if either burst mode is armed, enable the burst.
1356 	 * Compute the headway for the next packet and delay if
1357 	 * necessary to avoid exceeding the threshold.
1358 	 */
1359 	if (peer->retry > 0) {
1360 		peer->retry = 0;
1361 		if (peer->reach)
1362 			peer->burst = min(1 << (peer->hpoll -
1363 			    peer->minpoll), NTP_SHIFT) - 1;
1364 		else
1365 			peer->burst = NTP_IBURST - 1;
1366 		if (peer->burst > 0)
1367 			peer->nextdate = current_time;
1368 	}
1369 	poll_update(peer, peer->hpoll);
1370 
1371 	/*
1372 	 * Verify the server is synchronized; that is, the leap bits,
1373 	 * stratum and root distance are valid.
1374 	 */
1375 	if (pleap == LEAP_NOTINSYNC ||		/* test 6 */
1376 	    pstratum < sys_floor || pstratum >= sys_ceiling)
1377 		peer->flash |= TEST6;		/* bad synch or strat */
1378 	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
1379 		peer->flash |= TEST7;		/* bad header */
1380 
1381 	/*
1382 	 * If any tests fail at this point, the packet is discarded.
1383 	 * Note that some flashers may have already been set in the
1384 	 * receive() routine.
1385 	 */
1386 	if (peer->flash & PKT_TEST_MASK) {
1387 		peer->seldisptoolarge++;
1388 #ifdef DEBUG
1389 		if (debug)
1390 			printf("packet: flash header %04x\n",
1391 			    peer->flash);
1392 #endif
1393 		return;
1394 	}
1395 
1396 	/*
1397 	 * If the peer was previously unreachable, raise a trap. In any
1398 	 * case, mark it reachable.
1399 	 */
1400 	if (!peer->reach) {
1401 		report_event(PEVNT_REACH, peer, NULL);
1402 		peer->timereachable = current_time;
1403 	}
1404 	peer->reach |= 1;
1405 
1406 	/*
1407 	 * For a client/server association, calculate the clock offset,
1408 	 * roundtrip delay and dispersion. The equations are reordered
1409 	 * from the spec for more efficient use of temporaries. For a
1410 	 * broadcast association, offset the last measurement by the
1411 	 * computed delay during the client/server volley. Note the
1412 	 * computation of dispersion includes the system precision plus
1413 	 * that due to the frequency error since the origin time.
1414 	 *
1415 	 * It is very important to respect the hazards of overflow. The
1416 	 * only permitted operation on raw timestamps is subtraction,
1417 	 * where the result is a signed quantity spanning from 68 years
1418 	 * in the past to 68 years in the future. To avoid loss of
1419 	 * precision, these calculations are done using 64-bit integer
1420 	 * arithmetic. However, the offset and delay calculations are
1421 	 * sums and differences of these first-order differences, which
1422 	 * if done using 64-bit integer arithmetic, would be valid over
1423 	 * only half that span. Since the typical first-order
1424 	 * differences are usually very small, they are converted to 64-
1425 	 * bit doubles and all remaining calculations done in floating-
1426 	 * double arithmetic. This preserves the accuracy while
1427 	 * retaining the 68-year span.
1428 	 *
1429 	 * There are three interleaving schemes, basic, interleaved
1430 	 * symmetric and interleaved broadcast. The timestamps are
1431 	 * idioscyncratically different. See the onwire briefing/white
1432 	 * paper at www.eecis.udel.edu/~mills for details.
1433 	 *
1434 	 * Interleaved symmetric mode
1435 	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
1436 	 * t4 = peer->dst
1437 	 */
1438 	if (peer->flip != 0) {
1439 		ci = p_xmt;				/* t3 - t4 */
1440 		L_SUB(&ci, &peer->dst);
1441 		LFPTOD(&ci, t34);
1442 		ci = p_rec;				/* t2 - t1 */
1443 		if (peer->flip > 0)
1444 			L_SUB(&ci, &peer->borg);
1445 		else
1446 			L_SUB(&ci, &peer->aorg);
1447 		LFPTOD(&ci, t21);
1448 		p_del = t21 - t34;
1449 		p_offset = (t21 + t34) / 2.;
1450 		if (p_del < 0 || p_del > 1.) {
1451 			sprintf(statstr, "t21 %.6f t34 %.6f", t21, t34);
1452 			report_event(PEVNT_XERR, peer, statstr);
1453 			return;
1454 		}
1455 
1456 	/*
1457 	 * Broadcast modes
1458 	 */
1459 	} else if (peer->pmode == MODE_BROADCAST) {
1460 
1461 		/*
1462 		 * Interleaved broadcast mode. Use interleaved timestamps.
1463 		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
1464 		 */
1465 		if (peer->flags & FLAG_XB) {
1466 			ci = p_org;			/* delay */
1467 			L_SUB(&ci, &peer->aorg);
1468 			LFPTOD(&ci, t34);
1469 			ci = p_org;			/* t2 - t1 */
1470 			L_SUB(&ci, &peer->borg);
1471 			LFPTOD(&ci, t21);
1472 			peer->aorg = p_xmt;
1473 			peer->borg = peer->dst;
1474 			if (t34 < 0 || t34 > 1.) {
1475 				sprintf(statstr,
1476 				    "offset %.6f delay %.6f", t21, t34);
1477 				report_event(PEVNT_XERR, peer, statstr);
1478 				return;
1479 			}
1480 			p_offset = t21;
1481 			peer->xleave = t34;
1482 
1483 		/*
1484 		 * Basic broadcast - use direct timestamps.
1485 		 * t3 = p_xmt, t4 = peer->dst
1486 		 */
1487 		} else {
1488 			ci = p_xmt;		/* t3 - t4 */
1489 			L_SUB(&ci, &peer->dst);
1490 			LFPTOD(&ci, t34);
1491 			p_offset = t34;
1492 		}
1493 
1494 		/*
1495 		 * When calibration is complete and the clock is
1496 		 * synchronized, the bias is calculated as the difference
1497 		 * between the unicast timestamp and the broadcast
1498 		 * timestamp. This works for both basic and interleaved
1499 		 * modes.
1500 		 */
1501 		if (peer->cast_flags & MDF_BCLNT) {
1502 			peer->cast_flags &= ~MDF_BCLNT;
1503 			peer->delay = (peer->offset - p_offset) * 2;
1504 		}
1505 		p_del = peer->delay;
1506 		p_offset += p_del / 2;
1507 
1508 
1509 	/*
1510 	 * Basic mode, otherwise known as the old fashioned way.
1511 	 *
1512 	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
1513 	 */
1514 	} else {
1515 		ci = p_xmt;				/* t3 - t4 */
1516 		L_SUB(&ci, &peer->dst);
1517 		LFPTOD(&ci, t34);
1518 		ci = p_rec;				/* t2 - t1 */
1519 		L_SUB(&ci, &p_org);
1520 		LFPTOD(&ci, t21);
1521 		p_del = fabs(t21 - t34);
1522 		p_offset = (t21 + t34) / 2.;
1523 	}
1524 	p_offset += peer->bias;
1525 	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
1526 	    clock_phi * p_del;
1527 
1528 #if ASSYM
1529 	/*
1530 	 * This code calculates the outbound and inbound data rates by
1531 	 * measuring the differences between timestamps at different
1532 	 * packet lengths. This is helpful in cases of large asymmetric
1533 	 * delays commonly experienced on deep space communication
1534 	 * links.
1535 	 */
1536 	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
1537 		itemp = peer->t21_bytes - peer->t21_last;
1538 		if (itemp > 25) {
1539 			etemp = t21 - peer->t21;
1540 			if (fabs(etemp) > 1e-6) {
1541 				ftemp = itemp / etemp;
1542 				if (ftemp > 1000.)
1543 					peer->r21 = ftemp;
1544 			}
1545 		}
1546 		itemp = len - peer->t34_bytes;
1547 		if (itemp > 25) {
1548 			etemp = -t34 - peer->t34;
1549 			if (fabs(etemp) > 1e-6) {
1550 				ftemp = itemp / etemp;
1551 				if (ftemp > 1000.)
1552 					peer->r34 = ftemp;
1553 			}
1554 		}
1555 	}
1556 
1557 	/*
1558 	 * The following section compensates for different data rates on
1559 	 * the outbound (d21) and inbound (t34) directions. To do this,
1560 	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
1561 	 * the roundtrip delay. Then it calculates the correction as a
1562 	 * fraction of d.
1563 	 */
1564  	peer->t21 = t21;
1565 	peer->t21_last = peer->t21_bytes;
1566 	peer->t34 = -t34;
1567 	peer->t34_bytes = len;
1568 #ifdef DEBUG
1569 	if (debug > 1)
1570 		printf("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
1571 		    peer->t21_bytes, peer->t34, peer->t34_bytes);
1572 #endif
1573 	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
1574 		if (peer->pmode != MODE_BROADCAST)
1575 			td = (peer->r34 / (peer->r21 + peer->r34) -
1576 			    .5) * p_del;
1577 		else
1578 			td = 0;
1579 
1580 		/*
1581  		 * Unfortunately, in many cases the errors are
1582 		 * unacceptable, so for the present the rates are not
1583 		 * used. In future, we might find conditions where the
1584 		 * calculations are useful, so this should be considered
1585 		 * a work in progress.
1586 		 */
1587 		t21 -= td;
1588 		t34 -= td;
1589 #ifdef DEBUG
1590 		if (debug > 1)
1591 			printf("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
1592 			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
1593 			    td);
1594 #endif
1595 	}
1596 #endif /* ASSYM */
1597 
1598 	/*
1599 	 * That was awesome. Now hand off to the clock filter.
1600 	 */
1601 	clock_filter(peer, p_offset, p_del, p_disp);
1602 
1603 	/*
1604 	 * If we are in broadcast calibrate mode, return to broadcast
1605 	 * client mode when the client is fit and the autokey dance is
1606 	 * complete.
1607 	 */
1608 	if ((peer->cast_flags & MDF_BCLNT) && !(peer_unfit(peer) &
1609 	    TEST11)) {
1610 #ifdef OPENSSL
1611 		if (peer->flags & FLAG_SKEY) {
1612 			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
1613 				peer->hmode = MODE_BCLIENT;
1614 		} else {
1615 			peer->hmode = MODE_BCLIENT;
1616 		}
1617 #else /* OPENSSL */
1618 		peer->hmode = MODE_BCLIENT;
1619 #endif /* OPENSSL */
1620 	}
1621 }
1622 
1623 
1624 /*
1625  * clock_update - Called at system process update intervals.
1626  */
1627 static void
1628 clock_update(
1629 	struct peer *peer	/* peer structure pointer */
1630 	)
1631 {
1632 	double	dtemp;
1633 	l_fp	now;
1634 #ifdef HAVE_LIBSCF_H
1635 	char	*fmri;
1636 #endif /* HAVE_LIBSCF_H */
1637 
1638 	/*
1639 	 * Update the system state variables. We do this very carefully,
1640 	 * as the poll interval might need to be clamped differently.
1641 	 */
1642 	sys_peer = peer;
1643 	sys_epoch = peer->epoch;
1644 	if (sys_poll < peer->minpoll)
1645 		sys_poll = peer->minpoll;
1646 	if (sys_poll > peer->maxpoll)
1647 		sys_poll = peer->maxpoll;
1648 	poll_update(peer, sys_poll);
1649 	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
1650 	if (peer->stratum == STRATUM_REFCLOCK ||
1651 	    peer->stratum == STRATUM_UNSPEC)
1652 		sys_refid = peer->refid;
1653 	else
1654 		sys_refid = addr2refid(&peer->srcadr);
1655 	dtemp = sys_jitter + fabs(sys_offset) + peer->disp + clock_phi *
1656 	    (current_time - peer->update);
1657 	sys_rootdisp = dtemp + peer->rootdisp;
1658 	sys_rootdelay = peer->delay + peer->rootdelay;
1659 	sys_reftime = peer->dst;
1660 
1661 #ifdef DEBUG
1662 	if (debug)
1663 		printf(
1664 		    "clock_update: at %lu sample %lu associd %d\n",
1665 		    current_time, peer->epoch, peer->associd);
1666 #endif
1667 
1668 	/*
1669 	 * Comes now the moment of truth. Crank the clock discipline and
1670 	 * see what comes out.
1671 	 */
1672 	switch (local_clock(peer, sys_offset)) {
1673 
1674 	/*
1675 	 * Clock exceeds panic threshold. Life as we know it ends.
1676 	 */
1677 	case -1:
1678 #ifdef HAVE_LIBSCF_H
1679 		/*
1680 		 * For Solaris enter the maintenance mode.
1681 		 */
1682 		if ((fmri = getenv("SMF_FMRI")) != NULL) {
1683 			if (smf_maintain_instance(fmri, 0) < 0) {
1684 				printf("smf_maintain_instance: %s\n",
1685 				    scf_strerror(scf_error()));
1686 				exit(1);
1687 			}
1688 			/*
1689 			 * Sleep until SMF kills us.
1690 			 */
1691 			for (;;)
1692 				pause();
1693 		}
1694 #endif /* HAVE_LIBSCF_H */
1695 		exit (-1);
1696 		/* not reached */
1697 
1698 	/*
1699 	 * Clock was stepped. Flush all time values of all peers.
1700 	 */
1701 	case 2:
1702 		clear_all();
1703 		sys_leap = LEAP_NOTINSYNC;
1704 		sys_stratum = STRATUM_UNSPEC;
1705 		memcpy(&sys_refid, "STEP", 4);
1706 		sys_rootdelay = 0;
1707 		sys_rootdisp = 0;
1708 		L_CLR(&sys_reftime);
1709 		sys_jitter = LOGTOD(sys_precision);
1710 		leapsec = 0;
1711 		break;
1712 
1713 	/*
1714 	 * Clock was slewed. Handle the leapsecond stuff.
1715 	 */
1716 	case 1:
1717 
1718 		/*
1719 		 * If this is the first time the clock is set, reset the
1720 		 * leap bits. If crypto, the timer will goose the setup
1721 		 * process.
1722 		 */
1723 		if (sys_leap == LEAP_NOTINSYNC) {
1724 			sys_leap = LEAP_NOWARNING;
1725 #ifdef OPENSSL
1726 			if (crypto_flags)
1727 				crypto_update();
1728 #endif /* OPENSSL */
1729 		}
1730 
1731 		/*
1732 		 * If the leapseconds values are from file or network
1733 		 * and the leap is in the future, schedule a leap at the
1734 		 * given epoch. Otherwise, if the number of survivor
1735 		 * leap bits is greater than half the number of
1736 		 * survivors, schedule a leap for the end of the current
1737 		 * month.
1738 		 */
1739 		get_systime(&now);
1740 		if (leap_sec > 0) {
1741 			if (leap_sec > now.l_ui) {
1742 				sys_tai = leap_tai - 1;
1743 				if (leapsec == 0)
1744 					report_event(EVNT_ARMED, NULL,
1745 					    NULL);
1746 				leapsec = leap_sec - now.l_ui;
1747 			} else {
1748 				sys_tai = leap_tai;
1749 			}
1750 			break;
1751 
1752 		} else if (leap_vote > sys_survivors / 2) {
1753 			leap_peers = now.l_ui + leap_month(now.l_ui);
1754 			if (leap_peers > now.l_ui) {
1755 				if (leapsec == 0)
1756 					report_event(PEVNT_ARMED, peer,
1757 					    NULL);
1758 				leapsec = leap_peers - now.l_ui;
1759 			}
1760 		} else if (leapsec > 0) {
1761 			report_event(EVNT_DISARMED, NULL, NULL);
1762 			leapsec = 0;
1763 		}
1764 		break;
1765 
1766 	/*
1767 	 * Popcorn spike or step threshold exceeded. Pretend it never
1768 	 * happened.
1769 	 */
1770 	default:
1771 		break;
1772 	}
1773 }
1774 
1775 
1776 /*
1777  * poll_update - update peer poll interval
1778  */
1779 void
1780 poll_update(
1781 	struct peer *peer,	/* peer structure pointer */
1782 	int	mpoll
1783 	)
1784 {
1785 	int	hpoll, minpkt;
1786 	u_long	next, utemp;
1787 
1788 	/*
1789 	 * This routine figures out when the next poll should be sent.
1790 	 * That turns out to be wickedly complicated. One problem is
1791 	 * that sometimes the time for the next poll is in the past when
1792 	 * the poll interval is reduced. We watch out for races here
1793 	 * between the receive process and the poll process.
1794 	 *
1795 	 * First, bracket the poll interval according to the type of
1796 	 * association and options. If a fixed interval is configured,
1797 	 * use minpoll. This primarily is for reference clocks, but
1798 	 * works for any association. Otherwise, clamp the poll interval
1799 	 * between minpoll and maxpoll.
1800 	 */
1801 	if (peer->cast_flags & MDF_BCLNT)
1802 		hpoll = peer->minpoll;
1803 	else
1804 		hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
1805 
1806 #ifdef OPENSSL
1807 	/*
1808 	 * If during the crypto protocol the poll interval has changed,
1809 	 * the lifetimes in the key list are probably bogus. Purge the
1810 	 * the key list and regenerate it later.
1811 	 */
1812 	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
1813 		key_expire(peer);
1814 #endif /* OPENSSL */
1815 	peer->hpoll = hpoll;
1816 
1817 	/*
1818 	 * There are three variables important for poll scheduling, the
1819 	 * current time (current_time), next scheduled time (nextdate)
1820 	 * and the earliest time (utemp). The earliest time is 2 s
1821 	 * seconds, but could be more due to rate management. When
1822 	 * sending in a burst, use the earliest time. When not in a
1823 	 * burst but with a reply pending, send at the earliest time
1824 	 * unless the next scheduled time has not advanced. This can
1825 	 * only happen if multiple replies are peinding in the same
1826 	 * response interval. Otherwise, send at the later of the next
1827 	 * scheduled time and the earliest time.
1828 	 *
1829 	 * Now we figure out if there is an override. If a burst is in
1830 	 * progress and we get called from the receive process, just
1831 	 * slink away. If called from the poll process, delay 1 s for a
1832 	 * reference clock, otherwise 2 s.
1833 	 */
1834 	minpkt = 1 << ntp_minpkt;
1835 	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
1836 	    (1 << peer->minpoll), minpkt);
1837 	if (peer->burst > 0) {
1838 		if (peer->nextdate > current_time)
1839 			return;
1840 #ifdef REFCLOCK
1841 		else if (peer->flags & FLAG_REFCLOCK)
1842 			peer->nextdate = current_time + RESP_DELAY;
1843 #endif /* REFCLOCK */
1844 		else
1845 			peer->nextdate = utemp;
1846 
1847 #ifdef OPENSSL
1848 	/*
1849 	 * If a burst is not in progress and a crypto response message
1850 	 * is pending, delay 2 s, but only if this is a new interval.
1851 	 */
1852 	} else if (peer->cmmd != NULL) {
1853 		if (peer->nextdate > current_time) {
1854 			if (peer->nextdate + minpkt != utemp)
1855 				peer->nextdate = utemp;
1856 		} else {
1857 			peer->nextdate = utemp;
1858 		}
1859 #endif /* OPENSSL */
1860 
1861 	/*
1862 	 * The ordinary case. If a retry, use minpoll; if unreachable,
1863 	 * use host poll; otherwise, use the minimum of host and peer
1864 	 * polls; In other words, oversampling is okay but
1865 	 * understampling is evil. Use the maximum of this value and the
1866 	 * headway. If the average headway is greater than the headway
1867 	 * threshold, increase the headway by the minimum interval.
1868 	 */
1869 	} else {
1870 		if (peer->retry > 0)
1871 			hpoll = peer->minpoll;
1872 		else if (!(peer->reach))
1873 			hpoll = peer->hpoll;
1874 		else
1875 			hpoll = min(peer->ppoll, peer->hpoll);
1876 #ifdef REFCLOCK
1877 		if (peer->flags & FLAG_REFCLOCK)
1878 			next = 1 << hpoll;
1879 		else
1880 			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
1881 			    hpoll) >> 12;
1882 #else /* REFCLOCK */
1883 		next = ((0x1000UL | (ntp_random() & 0x0ff)) << hpoll) >>
1884 		    12;
1885 #endif /* REFCLOCK */
1886 		next += peer->outdate;
1887 		if (next > utemp)
1888 			peer->nextdate = next;
1889 		else
1890 			peer->nextdate = utemp;
1891 		hpoll = peer->throttle - (1 << peer->minpoll);
1892 		if (hpoll > 0)
1893 			peer->nextdate += minpkt;
1894 	}
1895 #ifdef DEBUG
1896 	if (debug > 1)
1897 		printf("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
1898 		    current_time, ntoa(&peer->srcadr), peer->hpoll,
1899 		    peer->burst, peer->retry, peer->throttle,
1900 		    utemp - current_time, peer->nextdate -
1901 		    current_time);
1902 #endif
1903 }
1904 
1905 
1906 /*
1907  * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
1908  * spec.
1909  */
1910 void
1911 peer_clear(
1912 	struct peer *peer,		/* peer structure */
1913 	const char *ident		/* tally lights */
1914 	)
1915 {
1916 	int	i;
1917 
1918 #ifdef OPENSSL
1919 	/*
1920 	 * If cryptographic credentials have been acquired, toss them to
1921 	 * Valhalla. Note that autokeys are ephemeral, in that they are
1922 	 * tossed immediately upon use. Therefore, the keylist can be
1923 	 * purged anytime without needing to preserve random keys. Note
1924 	 * that, if the peer is purged, the cryptographic variables are
1925 	 * purged, too. This makes it much harder to sneak in some
1926 	 * unauthenticated data in the clock filter.
1927 	 */
1928 	key_expire(peer);
1929 	if (peer->iffval != NULL)
1930 		BN_free(peer->iffval);
1931 	value_free(&peer->cookval);
1932 	value_free(&peer->recval);
1933 	value_free(&peer->encrypt);
1934 	value_free(&peer->sndval);
1935 	if (peer->cmmd != NULL)
1936 		free(peer->cmmd);
1937 	if (peer->subject != NULL)
1938 		free(peer->subject);
1939 	if (peer->issuer != NULL)
1940 		free(peer->issuer);
1941 #endif /* OPENSSL */
1942 
1943 	/*
1944 	 * Clear all values, including the optional crypto values above.
1945 	 */
1946 	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1947 	peer->ppoll = peer->maxpoll;
1948 	peer->hpoll = peer->minpoll;
1949 	peer->disp = MAXDISPERSE;
1950 	peer->flash = peer_unfit(peer);
1951 	peer->jitter = LOGTOD(sys_precision);
1952 
1953 	/*
1954 	 * If interleave mode, initialize the alternate origin switch.
1955 	 */
1956 	if (peer->flags & FLAG_XLEAVE)
1957 		peer->flip = 1;
1958 	for (i = 0; i < NTP_SHIFT; i++) {
1959 		peer->filter_order[i] = i;
1960 		peer->filter_disp[i] = MAXDISPERSE;
1961 	}
1962 #ifdef REFCLOCK
1963 	if (!(peer->flags & FLAG_REFCLOCK)) {
1964 		peer->leap = LEAP_NOTINSYNC;
1965 		peer->stratum = STRATUM_UNSPEC;
1966 		memcpy(&peer->refid, ident, 4);
1967 	}
1968 #else
1969 	peer->leap = LEAP_NOTINSYNC;
1970 	peer->stratum = STRATUM_UNSPEC;
1971 	memcpy(&peer->refid, ident, 4);
1972 #endif /* REFCLOCK */
1973 
1974 	/*
1975 	 * During initialization use the association count to spread out
1976 	 * the polls at one-second intervals. Otherwise, randomize over
1977 	 * the minimum poll interval in order to avoid broadcast
1978 	 * implosion.
1979 	 */
1980 	peer->nextdate = peer->update = peer->outdate = current_time;
1981 	if (initializing) {
1982 		peer->nextdate += peer_associations;
1983 	} else if (peer->hmode == MODE_PASSIVE) {
1984 		peer->nextdate += 1 << ntp_minpkt;
1985 	} else {
1986 		peer->nextdate += ntp_random() % peer_associations;
1987 	}
1988 #ifdef OPENSSL
1989 	peer->refresh = current_time + (1 << NTP_REFRESH);
1990 #endif /* OPENSSL */
1991 #ifdef DEBUG
1992 	if (debug)
1993 		printf(
1994 		    "peer_clear: at %ld next %ld associd %d refid %s\n",
1995 		    current_time, peer->nextdate, peer->associd,
1996 		    ident);
1997 #endif
1998 }
1999 
2000 
2001 /*
2002  * clock_filter - add incoming clock sample to filter register and run
2003  *		  the filter procedure to find the best sample.
2004  */
2005 void
2006 clock_filter(
2007 	struct peer *peer,		/* peer structure pointer */
2008 	double	sample_offset,		/* clock offset */
2009 	double	sample_delay,		/* roundtrip delay */
2010 	double	sample_disp		/* dispersion */
2011 	)
2012 {
2013 	double	dst[NTP_SHIFT];		/* distance vector */
2014 	int	ord[NTP_SHIFT];		/* index vector */
2015 	int	i, j, k, m;
2016 	double	dtemp, etemp;
2017 	char	tbuf[80];
2018 
2019 	/*
2020 	 * A sample consists of the offset, delay, dispersion and epoch
2021 	 * of arrival. The offset and delay are determined by the on-
2022 	 * wire protcol. The dispersion grows from the last outbound
2023 	 * packet to the arrival of this one increased by the sum of the
2024 	 * peer precision and the system precision as required by the
2025 	 * error budget. First, shift the new arrival into the shift
2026 	 * register discarding the oldest one.
2027 	 */
2028 	j = peer->filter_nextpt;
2029 	peer->filter_offset[j] = sample_offset;
2030 	peer->filter_delay[j] = sample_delay;
2031 	peer->filter_disp[j] = sample_disp;
2032 	peer->filter_epoch[j] = current_time;
2033 	j = (j + 1) % NTP_SHIFT;
2034 	peer->filter_nextpt = j;
2035 
2036 	/*
2037 	 * Update dispersions since the last update and at the same
2038 	 * time initialize the distance and index lists. Since samples
2039 	 * become increasingly uncorrelated beyond the Allan intercept,
2040 	 * only under exceptional cases will an older sample be used.
2041 	 * Therefore, the distance list uses a compound metric. If the
2042 	 * dispersion is greater than the maximum dispersion, clamp the
2043 	 * distance at that value. If the time since the last update is
2044 	 * less than the Allan intercept use the delay; otherwise, use
2045 	 * the sum of the delay and dispersion.
2046 	 */
2047 	dtemp = clock_phi * (current_time - peer->update);
2048 	peer->update = current_time;
2049 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
2050 		if (i != 0)
2051 			peer->filter_disp[j] += dtemp;
2052 		if (peer->filter_disp[j] >= MAXDISPERSE) {
2053 			peer->filter_disp[j] = MAXDISPERSE;
2054 			dst[i] = MAXDISPERSE;
2055 		} else if ((int)(peer->update - peer->filter_epoch[j]) >
2056 		    ULOGTOD(allan_xpt)) {
2057 			dst[i] = peer->filter_delay[j] +
2058 			    peer->filter_disp[j];
2059 		} else {
2060 			dst[i] = peer->filter_delay[j];
2061 		}
2062 		ord[i] = j;
2063 		j = (j + 1) % NTP_SHIFT;
2064 	}
2065 
2066         /*
2067 	 * If the clock discipline has stabilized, sort the samples by
2068 	 * distance.
2069 	 */
2070 	if (sys_leap != LEAP_NOTINSYNC) {
2071 		for (i = 1; i < NTP_SHIFT; i++) {
2072 			for (j = 0; j < i; j++) {
2073 				if (dst[j] > dst[i]) {
2074 					k = ord[j];
2075 					ord[j] = ord[i];
2076 					ord[i] = k;
2077 					etemp = dst[j];
2078 					dst[j] = dst[i];
2079 					dst[i] = etemp;
2080 				}
2081 			}
2082 		}
2083 	}
2084 
2085 	/*
2086 	 * Copy the index list to the association structure so ntpq
2087 	 * can see it later. Prune the distance list to leave only
2088 	 * samples less than the maximum dispersion, which disfavors
2089 	 * uncorrelated samples older than the Allan intercept. To
2090 	 * further improve the jitter estimate, of the remainder leave
2091 	 * only samples less than the maximum distance, but keep at
2092 	 * least two samples for jitter calculation.
2093 	 */
2094 	m = 0;
2095 	for (i = 0; i < NTP_SHIFT; i++) {
2096 		peer->filter_order[i] = (u_char) ord[i];
2097 		if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
2098 		    sys_maxdist))
2099 			continue;
2100 		m++;
2101 	}
2102 
2103 	/*
2104 	 * Compute the dispersion and jitter. The dispersion is weighted
2105 	 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2106 	 * to 1.0. The jitter is the RMS differences relative to the
2107 	 * lowest delay sample.
2108 	 */
2109 	peer->disp = peer->jitter = 0;
2110 	k = ord[0];
2111 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
2112 		j = ord[i];
2113 		peer->disp = NTP_FWEIGHT * (peer->disp +
2114 		    peer->filter_disp[j]);
2115 		if (i < m)
2116 			peer->jitter += DIFF(peer->filter_offset[j],
2117 			    peer->filter_offset[k]);
2118 	}
2119 
2120 	/*
2121 	 * If no acceptable samples remain in the shift register,
2122 	 * quietly tiptoe home leaving only the dispersion. Otherwise,
2123 	 * save the offset, delay and jitter. Note the jitter must not
2124 	 * be less than the precision.
2125 	 */
2126 	if (m == 0)
2127 		return;
2128 
2129 	etemp = fabs(peer->offset - peer->filter_offset[k]);
2130 	peer->offset = peer->filter_offset[k];
2131 	peer->delay = peer->filter_delay[k];
2132 	if (m > 1)
2133 		peer->jitter /= m - 1;
2134 	peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
2135 
2136 	/*
2137 	 * If the the new sample and the current sample are both valid
2138 	 * and the difference between their offsets exceeds CLOCK_SGATE
2139 	 * (3) times the jitter and the interval between them is less
2140 	 * than twice the host poll interval, consider the new sample
2141 	 * a popcorn spike and ignore it.
2142 	 */
2143 	if (peer->disp < sys_maxdist && peer->filter_disp[k] <
2144 	    sys_maxdist && etemp > CLOCK_SGATE * peer->jitter &&
2145 	    peer->filter_epoch[k] - peer->epoch < 2. *
2146 	    ULOGTOD(peer->hpoll)) {
2147 		snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
2148 		report_event(PEVNT_POPCORN, peer, tbuf);
2149 		return;
2150 	}
2151 
2152 	/*
2153 	 * A new minimum sample is useful only if it is later than the
2154 	 * last one used. In this design the maximum lifetime of any
2155 	 * sample is not greater than eight times the poll interval, so
2156 	 * the maximum interval between minimum samples is eight
2157 	 * packets.
2158 	 */
2159 	if (peer->filter_epoch[k] <= peer->epoch) {
2160 #if DEBUG
2161 	if (debug)
2162 		printf("clock_filter: old sample %lu\n", current_time -
2163 		    peer->filter_epoch[k]);
2164 #endif
2165 		return;
2166 	}
2167 	peer->epoch = peer->filter_epoch[k];
2168 
2169 	/*
2170 	 * The mitigated sample statistics are saved for later
2171 	 * processing. If not synchronized or not in a burst, tickle the
2172 	 * clock select algorithm.
2173 	 */
2174 	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
2175 	    peer->offset, peer->delay, peer->disp, peer->jitter);
2176 #ifdef DEBUG
2177 	if (debug)
2178 		printf(
2179 		    "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
2180 		    m, peer->offset, peer->delay, peer->disp,
2181 		    peer->jitter);
2182 #endif
2183 	if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
2184 		clock_select();
2185 }
2186 
2187 
2188 /*
2189  * clock_select - find the pick-of-the-litter clock
2190  *
2191  * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
2192  * be enabled, even if declared falseticker, (2) only the prefer peer
2193  * caN Be selected as the system peer, (3) if the external source is
2194  * down, the system leap bits are set to 11 and the stratum set to
2195  * infinity.
2196  */
2197 void
2198 clock_select(void)
2199 {
2200 	struct peer *peer;
2201 	int	i, j, k, n;
2202 	int	nlist, nl3;
2203 	int	allow, osurv;
2204 	double	d, e, f, g;
2205 	double	high, low;
2206 	double	seljitter;
2207 	double	synch[NTP_MAXASSOC], error[NTP_MAXASSOC];
2208 	double	orphdist = 1e10;
2209 	struct peer *osys_peer = NULL;
2210 	struct peer *sys_prefer = NULL;	/* prefer peer */
2211 	struct peer *typesystem = NULL;
2212 	struct peer *typeorphan = NULL;
2213 #ifdef REFCLOCK
2214 	struct peer *typeacts = NULL;
2215 	struct peer *typelocal = NULL;
2216 	struct peer *typepps = NULL;
2217 #endif /* REFCLOCK */
2218 
2219 	static int list_alloc = 0;
2220 	static struct endpoint *endpoint = NULL;
2221 	static int *indx = NULL;
2222 	static struct peer **peer_list = NULL;
2223 	static u_int endpoint_size = 0;
2224 	static u_int indx_size = 0;
2225 	static u_int peer_list_size = 0;
2226 
2227 	/*
2228 	 * Initialize and create endpoint, index and peer lists big
2229 	 * enough to handle all associations.
2230 	 */
2231 	osys_peer = sys_peer;
2232 	osurv = sys_survivors;
2233 	sys_survivors = 0;
2234 #ifdef LOCKCLOCK
2235 	sys_leap = LEAP_NOTINSYNC;
2236 	sys_stratum = STRATUM_UNSPEC;
2237 	memcpy(&sys_refid, "DOWN", 4);
2238 #endif /* LOCKCLOCK */
2239 	nlist = 0;
2240 	for (n = 0; n < NTP_HASH_SIZE; n++)
2241 		nlist += peer_hash_count[n];
2242 	if (nlist > list_alloc) {
2243 		if (list_alloc > 0) {
2244 			free(endpoint);
2245 			free(indx);
2246 			free(peer_list);
2247 		}
2248 		while (list_alloc < nlist) {
2249 			list_alloc += 5;
2250 			endpoint_size += 5 * 3 * sizeof(*endpoint);
2251 			indx_size += 5 * 3 * sizeof(*indx);
2252 			peer_list_size += 5 * sizeof(*peer_list);
2253 		}
2254 		endpoint = (struct endpoint *)emalloc(endpoint_size);
2255 		indx = (int *)emalloc(indx_size);
2256 		peer_list = (struct peer **)emalloc(peer_list_size);
2257 	}
2258 
2259 	/*
2260 	 * Initially, we populate the island with all the rifraff peers
2261 	 * that happen to be lying around. Those with seriously
2262 	 * defective clocks are immediately booted off the island. Then,
2263 	 * the falsetickers are culled and put to sea. The truechimers
2264 	 * remaining are subject to repeated rounds where the most
2265 	 * unpopular at each round is kicked off. When the population
2266 	 * has dwindled to sys_minclock, the survivors split a million
2267 	 * bucks and collectively crank the chimes.
2268 	 */
2269 	nlist = nl3 = 0;	/* none yet */
2270 	for (n = 0; n < NTP_HASH_SIZE; n++) {
2271 		for (peer = peer_hash[n]; peer != NULL; peer =
2272 		    peer->next) {
2273 			peer->flags &= ~FLAG_SYSPEER;
2274 			peer->status = CTL_PST_SEL_REJECT;
2275 
2276 			/*
2277 			 * Leave the island immediately if the peer is
2278 			 * unfit to synchronize.
2279 			 */
2280 			if (peer_unfit(peer))
2281 				continue;
2282 
2283 			/*
2284 			 * If this is an orphan, choose the one with
2285 			 * the lowest metric defined as the IPv4 address
2286 			 * or the first 64 bits of the hashed IPv6 address.
2287 			 */
2288 			if (peer->stratum == sys_orphan) {
2289 				double	ftemp;
2290 
2291 				ftemp = addr2refid(&peer->srcadr);
2292 				if (ftemp < orphdist) {
2293 					typeorphan = peer;
2294 					orphdist = ftemp;
2295 				}
2296 				continue;
2297 			}
2298 #ifdef REFCLOCK
2299 			/*
2300 			 * The following are special cases. We deal
2301 			 * with them later.
2302 			 */
2303 			switch (peer->refclktype) {
2304 			case REFCLK_LOCALCLOCK:
2305 				if (typelocal == NULL &&
2306 				    !(peer->flags & FLAG_PREFER))
2307 					typelocal = peer;
2308 				continue;
2309 
2310 			case REFCLK_ACTS:
2311 				if (typeacts == NULL &&
2312 				    !(peer->flags & FLAG_PREFER))
2313 					typeacts = peer;
2314 				continue;
2315 			}
2316 #endif /* REFCLOCK */
2317 
2318 			/*
2319 			 * If we get this far, the peer can stay on the
2320 			 * island, but does not yet have the immunity
2321 			 * idol.
2322 			 */
2323 			peer->status = CTL_PST_SEL_SANE;
2324 			peer_list[nlist++] = peer;
2325 
2326 			/*
2327 			 * Insert each interval endpoint on the sorted
2328 			 * list.
2329 			 */
2330 			e = peer->offset;	 /* Upper end */
2331 			f = root_distance(peer);
2332 			e = e + f;
2333 			for (i = nl3 - 1; i >= 0; i--) {
2334 				if (e >= endpoint[indx[i]].val)
2335 					break;
2336 
2337 				indx[i + 3] = indx[i];
2338 			}
2339 			indx[i + 3] = nl3;
2340 			endpoint[nl3].type = 1;
2341 			endpoint[nl3++].val = e;
2342 
2343 			e = e - f;		/* Center point */
2344 			for (; i >= 0; i--) {
2345 				if (e >= endpoint[indx[i]].val)
2346 					break;
2347 
2348 				indx[i + 2] = indx[i];
2349 			}
2350 			indx[i + 2] = nl3;
2351 			endpoint[nl3].type = 0;
2352 			endpoint[nl3++].val = e;
2353 
2354 			e = e - f;		/* Lower end */
2355 			for (; i >= 0; i--) {
2356 				if (e >= endpoint[indx[i]].val)
2357 					break;
2358 
2359 				indx[i + 1] = indx[i];
2360 			}
2361 			indx[i + 1] = nl3;
2362 			endpoint[nl3].type = -1;
2363 			endpoint[nl3++].val = e;
2364 		}
2365 	}
2366 #ifdef DEBUG
2367 	if (debug > 2)
2368 		for (i = 0; i < nl3; i++)
2369 			printf("select: endpoint %2d %.6f\n",
2370 			   endpoint[indx[i]].type,
2371 			   endpoint[indx[i]].val);
2372 #endif
2373 	/*
2374 	 * This is the actual algorithm that cleaves the truechimers
2375 	 * from the falsetickers. The original algorithm was described
2376 	 * in Keith Marzullo's dissertation, but has been modified for
2377 	 * better accuracy.
2378 	 *
2379 	 * Briefly put, we first assume there are no falsetickers, then
2380 	 * scan the candidate list first from the low end upwards and
2381 	 * then from the high end downwards. The scans stop when the
2382 	 * number of intersections equals the number of candidates less
2383 	 * the number of falsetickers. If this doesn't happen for a
2384 	 * given number of falsetickers, we bump the number of
2385 	 * falsetickers and try again. If the number of falsetickers
2386 	 * becomes equal to or greater than half the number of
2387 	 * candidates, the Albanians have won the Byzantine wars and
2388 	 * correct synchronization is not possible.
2389 	 *
2390 	 * Here, nlist is the number of candidates and allow is the
2391 	 * number of falsetickers. Upon exit, the truechimers are the
2392 	 * susvivors with offsets not less than low and not greater than
2393 	 * high. There may be none of them.
2394 	 */
2395 	low = 1e9;
2396 	high = -1e9;
2397 	for (allow = 0; 2 * allow < nlist; allow++) {
2398 		int	found;
2399 
2400 		/*
2401 		 * Bound the interval (low, high) as the largest
2402 		 * interval containing points from presumed truechimers.
2403 		 */
2404 		found = 0;
2405 		n = 0;
2406 		for (i = 0; i < nl3; i++) {
2407 			low = endpoint[indx[i]].val;
2408 			n -= endpoint[indx[i]].type;
2409 			if (n >= nlist - allow)
2410 				break;
2411 			if (endpoint[indx[i]].type == 0)
2412 				found++;
2413 		}
2414 		n = 0;
2415 		for (j = nl3 - 1; j >= 0; j--) {
2416 			high = endpoint[indx[j]].val;
2417 			n += endpoint[indx[j]].type;
2418 			if (n >= nlist - allow)
2419 				break;
2420 			if (endpoint[indx[j]].type == 0)
2421 				found++;
2422 		}
2423 
2424 		/*
2425 		 * If the number of candidates found outside the
2426 		 * interval is greater than the number of falsetickers,
2427 		 * then at least one truechimer is outside the interval,
2428 		 * so go around again. This is what makes this algorithm
2429 		 * different than Marzullo's.
2430 		 */
2431 		if (found > allow)
2432 			continue;
2433 
2434 		/*
2435 		 * If an interval containing truechimers is found, stop.
2436 		 * If not, increase the number of falsetickers and go
2437 		 * around again.
2438 		 */
2439 		if (high > low)
2440 			break;
2441 	}
2442 
2443 	/*
2444 	 * Clustering algorithm. Construct candidate list in order first
2445 	 * by stratum then by root distance, but keep only the best
2446 	 * NTP_MAXASSOC of them. Scan the list to find falsetickers, who
2447 	 * leave the island immediately. The TRUE peer is always a
2448 	 * truechimer. We must leave at least one peer to collect the
2449 	 * million bucks.
2450 	 */
2451 	j = 0;
2452 	for (i = 0; i < nlist; i++) {
2453 		peer = peer_list[i];
2454 		if (nlist > 1 && (peer->offset <= low || peer->offset >=
2455 		    high) && !(peer->flags & FLAG_TRUE))
2456 			continue;
2457 
2458 #ifdef REFCLOCK
2459 		/*
2460 		 * Elegible PPS peers must survive the intersection
2461 		 * algorithm. Use the first one found, but don't
2462 		 * include any of them in the cluster population.
2463 		 */
2464 		if (peer->flags & FLAG_PPS) {
2465 			if (typepps == NULL)
2466 				typepps = peer;
2467 			continue;
2468 		}
2469 #endif /* REFCLOCK */
2470 
2471 		/*
2472 		 * The metric is the scaled root distance at the next
2473 		 * poll interval plus the peer stratum.
2474 		 */
2475 		d = (root_distance(peer) + clock_phi * (peer->nextdate -
2476 		    current_time)) / sys_maxdist + peer->stratum;
2477 		if (j >= NTP_MAXASSOC) {
2478 			if (d >= synch[j - 1])
2479 				continue;
2480 			else
2481 				j--;
2482 		}
2483 		for (k = j; k > 0; k--) {
2484 			if (d >= synch[k - 1])
2485 				break;
2486 
2487 			peer_list[k] = peer_list[k - 1];
2488 			error[k] = error[k - 1];
2489 			synch[k] = synch[k - 1];
2490 		}
2491 		peer_list[k] = peer;
2492 		error[k] = peer->jitter;
2493 		synch[k] = d;
2494 		j++;
2495 	}
2496 	nlist = j;
2497 
2498 	/*
2499 	 * If no survivors remain at this point, check if the modem
2500 	 * driver, local driver or orphan parent in that order. If so,
2501 	 * nominate the first one found as the only survivor.
2502 	 * Otherwise, give up and leave the island to the rats.
2503 	 */
2504 	if (nlist == 0) {
2505 		error[0] = 0;
2506 		synch[0] = 0;
2507 #ifdef REFCLOCK
2508 		if (typeacts != NULL) {
2509 			peer_list[0] = typeacts;
2510 			nlist = 1;
2511 		} else if (typelocal != NULL) {
2512 			peer_list[0] = typelocal;
2513 			nlist = 1;
2514 		}
2515 #endif /* REFCLOCK */
2516 		if (typeorphan != NULL) {
2517 			peer_list[0] = typeorphan;
2518 			nlist = 1;
2519 		}
2520 	}
2521 
2522 	/*
2523 	 * Mark the candidates at this point as truechimers.
2524 	 */
2525 	for (i = 0; i < nlist; i++) {
2526 		peer_list[i]->status = CTL_PST_SEL_SELCAND;
2527 #ifdef DEBUG
2528 		if (debug > 1)
2529 			printf("select: survivor %s %f\n",
2530 			    stoa(&peer_list[i]->srcadr), synch[i]);
2531 #endif
2532 	}
2533 
2534 	/*
2535 	 * Now, vote outlyers off the island by select jitter weighted
2536 	 * by root distance. Continue voting as long as there are more
2537 	 * than sys_minclock survivors and the minimum select jitter is
2538 	 * greater than the maximum peer jitter. Stop if we are about to
2539 	 * discard a TRUE or PREFER  peer, who of course has the
2540 	 * immunity idol.
2541 	 */
2542 	seljitter = 0;
2543 	while (1) {
2544 		d = 1e9;
2545 		e = -1e9;
2546 		f = g = 0;
2547 		k = 0;
2548 		for (i = 0; i < nlist; i++) {
2549 			if (error[i] < d)
2550 				d = error[i];
2551 			f = 0;
2552 			if (nlist > 1) {
2553 				for (j = 0; j < nlist; j++)
2554 					f += DIFF(peer_list[j]->offset,
2555 					    peer_list[i]->offset);
2556 				f = SQRT(f / (nlist - 1));
2557 			}
2558 			if (f * synch[i] > e) {
2559 				g = f;
2560 				e = f * synch[i];
2561 				k = i;
2562 			}
2563 		}
2564 		f = max(f, LOGTOD(sys_precision));
2565 		if (nlist <= sys_minsane || nlist <= sys_minclock) {
2566 			break;
2567 
2568 		} else if (f <= d || peer_list[k]->flags &
2569 		    (FLAG_TRUE | FLAG_PREFER)) {
2570 			seljitter = f;
2571 			break;
2572 		}
2573 #ifdef DEBUG
2574 		if (debug > 2)
2575 			printf(
2576 			    "select: drop %s seljit %.6f jit %.6f\n",
2577 			    ntoa(&peer_list[k]->srcadr), g, d);
2578 #endif
2579 		if (nlist > sys_maxclock)
2580 			peer_list[k]->status = CTL_PST_SEL_EXCESS;
2581 		for (j = k + 1; j < nlist; j++) {
2582 			peer_list[j - 1] = peer_list[j];
2583 			synch[j - 1] = synch[j];
2584 			error[j - 1] = error[j];
2585 		}
2586 		nlist--;
2587 	}
2588 
2589 	/*
2590 	 * What remains is a list usually not greater than sys_minclock
2591 	 * peers. Note that the head of the list is the system peer at
2592 	 * the lowest stratum and that unsynchronized peers cannot
2593 	 * survive this far.
2594 	 *
2595 	 * While at it, count the number of leap warning bits found.
2596 	 * This will be used later to vote the system leap warning bit.
2597 	 * If a leap warning bit is found on a reference clock, the vote
2598 	 * is always won.
2599 	 */
2600 	leap_vote = 0;
2601 	for (i = 0; i < nlist; i++) {
2602 		peer = peer_list[i];
2603 		peer->unreach = 0;
2604 		peer->status = CTL_PST_SEL_SYNCCAND;
2605 		sys_survivors++;
2606 		if (peer->leap == LEAP_ADDSECOND) {
2607 			if (peer->flags & FLAG_REFCLOCK)
2608 				leap_vote = nlist;
2609 			else
2610 				leap_vote++;
2611 		}
2612 		if (peer->flags & FLAG_PREFER)
2613 			sys_prefer = peer;
2614 	}
2615 
2616 	/*
2617 	 * Unless there are at least sys_misane survivors, leave the
2618 	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
2619 	 * use the first survivor on the survivor list. However, if the
2620 	 * last selection is not first on the list, use it as long as
2621 	 * it doesn't get too old or too ugly.
2622 	 */
2623 	if (nlist > 0 && nlist >= sys_minsane) {
2624 		double	x;
2625 
2626 		typesystem = peer_list[0];
2627 		if (osys_peer == NULL || osys_peer == typesystem) {
2628 			sys_clockhop = 0;
2629 		} else if ((x = fabs(typesystem->offset -
2630 		    osys_peer->offset)) < sys_mindisp) {
2631 			if (sys_clockhop == 0)
2632 				sys_clockhop = sys_mindisp;
2633 			else
2634 				sys_clockhop *= .5;
2635 #ifdef DEBUG
2636 			if (debug)
2637 				printf("select: clockhop %d %.6f %.6f\n",
2638 				    j, x, sys_clockhop);
2639 #endif
2640 			if (fabs(x) < sys_clockhop)
2641 				typesystem = osys_peer;
2642 			else
2643 				sys_clockhop = 0;
2644 		} else {
2645 			sys_clockhop = 0;
2646 		}
2647 	}
2648 
2649 	/*
2650 	 * Mitigation rules of the game. We have the pick of the
2651 	 * litter in typesystem if any survivors are left. If
2652 	 * there is a prefer peer, use its offset and jitter.
2653 	 * Otherwise, use the combined offset and jitter of all kitters.
2654 	 */
2655 	if (typesystem != NULL) {
2656 		if (sys_prefer == NULL) {
2657 			typesystem->status = CTL_PST_SEL_SYSPEER;
2658 			clock_combine(peer_list, sys_survivors);
2659 			sys_jitter = SQRT(SQUARE(typesystem->jitter) +
2660 			    SQUARE(sys_jitter) + SQUARE(seljitter));
2661 		} else {
2662 			typesystem = sys_prefer;
2663 			sys_clockhop = 0;
2664 			typesystem->status = CTL_PST_SEL_SYSPEER;
2665 			sys_offset = typesystem->offset;
2666 			sys_jitter = typesystem->jitter;
2667 		}
2668 #ifdef DEBUG
2669 		if (debug)
2670 			printf("select: combine offset %.9f jitter %.9f\n",
2671 			    sys_offset, sys_jitter);
2672 #endif
2673 	}
2674 #ifdef REFCLOCK
2675 	/*
2676 	 * If a PPS driver is lit and the combined offset is less than
2677 	 * 0.4 s, select the driver as the PPS peer and use its offset
2678 	 * and jitter. However, if this is the atom driver, use it only
2679 	 * if there is a prefer peer or there are no survivors and none
2680 	 * are required.
2681 	 */
2682 	if (typepps != NULL && fabs(sys_offset < 0.4) &&
2683 	    (typepps->refclktype != REFCLK_ATOM_PPS ||
2684 	    (typepps->refclktype == REFCLK_ATOM_PPS && (sys_prefer !=
2685 	    NULL || (typesystem == NULL && sys_minsane == 0))))) {
2686 		typesystem = typepps;
2687 		sys_clockhop = 0;
2688 		typesystem->status = CTL_PST_SEL_PPS;
2689  		sys_offset = typesystem->offset;
2690 		sys_jitter = typesystem->jitter;
2691 #ifdef DEBUG
2692 		if (debug)
2693 			printf("select: pps offset %.9f jitter %.9f\n",
2694 			    sys_offset, sys_jitter);
2695 #endif
2696 	}
2697 #endif /* REFCLOCK */
2698 
2699 	/*
2700 	 * If there are no survivors at this point, there is no
2701 	 * system peer. If so and this is an old update, keep the
2702 	 * current statistics, but do not update the clock.
2703 	 */
2704 	if (typesystem == NULL) {
2705 		if (osys_peer != NULL)
2706 			report_event(EVNT_NOPEER, NULL, NULL);
2707 		sys_peer = NULL;
2708 		return;
2709 	}
2710 
2711 	/*
2712 	 * Do not use old data, as this may mess up the clock discipline
2713 	 * stability.
2714 	 */
2715 	if (typesystem->epoch <= sys_epoch)
2716 		return;
2717 
2718 	/*
2719 	 * We have found the alpha male. Wind the clock.
2720 	 */
2721  	if (osys_peer != typesystem)
2722 		report_event(PEVNT_NEWPEER, typesystem, NULL);
2723 	typesystem->flags |= FLAG_SYSPEER;
2724 	clock_update(typesystem);
2725 }
2726 
2727 
2728 /*
2729  * clock_combine - compute system offset and jitter from selected peers
2730  */
2731 static void
2732 clock_combine(
2733 	struct peer **peers,	/* survivor list */
2734 	int	npeers		/* number of survivors */
2735 	)
2736 {
2737 	int	i;
2738 	double	x, y, z, w;
2739 
2740 	y = z = w = 0;
2741 	for (i = 0; i < npeers; i++) {
2742 		x = root_distance(peers[i]);
2743 		y += 1. / x;
2744 		z += peers[i]->offset / x;
2745 		w += SQUARE(peers[i]->offset - peers[0]->offset) / x;
2746 	}
2747 	sys_offset = z / y;
2748 	sys_jitter = SQRT(w / y);
2749 }
2750 
2751 
2752 /*
2753  * root_distance - compute synchronization distance from peer to root
2754  */
2755 static double
2756 root_distance(
2757 	struct peer *peer	/* peer structure pointer */
2758 	)
2759 {
2760 	double	dtemp;
2761 
2762 	/*
2763 	 * Careful squeak here. The value returned must be greater than
2764 	 * the minimum root dispersion in order to avoid clockhop with
2765 	 * highly precise reference clocks. Note that the root distance
2766 	 * cannot exceed the sys_maxdist, as this is the cutoff by the
2767 	 * selection algorithm.
2768 	 */
2769 	dtemp = (peer->delay + peer->rootdelay) / 2 + peer->disp +
2770 	    peer->rootdisp + clock_phi * (current_time - peer->update) +
2771 	    peer->jitter;
2772 	if (dtemp < sys_mindisp)
2773 		dtemp = sys_mindisp;
2774 	return (dtemp);
2775 }
2776 
2777 
2778 /*
2779  * peer_xmit - send packet for persistent association.
2780  */
2781 static void
2782 peer_xmit(
2783 	struct peer *peer	/* peer structure pointer */
2784 	)
2785 {
2786 	struct pkt xpkt;	/* transmit packet */
2787 	int	sendlen, authlen;
2788 	keyid_t	xkeyid = 0;	/* transmit key ID */
2789 	l_fp	xmt_tx, xmt_ty;
2790 
2791 	if (!peer->dstadr)	/* drop peers without interface */
2792 		return;
2793 
2794 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
2795 	    peer->hmode);
2796 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2797 	xpkt.ppoll = peer->hpoll;
2798 	xpkt.precision = sys_precision;
2799 	xpkt.refid = sys_refid;
2800 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2801 	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
2802 	HTONL_FP(&sys_reftime, &xpkt.reftime);
2803 	HTONL_FP(&peer->rec, &xpkt.org);
2804 	HTONL_FP(&peer->dst, &xpkt.rec);
2805 
2806 	/*
2807 	 * If the received packet contains a MAC, the transmitted packet
2808 	 * is authenticated and contains a MAC. If not, the transmitted
2809 	 * packet is not authenticated.
2810 	 *
2811 	 * It is most important when autokey is in use that the local
2812 	 * interface IP address be known before the first packet is
2813 	 * sent. Otherwise, it is not possible to compute a correct MAC
2814 	 * the recipient will accept. Thus, the I/O semantics have to do
2815 	 * a little more work. In particular, the wildcard interface
2816 	 * might not be usable.
2817 	 */
2818 	sendlen = LEN_PKT_NOMAC;
2819 #ifdef OPENSSL
2820 	if (!(peer->flags & FLAG_SKEY) && peer->keyid == 0) {
2821 #else
2822 	if (peer->keyid == 0) {
2823 #endif /* OPENSSL */
2824 
2825 		/*
2826 		 * Transmit a-priori timestamps
2827 		 */
2828 		get_systime(&xmt_tx);
2829 		if (peer->flip == 0) {	/* basic mode */
2830 			peer->aorg = xmt_tx;
2831 			HTONL_FP(&xmt_tx, &xpkt.xmt);
2832 		} else {		/* interleaved modes */
2833 			if (peer->hmode == MODE_BROADCAST) { /* bcst */
2834 				HTONL_FP(&xmt_tx, &xpkt.xmt);
2835 				if (peer->flip > 0)
2836 					HTONL_FP(&peer->borg,
2837 					    &xpkt.org);
2838 				else
2839 					HTONL_FP(&peer->aorg,
2840 					    &xpkt.org);
2841 			} else {	/* symmetric */
2842 				if (peer->flip > 0)
2843 					HTONL_FP(&peer->borg,
2844 					    &xpkt.xmt);
2845 				else
2846 					HTONL_FP(&peer->aorg,
2847 					    &xpkt.xmt);
2848 			}
2849 		}
2850 		peer->t21_bytes = sendlen;
2851 		sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2852 		    &xpkt, sendlen);
2853 		peer->sent++;
2854 		peer->throttle += (1 << peer->minpoll) - 2;
2855 
2856 		/*
2857 		 * Capture a-posteriori timestamps
2858 		 */
2859 		get_systime(&xmt_ty);
2860 		if (peer->flip != 0) {		/* interleaved modes */
2861 			if (peer->flip > 0)
2862 				peer->aorg = xmt_ty;
2863 			else
2864 				peer->borg = xmt_ty;
2865 			peer->flip = -peer->flip;
2866 		}
2867 		L_SUB(&xmt_ty, &xmt_tx);
2868 		LFPTOD(&xmt_ty, peer->xleave);
2869 #ifdef DEBUG
2870 		if (debug)
2871 			printf("transmit: at %ld %s->%s mode %d len %d\n",
2872 		    	    current_time, peer->dstadr ?
2873 			    stoa(&peer->dstadr->sin) : "-",
2874 		            stoa(&peer->srcadr), peer->hmode, sendlen);
2875 #endif
2876 		return;
2877 	}
2878 
2879 	/*
2880 	 * Authentication is enabled, so the transmitted packet must be
2881 	 * authenticated. If autokey is enabled, fuss with the various
2882 	 * modes; otherwise, symmetric key cryptography is used.
2883 	 */
2884 #ifdef OPENSSL
2885 	if (peer->flags & FLAG_SKEY) {
2886 		struct exten *exten;	/* extension field */
2887 
2888 		/*
2889 		 * The Public Key Dance (PKD): Cryptographic credentials
2890 		 * are contained in extension fields, each including a
2891 		 * 4-octet length/code word followed by a 4-octet
2892 		 * association ID and optional additional data. Optional
2893 		 * data includes a 4-octet data length field followed by
2894 		 * the data itself. Request messages are sent from a
2895 		 * configured association; response messages can be sent
2896 		 * from a configured association or can take the fast
2897 		 * path without ever matching an association. Response
2898 		 * messages have the same code as the request, but have
2899 		 * a response bit and possibly an error bit set. In this
2900 		 * implementation, a message may contain no more than
2901 		 * one command and one or more responses.
2902 		 *
2903 		 * Cryptographic session keys include both a public and
2904 		 * a private componet. Request and response messages
2905 		 * using extension fields are always sent with the
2906 		 * private component set to zero. Packets without
2907 		 * extension fields indlude the private component when
2908 		 * the session key is generated.
2909 		 */
2910 		while (1) {
2911 
2912 			/*
2913 			 * Allocate and initialize a keylist if not
2914 			 * already done. Then, use the list in inverse
2915 			 * order, discarding keys once used. Keep the
2916 			 * latest key around until the next one, so
2917 			 * clients can use client/server packets to
2918 			 * compute propagation delay.
2919 			 *
2920 			 * Note that once a key is used from the list,
2921 			 * it is retained in the key cache until the
2922 			 * next key is used. This is to allow a client
2923 			 * to retrieve the encrypted session key
2924 			 * identifier to verify authenticity.
2925 			 *
2926 			 * If for some reason a key is no longer in the
2927 			 * key cache, a birthday has happened or the key
2928 			 * has expired, so the pseudo-random sequence is
2929 			 * broken. In that case, purge the keylist and
2930 			 * regenerate it.
2931 			 */
2932 			if (peer->keynumber == 0)
2933 				make_keylist(peer, peer->dstadr);
2934 			else
2935 				peer->keynumber--;
2936 			xkeyid = peer->keylist[peer->keynumber];
2937 			if (authistrusted(xkeyid))
2938 				break;
2939 			else
2940 				key_expire(peer);
2941 		}
2942 		peer->keyid = xkeyid;
2943 		exten = NULL;
2944 		switch (peer->hmode) {
2945 
2946 		/*
2947 		 * In broadcast server mode the autokey values are
2948 		 * required by the broadcast clients. Push them when a
2949 		 * new keylist is generated; otherwise, push the
2950 		 * association message so the client can request them at
2951 		 * other times.
2952 		 */
2953 		case MODE_BROADCAST:
2954 			if (peer->flags & FLAG_ASSOC)
2955 				exten = crypto_args(peer, CRYPTO_AUTO |
2956 				    CRYPTO_RESP, peer->associd, NULL);
2957 			else
2958 				exten = crypto_args(peer, CRYPTO_ASSOC |
2959 				    CRYPTO_RESP, peer->associd, NULL);
2960 			break;
2961 
2962 		/*
2963 		 * In symmetric modes the parameter, certificate,
2964 		 * identity, cookie and autokey exchanges are
2965 		 * required. The leapsecond exchange is optional. But, a
2966 		 * peer will not believe the other peer until the other
2967 		 * peer has synchronized, so the certificate exchange
2968 		 * might loop until then. If a peer finds a broken
2969 		 * autokey sequence, it uses the autokey exchange to
2970 		 * retrieve the autokey values. In any case, if a new
2971 		 * keylist is generated, the autokey values are pushed.
2972 		 */
2973 		case MODE_ACTIVE:
2974 		case MODE_PASSIVE:
2975 
2976 			/*
2977 			 * Parameter, certificate and identity.
2978 			 */
2979 			if (!peer->crypto)
2980 				exten = crypto_args(peer, CRYPTO_ASSOC,
2981 				    peer->associd, sys_hostname);
2982 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
2983 				exten = crypto_args(peer, CRYPTO_CERT,
2984 				    peer->associd, peer->issuer);
2985 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2986 				exten = crypto_args(peer,
2987 				    crypto_ident(peer), peer->associd,
2988 				    NULL);
2989 
2990 			/*
2991 			 * Cookie and autokey. We request the cookie
2992 			 * only when the this peer and the other peer
2993 			 * are synchronized. But, this peer needs the
2994 			 * autokey values when the cookie is zero. Any
2995 			 * time we regenerate the key list, we offer the
2996 			 * autokey values without being asked. If for
2997 			 * some reason either peer finds a broken
2998 			 * autokey sequence, the autokey exchange is
2999 			 * used to retrieve the autokey values.
3000 			 */
3001 			else if (sys_leap != LEAP_NOTINSYNC &&
3002 			    peer->leap != LEAP_NOTINSYNC &&
3003 			    !(peer->crypto & CRYPTO_FLAG_COOK))
3004 				exten = crypto_args(peer, CRYPTO_COOK,
3005 				    peer->associd, NULL);
3006 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3007 				exten = crypto_args(peer, CRYPTO_AUTO,
3008 				    peer->associd, NULL);
3009 			else if (peer->flags & FLAG_ASSOC &&
3010 			    peer->crypto & CRYPTO_FLAG_SIGN)
3011 				exten = crypto_args(peer, CRYPTO_AUTO |
3012 				    CRYPTO_RESP, peer->assoc, NULL);
3013 
3014 			/*
3015 			 * Wait for clock sync, then sign the
3016 			 * certificate and retrieve the leapsecond
3017 			 * values.
3018 			 */
3019 			else if (sys_leap == LEAP_NOTINSYNC)
3020 				break;
3021 
3022 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3023 				exten = crypto_args(peer, CRYPTO_SIGN,
3024 				    peer->associd, sys_hostname);
3025 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3026 				exten = crypto_args(peer, CRYPTO_LEAP,
3027 				    peer->associd, NULL);
3028 			break;
3029 
3030 		/*
3031 		 * In client mode the parameter, certificate, identity,
3032 		 * cookie and sign exchanges are required. The
3033 		 * leapsecond exchange is optional. If broadcast client
3034 		 * mode the same exchanges are required, except that the
3035 		 * autokey exchange is substitutes for the cookie
3036 		 * exchange, since the cookie is always zero. If the
3037 		 * broadcast client finds a broken autokey sequence, it
3038 		 * uses the autokey exchange to retrieve the autokey
3039 		 * values.
3040 		 */
3041 		case MODE_CLIENT:
3042 
3043 			/*
3044 			 * Parameter, certificate and identity.
3045 			 */
3046 			if (!peer->crypto)
3047 				exten = crypto_args(peer, CRYPTO_ASSOC,
3048 				    peer->associd, sys_hostname);
3049 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3050 				exten = crypto_args(peer, CRYPTO_CERT,
3051 				    peer->associd, peer->issuer);
3052 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3053 				exten = crypto_args(peer,
3054 				    crypto_ident(peer), peer->associd,
3055 				    NULL);
3056 
3057 			/*
3058 			 * Cookie and autokey. These are requests, but
3059 			 * we use the peer association ID with autokey
3060 			 * rather than our own.
3061 			 */
3062 			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3063 				exten = crypto_args(peer, CRYPTO_COOK,
3064 				    peer->associd, NULL);
3065 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3066 				exten = crypto_args(peer, CRYPTO_AUTO,
3067 				    peer->assoc, NULL);
3068 
3069 			/*
3070 			 * Wait for clock sync, then sign the
3071 			 * certificate and retrieve the leapsecond
3072 			 * values.
3073 			 */
3074 			else if (sys_leap == LEAP_NOTINSYNC)
3075 				break;
3076 
3077 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3078 				exten = crypto_args(peer, CRYPTO_SIGN,
3079 				    peer->associd, sys_hostname);
3080 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3081 				exten = crypto_args(peer, CRYPTO_LEAP,
3082 				    peer->associd, NULL);
3083 			break;
3084 		}
3085 
3086 		/*
3087 		 * Add a queued extension field if present. This is
3088 		 * always a request message, so the reply ID is already
3089 		 * in the message. If an error occurs, the error bit is
3090 		 * lit in the response.
3091 		 */
3092 		if (peer->cmmd != NULL) {
3093 			u_int32 temp32;
3094 
3095 			temp32 = CRYPTO_RESP;
3096 			peer->cmmd->opcode |= htonl(temp32);
3097 			sendlen += crypto_xmit(peer, &xpkt, NULL,
3098 			    sendlen, peer->cmmd, 0);
3099 			free(peer->cmmd);
3100 			peer->cmmd = NULL;
3101 		}
3102 
3103 		/*
3104 		 * Add an extension field created above. All but the
3105 		 * autokey response message are request messages.
3106 		 */
3107 		if (exten != NULL) {
3108 			if (exten->opcode != 0)
3109 				sendlen += crypto_xmit(peer, &xpkt,
3110 				    NULL, sendlen, exten, 0);
3111 			free(exten);
3112 		}
3113 
3114 		/*
3115 		 * Calculate the next session key. Since extension
3116 		 * fields are present, the cookie value is zero.
3117 		 */
3118 		if (sendlen > (int)LEN_PKT_NOMAC) {
3119 			session_key(&peer->dstadr->sin, &peer->srcadr,
3120 			    xkeyid, 0, 2);
3121 		}
3122 	}
3123 #endif /* OPENSSL */
3124 
3125 	/*
3126 	 * Transmit a-priori timestamps
3127 	 */
3128 	get_systime(&xmt_tx);
3129 	if (peer->flip == 0) {		/* basic mode */
3130 		peer->aorg = xmt_tx;
3131 		HTONL_FP(&xmt_tx, &xpkt.xmt);
3132 	} else {			/* interleaved modes */
3133 		if (peer->hmode == MODE_BROADCAST) { /* bcst */
3134 			HTONL_FP(&xmt_tx, &xpkt.xmt);
3135 			if (peer->flip > 0)
3136 				HTONL_FP(&peer->borg, &xpkt.org);
3137 			else
3138 				HTONL_FP(&peer->aorg, &xpkt.org);
3139 		} else {		/* symmetric */
3140 			if (peer->flip > 0)
3141 				HTONL_FP(&peer->borg, &xpkt.xmt);
3142 			else
3143 				HTONL_FP(&peer->aorg, &xpkt.xmt);
3144 		}
3145 	}
3146 	xkeyid = peer->keyid;
3147 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3148 	if (authlen == 0) {
3149 		report_event(PEVNT_AUTH, peer, "no key");
3150 		peer->flash |= TEST5;		/* auth error */
3151 		peer->badauth++;
3152 		return;
3153 	}
3154 	sendlen += authlen;
3155 #ifdef OPENSSL
3156 	if (xkeyid > NTP_MAXKEY)
3157 		authtrust(xkeyid, 0);
3158 #endif /* OPENSSL */
3159 	if (sendlen > (int)sizeof(xpkt)) {
3160 		msyslog(LOG_ERR, "proto: buffer overflow %u", sendlen);
3161 		exit (-1);
3162 	}
3163 	peer->t21_bytes = sendlen;
3164 	sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
3165 	    sendlen);
3166 	peer->sent++;
3167 	peer->throttle += (1 << peer->minpoll) - 2;
3168 
3169 	/*
3170 	 * Capture a-posteriori timestamps
3171 	 */
3172 	get_systime(&xmt_ty);
3173 	if (peer->flip != 0) {			/* interleaved modes */
3174 		if (peer->flip > 0)
3175 			peer->aorg = xmt_ty;
3176 		else
3177 			peer->borg = xmt_ty;
3178 		peer->flip = -peer->flip;
3179 	}
3180 	L_SUB(&xmt_ty, &xmt_tx);
3181 	LFPTOD(&xmt_ty, peer->xleave);
3182 #ifdef OPENSSL
3183 #ifdef DEBUG
3184 	if (debug)
3185 		printf("transmit: at %ld %s->%s mode %d keyid %08x len %d index %d\n",
3186 		    current_time, peer->dstadr ?
3187 		    ntoa(&peer->dstadr->sin) : "-",
3188 	 	    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
3189 		    peer->keynumber);
3190 #endif
3191 #else /* OPENSSL */
3192 #ifdef DEBUG
3193 	if (debug)
3194 		printf("transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3195 		    current_time, peer->dstadr ?
3196 		    ntoa(&peer->dstadr->sin) : "-",
3197 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen);
3198 #endif
3199 #endif /* OPENSSL */
3200 }
3201 
3202 
3203 /*
3204  * fast_xmit - Send packet for nonpersistent association. Note that
3205  * neither the source or destination can be a broadcast address.
3206  */
3207 static void
3208 fast_xmit(
3209 	struct recvbuf *rbufp,	/* receive packet pointer */
3210 	int	xmode,		/* receive mode */
3211 	keyid_t	xkeyid,		/* transmit key ID */
3212 	int	flags		/* restrict mask */
3213 	)
3214 {
3215 	struct pkt xpkt;	/* transmit packet structure */
3216 	struct pkt *rpkt;	/* receive packet structure */
3217 	l_fp	xmt_tx, xmt_ty;
3218 	int	sendlen;
3219 #ifdef OPENSSL
3220 	u_int32	temp32;
3221 #endif
3222 
3223 	/*
3224 	 * Initialize transmit packet header fields from the receive
3225 	 * buffer provided. We leave the fields intact as received, but
3226 	 * set the peer poll at the maximum of the receive peer poll and
3227 	 * the system minimum poll (ntp_minpoll). This is for KoD rate
3228 	 * control and not strictly specification compliant, but doesn't
3229 	 * break anything.
3230 	 *
3231 	 * If the gazinta was from a multicast address, the gazoutta
3232 	 * must go out another way.
3233 	 */
3234 	rpkt = &rbufp->recv_pkt;
3235 	if (rbufp->dstadr->flags & INT_MCASTOPEN)
3236 		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
3237 
3238 	/*
3239 	 * If this is a kiss-o'-death (KoD) packet, show leap
3240 	 * unsynchronized, stratum zero, reference ID the four-character
3241 	 * kiss code and system root delay. Note we don't reveal the
3242 	 * local time, so these packets can't be used for
3243 	 * synchronization.
3244 	 */
3245 	if (flags & RES_KOD) {
3246 		sys_kodsent++;
3247 		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
3248 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
3249 		xpkt.stratum = STRATUM_PKT_UNSPEC;
3250 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3251 		memcpy(&xpkt.refid, "RATE", 4);
3252 		xpkt.org = rpkt->xmt;
3253 		xpkt.rec = rpkt->xmt;
3254 		xpkt.xmt = rpkt->xmt;
3255 
3256 	/*
3257 	 * This is a normal packet. Use the system variables.
3258 	 */
3259 	} else {
3260 		xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
3261 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
3262 		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3263 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3264 		xpkt.precision = sys_precision;
3265 		xpkt.refid = sys_refid;
3266 		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3267 		xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3268 		HTONL_FP(&sys_reftime, &xpkt.reftime);
3269 		xpkt.org = rpkt->xmt;
3270 		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
3271 		get_systime(&xmt_tx);
3272 		HTONL_FP(&xmt_tx, &xpkt.xmt);
3273 	}
3274 
3275 #ifdef HAVE_NTP_SIGND
3276 	if (flags & RES_MSSNTP) {
3277 		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
3278 		return;
3279 	}
3280 #endif /* HAVE_NTP_SIGND */
3281 
3282 	/*
3283 	 * If the received packet contains a MAC, the transmitted packet
3284 	 * is authenticated and contains a MAC. If not, the transmitted
3285 	 * packet is not authenticated.
3286 	 */
3287 	sendlen = LEN_PKT_NOMAC;
3288 	if (rbufp->recv_length == sendlen) {
3289 		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
3290 		    sendlen);
3291 #ifdef DEBUG
3292 		if (debug)
3293 			printf(
3294 			    "transmit: at %ld %s->%s mode %d len %d\n",
3295 			    current_time, stoa(&rbufp->dstadr->sin),
3296 			    stoa(&rbufp->recv_srcadr), xmode, sendlen);
3297 #endif
3298 		return;
3299 	}
3300 
3301 	/*
3302 	 * The received packet contains a MAC, so the transmitted packet
3303 	 * must be authenticated. For symmetric key cryptography, use
3304 	 * the predefined and trusted symmetric keys to generate the
3305 	 * cryptosum. For autokey cryptography, use the server private
3306 	 * value to generate the cookie, which is unique for every
3307 	 * source-destination-key ID combination.
3308 	 */
3309 #ifdef OPENSSL
3310 	if (xkeyid > NTP_MAXKEY) {
3311 		keyid_t cookie;
3312 
3313 		/*
3314 		 * The only way to get here is a reply to a legitimate
3315 		 * client request message, so the mode must be
3316 		 * MODE_SERVER. If an extension field is present, there
3317 		 * can be only one and that must be a command. Do what
3318 		 * needs, but with private value of zero so the poor
3319 		 * jerk can decode it. If no extension field is present,
3320 		 * use the cookie to generate the session key.
3321 		 */
3322 		cookie = session_key(&rbufp->recv_srcadr,
3323 		    &rbufp->dstadr->sin, 0, sys_private, 0);
3324 		if (rbufp->recv_length > (int)(sendlen + MAX_MAC_LEN)) {
3325 			session_key(&rbufp->dstadr->sin,
3326 			    &rbufp->recv_srcadr, xkeyid, 0, 2);
3327 			temp32 = CRYPTO_RESP;
3328 			rpkt->exten[0] |= htonl(temp32);
3329 			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
3330 			    sendlen, (struct exten *)rpkt->exten,
3331 			    cookie);
3332 		} else {
3333 			session_key(&rbufp->dstadr->sin,
3334 			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
3335 		}
3336 	}
3337 #endif /* OPENSSL */
3338 	get_systime(&xmt_tx);
3339 	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3340 #ifdef OPENSSL
3341 	if (xkeyid > NTP_MAXKEY)
3342 		authtrust(xkeyid, 0);
3343 #endif /* OPENSSL */
3344 	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
3345 	get_systime(&xmt_ty);
3346 	L_SUB(&xmt_ty, &xmt_tx);
3347 	sys_authdelay = xmt_ty;
3348 #ifdef DEBUG
3349 	if (debug)
3350 		printf(
3351 		    "transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3352 		    current_time, ntoa(&rbufp->dstadr->sin),
3353 		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen);
3354 #endif
3355 }
3356 
3357 
3358 #ifdef OPENSSL
3359 /*
3360  * key_expire - purge the key list
3361  */
3362 void
3363 key_expire(
3364 	struct peer *peer	/* peer structure pointer */
3365 	)
3366 {
3367 	int i;
3368 
3369 	if (peer->keylist != NULL) {
3370 		for (i = 0; i <= peer->keynumber; i++)
3371 			authtrust(peer->keylist[i], 0);
3372 		free(peer->keylist);
3373 		peer->keylist = NULL;
3374 	}
3375 	value_free(&peer->sndval);
3376 	peer->keynumber = 0;
3377 	peer->flags &= ~FLAG_ASSOC;
3378 #ifdef DEBUG
3379 	if (debug)
3380 		printf("key_expire: at %lu associd %d\n", current_time,
3381 		    peer->associd);
3382 #endif
3383 }
3384 #endif /* OPENSSL */
3385 
3386 
3387 /*
3388  * Determine if the peer is unfit for synchronization
3389  *
3390  * A peer is unfit for synchronization if
3391  * > TEST10 bad leap or stratum below floor or at or above ceiling
3392  * > TEST11 root distance exceeded for remote peer
3393  * > TEST12 a direct or indirect synchronization loop would form
3394  * > TEST13 unreachable or noselect
3395  */
3396 int				/* FALSE if fit, TRUE if unfit */
3397 peer_unfit(
3398 	struct peer *peer	/* peer structure pointer */
3399 	)
3400 {
3401 	int	rval = 0;
3402 
3403 	/*
3404 	 * A stratum error occurs if (1) the server has never been
3405 	 * synchronized, (2) the server stratum is below the floor or
3406 	 * greater than or equal to the ceiling.
3407 	 */
3408 	if (peer->leap == LEAP_NOTINSYNC || peer->stratum < sys_floor ||
3409 	    peer->stratum >= sys_ceiling)
3410 		rval |= TEST10;		/* bad synch or stratum */
3411 
3412 	/*
3413 	 * A distance error for a remote peer occurs if the root
3414 	 * distance is greater than or equal to the distance threshold
3415 	 * plus the increment due to one host poll interval.
3416 	 */
3417 	if (!(peer->flags & FLAG_REFCLOCK) && root_distance(peer) >=
3418 	    sys_maxdist + clock_phi * ULOGTOD(peer->hpoll))
3419 		rval |= TEST11;		/* distance exceeded */
3420 
3421 	/*
3422 	 * A loop error occurs if the remote peer is synchronized to the
3423 	 * local peer or if the remote peer is synchronized to the same
3424 	 * server as the local peer but only if the remote peer is
3425 	 * neither a reference clock nor an orphan.
3426 	 */
3427 	if (peer->stratum > 1 && peer->refid != htonl(LOOPBACKADR) &&
3428 	    (peer->refid == (peer->dstadr ? peer->dstadr->addr_refid :
3429 	    0) || peer->refid == sys_refid))
3430 		rval |= TEST12;		/* synchronization loop */
3431 
3432 	/*
3433 	 * An unreachable error occurs if the server is unreachable or
3434 	 * the noselect bit is set.
3435 	 */
3436 	if (!peer->reach || (peer->flags & FLAG_NOSELECT))
3437 		rval |= TEST13;		/* unreachable */
3438 
3439 	peer->flash &= ~PEER_TEST_MASK;
3440 	peer->flash |= rval;
3441 	return (rval);
3442 }
3443 
3444 
3445 /*
3446  * Find the precision of this particular machine
3447  */
3448 #define MINSTEP 100e-9		/* minimum clock increment (s) */
3449 #define MAXSTEP 20e-3		/* maximum clock increment (s) */
3450 #define MINLOOPS 5		/* minimum number of step samples */
3451 
3452 /*
3453  * This routine measures the system precision defined as the minimum of
3454  * a sequence of differences between successive readings of the system
3455  * clock. However, if a difference is less than MINSTEP, the clock has
3456  * been read more than once during a clock tick and the difference is
3457  * ignored. We set MINSTEP greater than zero in case something happens
3458  * like a cache miss.
3459  */
3460 int
3461 default_get_precision(void)
3462 {
3463 	l_fp	val;		/* current seconds fraction */
3464 	l_fp	last;		/* last seconds fraction */
3465 	l_fp	diff;		/* difference */
3466 	double	tick;		/* computed tick value */
3467 	double	dtemp;		/* scratch */
3468 	int	i;		/* log2 precision */
3469 
3470 	/*
3471 	 * Loop to find precision value in seconds.
3472 	 */
3473 	tick = MAXSTEP;
3474 	i = 0;
3475 	get_systime(&last);
3476 	while (1) {
3477 		get_systime(&val);
3478 		diff = val;
3479 		L_SUB(&diff, &last);
3480 		last = val;
3481 		LFPTOD(&diff, dtemp);
3482 		if (dtemp < MINSTEP)
3483 			continue;
3484 
3485 		if (dtemp < tick)
3486 			tick = dtemp;
3487 		if (++i >= MINLOOPS)
3488 			break;
3489 	}
3490 	sys_tick = tick;
3491 
3492 	/*
3493 	 * Find the nearest power of two.
3494 	 */
3495 	msyslog(LOG_NOTICE, "proto: precision = %.3f usec", tick * 1e6);
3496 	for (i = 0; tick <= 1; i++)
3497 		tick *= 2;
3498 	if (tick - 1 > 1 - tick / 2)
3499 		i--;
3500 	return (-i);
3501 }
3502 
3503 
3504 /*
3505  * init_proto - initialize the protocol module's data
3506  */
3507 void
3508 init_proto(void)
3509 {
3510 	l_fp	dummy;
3511 	int	i;
3512 
3513 	/*
3514 	 * Fill in the sys_* stuff.  Default is don't listen to
3515 	 * broadcasting, require authentication.
3516 	 */
3517 	sys_leap = LEAP_NOTINSYNC;
3518 	sys_stratum = STRATUM_UNSPEC;
3519 	memcpy(&sys_refid, "INIT", 4);
3520 	sys_peer = NULL;
3521 	sys_rootdelay = 0;
3522 	sys_rootdisp = 0;
3523 	L_CLR(&sys_reftime);
3524 	sys_jitter = 0;
3525 	sys_precision = (s_char)default_get_precision();
3526 	get_systime(&dummy);
3527 	sys_survivors = 0;
3528 	sys_manycastserver = 0;
3529 	sys_bclient = 0;
3530 	sys_bdelay = 0;
3531 	sys_authenticate = 1;
3532 	sys_stattime = current_time;
3533 	proto_clr_stats();
3534 	for (i = 0; i < MAX_TTL; i++) {
3535 		sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
3536 		sys_ttlmax = i;
3537 	}
3538 	pps_enable = 0;
3539 	stats_control = 1;
3540 }
3541 
3542 
3543 /*
3544  * proto_config - configure the protocol module
3545  */
3546 void
3547 proto_config(
3548 	int	item,
3549 	u_long	value,
3550 	double	dvalue,
3551 	sockaddr_u *svalue
3552 	)
3553 {
3554 	/*
3555 	 * Figure out what he wants to change, then do it
3556 	 */
3557 	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
3558 		    item, value, dvalue));
3559 
3560 	switch (item) {
3561 
3562 	/*
3563 	 * enable and disable commands - arguments are Boolean.
3564 	 */
3565 	case PROTO_AUTHENTICATE: /* authentication (auth) */
3566 		sys_authenticate = value;
3567 		break;
3568 
3569 	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
3570 		sys_bclient = (int)value;
3571 		if (sys_bclient == 0)
3572 			io_unsetbclient();
3573 		else
3574 			io_setbclient();
3575 		break;
3576 
3577 #ifdef REFCLOCK
3578 	case PROTO_CAL:		/* refclock calibrate (calibrate) */
3579 		cal_enable = value;
3580 		break;
3581 #endif /* REFCLOCK */
3582 
3583 	case PROTO_KERNEL:	/* kernel discipline (kernel) */
3584 		kern_enable = value;
3585 		break;
3586 
3587 	case PROTO_MONITOR:	/* monitoring (monitor) */
3588 		if (value)
3589 			mon_start(MON_ON);
3590 		else
3591 			mon_stop(MON_ON);
3592 		break;
3593 
3594 	case PROTO_NTP:		/* NTP discipline (ntp) */
3595 		ntp_enable = value;
3596 		break;
3597 
3598 	case PROTO_PPS:		/* PPS discipline (pps) */
3599 		pps_enable = value;
3600 		break;
3601 
3602 	case PROTO_FILEGEN:	/* statistics (stats) */
3603 		stats_control = value;
3604 		break;
3605 
3606 	/*
3607 	 * tos command - arguments are double, sometimes cast to int
3608 	 */
3609 	case PROTO_BEACON:	/* manycast beacon (beacon) */
3610 		sys_beacon = (int)dvalue;
3611 		break;
3612 
3613 	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
3614 		sys_bdelay = dvalue;
3615 		break;
3616 
3617 	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
3618 		sys_ceiling = (int)dvalue;
3619 		break;
3620 
3621 	case PROTO_COHORT:	/* cohort switch (cohort) */
3622 		sys_cohort = (int)dvalue;
3623 		break;
3624 
3625 	case PROTO_FLOOR:	/* stratum floor (floor) */
3626 		sys_floor = (int)dvalue;
3627 		break;
3628 
3629 	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
3630 		sys_maxclock = (int)dvalue;
3631 		break;
3632 
3633 	case PROTO_MAXDIST:	/* select threshold (maxdist) */
3634 		sys_maxdist = dvalue;
3635 		break;
3636 
3637 	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
3638 		break;		/* NOT USED */
3639 
3640 	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
3641 		sys_minclock = (int)dvalue;
3642 		break;
3643 
3644 	case PROTO_MINDISP:	/* minimum distance (mindist) */
3645 		sys_mindisp = dvalue;
3646 		break;
3647 
3648 	case PROTO_MINSANE:	/* minimum survivors (minsane) */
3649 		sys_minsane = (int)dvalue;
3650 		break;
3651 
3652 	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
3653 		sys_orphan = (int)dvalue;
3654 		break;
3655 
3656 	case PROTO_ADJ:		/* tick increment (tick) */
3657 		sys_tick = dvalue;
3658 		break;
3659 
3660 	/*
3661 	 * Miscellaneous commands
3662 	 */
3663 	case PROTO_MULTICAST_ADD: /* add group address */
3664 		if (svalue != NULL)
3665 			io_multicast_add(svalue);
3666 		sys_bclient = 1;
3667 		break;
3668 
3669 	case PROTO_MULTICAST_DEL: /* delete group address */
3670 		if (svalue != NULL)
3671 			io_multicast_del(svalue);
3672 		break;
3673 
3674 	default:
3675 		msyslog(LOG_NOTICE,
3676 		    "proto: unsupported option %d", item);
3677 	}
3678 }
3679 
3680 
3681 /*
3682  * proto_clr_stats - clear protocol stat counters
3683  */
3684 void
3685 proto_clr_stats(void)
3686 {
3687 	sys_stattime = current_time;
3688 	sys_received = 0;
3689 	sys_processed = 0;
3690 	sys_newversion = 0;
3691 	sys_oldversion = 0;
3692 	sys_declined = 0;
3693 	sys_restricted = 0;
3694 	sys_badlength = 0;
3695 	sys_badauth = 0;
3696 	sys_limitrejected = 0;
3697 }
3698