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