xref: /freebsd/contrib/ntp/ntpd/ntp_proto.c (revision b52b9d56d4e96089873a75f9e29062eec19fabba)
1 /*
2  * ntp_proto.c - NTP version 4 protocol machinery
3  *
4  * $FreeBSD$
5  */
6 #ifdef HAVE_CONFIG_H
7 #include <config.h>
8 #endif
9 
10 #include "ntpd.h"
11 #include "ntp_stdlib.h"
12 #include "ntp_unixtime.h"
13 #include "ntp_control.h"
14 #include "ntp_string.h"
15 #include "ntp_crypto.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  * System variables are declared here. See Section 3.2 of the
29  * specification.
30  */
31 u_char	sys_leap;		/* system leap indicator */
32 u_char	sys_stratum;		/* stratum of system */
33 s_char	sys_precision;		/* local clock precision */
34 double	sys_rootdelay;		/* roundtrip delay to primary source */
35 double	sys_rootdispersion;	/* dispersion to primary source */
36 u_int32 sys_refid;		/* reference source for local clock */
37 static	double sys_offset;	/* current local clock offset */
38 l_fp	sys_reftime;		/* time we were last updated */
39 struct	peer *sys_peer; 	/* our current peer */
40 struct	peer *sys_prefer;	/* our cherished peer */
41 #ifdef AUTOKEY
42 u_long	sys_automax;		/* maximum session key lifetime */
43 #endif /* AUTOKEY */
44 
45 /*
46  * Nonspecified system state variables.
47  */
48 int	sys_bclient;		/* we set our time to broadcasts */
49 double	sys_bdelay; 		/* broadcast client default delay */
50 int	sys_authenticate;	/* requre authentication for config */
51 l_fp	sys_authdelay;		/* authentication delay */
52 static	u_long sys_authdly[2]; 	/* authentication delay shift reg */
53 static	u_char leap_consensus;	/* consensus of survivor leap bits */
54 static	double sys_selerr; 	/* select error (squares) */
55 static	double sys_syserr;	/* system error (squares) */
56 keyid_t	sys_private;		/* private value for session seed */
57 int	sys_manycastserver;	/* respond to manycast client pkts */
58 u_int sys_survivors;		/* truest of the truechimers */
59 int	peer_ntpdate;		/* active peers in ntpdate mode */
60 #ifdef AUTOKEY
61 char	*sys_hostname;		/* gethostname() name */
62 #endif /* AUTOKEY */
63 
64 /*
65  * Statistics counters
66  */
67 u_long	sys_stattime;		/* time when we started recording */
68 u_long	sys_badstratum; 	/* packets with invalid stratum */
69 u_long	sys_oldversionpkt;	/* old version packets received */
70 u_long	sys_newversionpkt;	/* new version packets received */
71 u_long	sys_unknownversion;	/* don't know version packets */
72 u_long	sys_badlength;		/* packets with bad length */
73 u_long	sys_processed;		/* packets processed */
74 u_long	sys_badauth;		/* packets dropped because of auth */
75 u_long	sys_limitrejected;	/* pkts rejected due to client count per net */
76 
77 static	double	root_distance	P((struct peer *));
78 static	double	clock_combine	P((struct peer **, int));
79 static	void	peer_xmit	P((struct peer *));
80 static	void	fast_xmit	P((struct recvbuf *, int, keyid_t, int));
81 static	void	clock_update	P((void));
82 int	default_get_precision	P((void));
83 
84 
85 /*
86  * transmit - Transmit Procedure. See Section 3.4.2 of the
87  *	specification.
88  */
89 void
90 transmit(
91 	struct peer *peer	/* peer structure pointer */
92 	)
93 {
94 	int hpoll;
95 
96 	hpoll = peer->hpoll;
97 	if (peer->burst == 0) {
98 		u_char oreach;
99 
100 		/*
101 		 * The polling state machine. There are two kinds of
102 		 * machines, those that never expect a reply (broadcast
103 		 * and manycast server modes) and those that do (all
104 		 * other modes). The dance is intricate...
105 		 */
106 		if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
107 
108 			/*
109 			 * In broadcast mode the poll interval is fixed
110 			 * at minpoll and the ttl at ttlmax.
111 			 */
112 			hpoll = peer->minpoll;
113 			peer->ttl = peer->ttlmax;
114 #ifdef AUTOKEY
115 		} else if (peer->cast_flags & MDF_ACAST) {
116 
117 			/*
118 			 * In manycast mode we start with the minpoll
119 			 * interval and ttl. However, the actual poll
120 			 * interval is eight times the nominal poll
121 			 * interval shown here. If fewer than three
122 			 * servers are found, the ttl is increased by
123 			 * one and we try again. If this continues to
124 			 * the max ttl, the poll interval is bumped by
125 			 * one and we try again. If at least three
126 			 * servers are found, the poll interval
127 			 * increases with the system poll interval to
128 			 * the max and we continue indefinately.
129 			 * However, about once per day when the
130 			 * agreement parameters are refreshed, the
131 			 * manycast clients are reset and we start from
132 			 * the beginning. This is to catch and clamp the
133 			 * ttl to the lowest practical value and avoid
134 			 * knocking on spurious doors.
135 			 */
136 			if (sys_survivors < NTP_MINCLOCK && peer->ttl <
137 			    peer->ttlmax)
138 				peer->ttl++;
139 			hpoll = sys_poll;
140 #endif /* AUTOKEY */
141 		} else {
142 
143 			/*
144 			 * For associations expecting a reply, the
145 			 * watchdog counter is bumped by one if the peer
146 			 * has not been heard since the previous poll.
147 			 * If the counter reaches the max, the peer is
148 			 * demobilized if not configured and just
149 			 * cleared if it is, but in this case the poll
150 			 * interval is bumped by one.
151 			 */
152 			if (peer->unreach < NTP_UNREACH) {
153 				peer->unreach++;
154 			} else if (!(peer->flags & FLAG_CONFIG)) {
155 				unpeer(peer);
156 				clock_select();
157 				return;
158 
159 			} else {
160 				peer_clear(peer);
161 				hpoll++;
162 			}
163 		}
164 		oreach = peer->reach;
165 		peer->reach <<= 1;
166 		if (peer->reach == 0) {
167 
168 			/*
169 			 * If this association has become unreachable,
170 			 * clear it and raise a trap.
171 			 */
172 			if (oreach != 0) {
173 				report_event(EVNT_UNREACH, peer);
174 				peer->timereachable = current_time;
175 				if (!(peer->flags & FLAG_CONFIG)) {
176 					unpeer(peer);
177 					clock_select();
178 					return;
179 				} else {
180 					peer_clear(peer);
181 					hpoll = peer->minpoll;
182 				}
183 			}
184 			if (peer->flags & FLAG_IBURST)
185 				peer->burst = NTP_SHIFT;
186 		} else {
187 
188 			/*
189 			 * Here the peer is reachable. If it has not
190 			 * been heard for three consecutive polls, stuff
191 			 * the clock filter. Next, determine the poll
192 			 * interval. If the peer is a synchronization
193 			 * candidate, use the system poll interval. If
194 			 * the peer is not sane, increase it by one. If
195 			 * the number of valid updates is not greater
196 			 * than half the register size, clamp it to the
197 			 * minimum. This is to quickly recover the time
198 			 * variables when a noisy peer shows life.
199 			 */
200 			if (!(peer->reach & 0x07)) {
201 				clock_filter(peer, 0., 0., MAXDISPERSE);
202 				clock_select();
203 			}
204 			if ((peer->stratum > 1 && peer->refid ==
205 			    peer->dstadr->sin.sin_addr.s_addr) ||
206 			    peer->stratum >= STRATUM_UNSPEC)
207 				hpoll++;
208 			else
209 				hpoll = sys_poll;
210 			if (peer->flags & FLAG_BURST)
211 				peer->burst = NTP_SHIFT;
212 		}
213 	} else {
214 		peer->burst--;
215 		if (peer->burst == 0) {
216 
217 			/*
218 			 * If a broadcast client at this point, the
219 			 * burst has concluded, so we switch to client
220 			 * mode and purge the keylist, since no further
221 			 * transmissions will be made.
222 			 */
223 			if (peer->cast_flags & MDF_BCLNT) {
224 				peer->hmode = MODE_BCLIENT;
225 #ifdef AUTOKEY
226 				key_expire(peer);
227 #endif /* AUTOKEY */
228 			}
229 			poll_update(peer, hpoll);
230 			clock_select();
231 
232 			/*
233 			 * If ntpdate mode and the clock has not been
234 			 * set and all peers have completed the burst,
235 			 * we declare a successful failure.
236 			 */
237 			if (mode_ntpdate) {
238 				peer_ntpdate--;
239 				if (peer_ntpdate > 0)
240 					return;
241 				NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
242 				    msyslog(LOG_NOTICE,
243 				    "no reply; clock not set");
244 				printf(
245 				    "ntpd: no reply; clock not set\n");
246 				exit(0);
247 			}
248 			return;
249 
250 		}
251 	}
252 	peer->outdate = current_time;
253 	poll_update(peer, hpoll);
254 
255 	/*
256 	 * We need to be very careful about honking uncivilized time.
257 	 * Never transmit if in broadcast client mode or access denied.
258 	 * If in broadcast mode, transmit only if synchronized to a
259 	 * valid source.
260 	 */
261 	if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
262 		return;
263 	} else if (peer->hmode == MODE_BROADCAST) {
264 		if (sys_peer == NULL)
265 			return;
266 	}
267 	peer_xmit(peer);
268 }
269 
270 /*
271  * receive - Receive Procedure.  See section 3.4.3 in the specification.
272  */
273 void
274 receive(
275 	struct recvbuf *rbufp
276 	)
277 {
278 	register struct peer *peer;
279 	register struct pkt *pkt;
280 	int hismode;
281 	int oflags;
282 	int restrict_mask;
283 	int has_mac;			/* length of MAC field */
284 	int authlen;			/* offset of MAC field */
285 	int is_authentic;		/* cryptosum ok */
286 	keyid_t skeyid;			/* cryptographic keys */
287 	struct sockaddr_in *dstadr_sin;	/* active runway */
288 #ifdef AUTOKEY
289 	keyid_t pkeyid, tkeyid;		/* cryptographic keys */
290 #endif /* AUTOKEY */
291 	struct peer *peer2;
292 	int retcode = AM_NOMATCH;
293 
294 	/*
295 	 * Monitor the packet and get restrictions. Note that the packet
296 	 * length for control and private mode packets must be checked
297 	 * by the service routines. Note that no statistics counters are
298 	 * recorded for restrict violations, since these counters are in
299 	 * the restriction routine. Note the careful distinctions here
300 	 * between a packet with a format error and a packet that is
301 	 * simply discarded without prejudice. Some restrictions have to
302 	 * be handled later in order to generate a kiss-of-death packet.
303 	 */
304 	ntp_monitor(rbufp);
305 	restrict_mask = restrictions(&rbufp->recv_srcadr);
306 #ifdef DEBUG
307 	if (debug > 2)
308 		printf("receive: at %ld %s<-%s restrict %02x\n",
309 		    current_time, ntoa(&rbufp->dstadr->sin),
310 		    ntoa(&rbufp->recv_srcadr), restrict_mask);
311 #endif
312 	if (restrict_mask & RES_IGNORE)
313 		return;				/* no anything */
314 	if (!(SRCPORT(&rbufp->recv_srcadr) == NTP_PORT ||
315 	    SRCPORT(&rbufp->recv_srcadr) >= IPPORT_RESERVED)) {
316 		sys_badlength++;
317 		return;				/* invalid port */
318 	}
319 	pkt = &rbufp->recv_pkt;
320 	if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
321 		sys_newversionpkt++;		/* new version */
322 	} else if (!(restrict_mask & RES_VERSION) &&
323 	    PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
324 		sys_oldversionpkt++;		/* old version */
325 	} else {
326 		sys_unknownversion++;
327 		return;				/* invalid version */
328 	}
329 	if (PKT_MODE(pkt->li_vn_mode) == MODE_PRIVATE) {
330 		if (restrict_mask & RES_NOQUERY)
331 			return;			/* no query private */
332 		process_private(rbufp, ((restrict_mask &
333 		    RES_NOMODIFY) == 0));
334 		return;
335 	}
336 	if (PKT_MODE(pkt->li_vn_mode) == MODE_CONTROL) {
337 		if (restrict_mask & RES_NOQUERY)
338 			return;			/* no query control */
339 		process_control(rbufp, restrict_mask);
340 		return;
341 	}
342 	if (rbufp->recv_length < LEN_PKT_NOMAC) {
343 		sys_badlength++;
344 		return;				/* runt packet */
345 	}
346 
347 	/*
348 	 * Validate mode. Note that NTPv1 is no longer supported.
349 	 */
350 	hismode = (int)PKT_MODE(pkt->li_vn_mode);
351 	if (hismode == MODE_UNSPEC) {
352 		sys_badlength++;
353 		return;				/* invalid mode */
354 	}
355 
356 	/*
357 	 * Discard broadcast packets received on the wildcard interface
358 	 * or if not enabled as broadcast client.
359 	 */
360 	if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
361 	    (rbufp->dstadr == any_interface || !sys_bclient))
362 		return;
363 
364 	/*
365 	 * Parse the extension field if present. We figure out whether
366 	 * an extension field is present by measuring the MAC size. If
367 	 * the number of words following the packet header is 0 or 1, no
368 	 * MAC is present and the packet is not authenticated. If 1, the
369 	 * packet is a reply to a previous request that failed to
370 	 * authenticate. If 3, the packet is authenticated with DES; if
371 	 * 5, the packet is authenticated with MD5. If greater than 5,
372 	 * an extension field is present. If 2 or 4, the packet is a
373 	 * runt and goes poof! with a brilliant flash.
374 	 */
375 	skeyid = 0;
376 #ifdef AUTOKEY
377 	pkeyid = tkeyid = 0;
378 #endif /* AUTOKEY */
379 	authlen = LEN_PKT_NOMAC;
380 	while ((has_mac = rbufp->recv_length - authlen) > 0) {
381 		int temp;
382 
383 		if (has_mac % 4 != 0 || has_mac < 0) {
384 			sys_badlength++;
385 			return;
386 		}
387 		if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
388 		    MAX_MAC_LEN) {
389 			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
390 			break;
391 
392 		} else if (has_mac > MAX_MAC_LEN) {
393 			temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
394 			    0xffff;
395 			if (temp < 4 || temp % 4 != 0) {
396 				sys_badlength++;
397 				return;
398 			}
399 			authlen += temp;
400 		} else {
401 			sys_badlength++;
402 			return;
403 		}
404 	}
405 
406 	/*
407 	 * We have tossed out as many buggy packets as possible early in
408 	 * the game to reduce the exposure to a clogging attack. Now we
409 	 * have to burn some cycles to find the association and
410 	 * authenticate the packet if required. Note that we burn only
411 	 * MD5 or DES cycles, again to reduce exposure. There may be no
412 	 * matching association and that's okay.
413 	 *
414 	 * More on the autokey mambo. Normally the local interface is
415 	 * found when the association was mobilized with respect to a
416 	 * designated remote address. We assume packets arriving from
417 	 * the remote address arrive via this interface and the local
418 	 * address used to construct the autokey is the unicast address
419 	 * of the interface. However, if the sender is a broadcaster,
420 	 * the interface broadcast address is used instead.
421 	 * Notwithstanding this technobabble, if the sender is a
422 	 * multicaster, the broadcast address is null, so we use the
423 	 * unicast address anyway. Don't ask.
424 	 */
425 	peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
426 	    hismode, &retcode);
427 	is_authentic = 0;
428 	dstadr_sin = &rbufp->dstadr->sin;
429 	if (has_mac == 0) {
430 #ifdef DEBUG
431 		if (debug)
432 			printf("receive: at %ld %s<-%s mode %d code %d\n",
433 			    current_time, ntoa(&rbufp->dstadr->sin),
434 			    ntoa(&rbufp->recv_srcadr), hismode, retcode);
435 #endif
436 	} else {
437 #ifdef AUTOKEY
438 		/*
439 		 * For autokey modes, generate the session key
440 		 * and install in the key cache. Use the socket
441 		 * broadcast or unicast address as appropriate.
442 		 */
443 		if (skeyid > NTP_MAXKEY) {
444 
445 			/*
446 			 * More on the autokey dance (AKD). A cookie is
447 			 * constructed from public and private values.
448 			 * For broadcast packets, the cookie is public
449 			 * (zero). For packets that match no
450 			 * association, the cookie is hashed from the
451 			 * addresses and private value. For server
452 			 * packets, the cookie was previously obtained
453 			 * from the server. For symmetric modes, the
454 			 * cookie was previously constructed using an
455 			 * agreement protocol; however, should PKI be
456 			 * unavailable, we construct a fake agreement as
457 			 * the EXOR of the peer and host cookies.
458 			 *
459 			 * hismode	ephemeral	persistent
460 			 * =======================================
461 			 * active	0		cookie#
462 			 * passive	0%		cookie#
463 			 * client	sys cookie	0%
464 			 * server	0%		sys cookie
465 			 * broadcast	0		0
466 			 *
467 			 * # if unsync, 0
468 			 * % can't happen
469 			 */
470 			if (hismode == MODE_BROADCAST) {
471 
472 				/*
473 				 * For broadcaster, use the interface
474 				 * broadcast address when available;
475 				 * otherwise, use the unicast address
476 				 * found when the association was
477 				 * mobilized.
478 				 */
479 				pkeyid = 0;
480 				if (rbufp->dstadr->bcast.sin_addr.s_addr
481 				    != 0)
482 					dstadr_sin =
483 					    &rbufp->dstadr->bcast;
484 			} else if (peer == NULL) {
485 				pkeyid = session_key(
486 				    &rbufp->recv_srcadr, dstadr_sin, 0,
487 				    sys_private, 0);
488 			} else {
489 				pkeyid = peer->pcookie.key;
490 			}
491 
492 			/*
493 			 * The session key includes both the public
494 			 * values and cookie. In case of an extension
495 			 * field, the cookie used for authentication
496 			 * purposes is zero. Note the hash is saved for
497 			 * use later in the autokey mambo.
498 			 */
499 			if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
500 				session_key(&rbufp->recv_srcadr,
501 				    dstadr_sin, skeyid, 0, 2);
502 				tkeyid = session_key(
503 				    &rbufp->recv_srcadr, dstadr_sin,
504 				    skeyid, pkeyid, 0);
505 			} else {
506 				tkeyid = session_key(
507 				    &rbufp->recv_srcadr, dstadr_sin,
508 				    skeyid, pkeyid, 2);
509 			}
510 
511 		}
512 #endif /* AUTOKEY */
513 
514 		/*
515 		 * Compute the cryptosum. Note a clogging attack may
516 		 * succeed in bloating the key cache. If an autokey,
517 		 * purge it immediately, since we won't be needing it
518 		 * again.
519 		 */
520 		if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
521 		    has_mac))
522 			is_authentic = 1;
523 		else
524 			sys_badauth++;
525 #ifdef AUTOKEY
526 		if (skeyid > NTP_MAXKEY)
527 			authtrust(skeyid, 0);
528 #endif /* AUTOKEY */
529 #ifdef DEBUG
530 		if (debug)
531 			printf(
532 			    "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
533 			    current_time, ntoa(dstadr_sin),
534 			    ntoa(&rbufp->recv_srcadr), hismode, retcode,
535 			    skeyid, authlen, has_mac,
536 			    is_authentic);
537 #endif
538 	}
539 
540 	/*
541 	 * The association matching rules are implemented by a set of
542 	 * routines and a table in ntp_peer.c. A packet matching an
543 	 * association is processed by that association. If not and
544 	 * certain conditions prevail, then an ephemeral association is
545 	 * mobilized: a broadcast packet mobilizes a broadcast client
546 	 * aassociation; a server packet mobilizes a client association;
547 	 * a symmetric active packet mobilizes a symmetric passive
548 	 * association. And, the adventure continues...
549 	 */
550 	switch (retcode) {
551 	case AM_FXMIT:
552 
553 		/*
554 		 * This is a client mode packet not matching a known
555 		 * association. If from a manycast client we run a few
556 		 * sanity checks before deciding to send a unicast
557 		 * server response. Otherwise, it must be a client
558 		 * request, so send a server response and go home.
559 		 */
560 		if (sys_manycastserver && (rbufp->dstadr->flags &
561 		    INT_MULTICAST)) {
562 
563 			/*
564 			 * We are picky about responding to a
565 			 * manycaster. There is no reason to respond to
566 			 * a request if our time is worse than the
567 			 * manycaster. We certainly don't reply if not
568 			 * synchronized to proventic time.
569 			 */
570 			if (sys_peer == NULL)
571 				return;
572 
573 			/*
574 			 * We don't reply if the our stratum is greater
575 			 * than the manycaster.
576 			 */
577 			if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
578 				return;
579 		}
580 
581 		/*
582 		 * Note that we don't require an authentication check
583 		 * here, since we can't set the system clock; but, we do
584 		 * set the key ID to zero to tell the caller about this.
585 		 */
586 		if (is_authentic)
587 			fast_xmit(rbufp, MODE_SERVER, skeyid,
588 			    restrict_mask);
589 		else
590 			fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
591 		return;
592 
593 	case AM_MANYCAST:
594 
595 		/*
596 		 * This is a server mode packet returned in response to
597 		 * a client mode packet sent to a multicast group
598 		 * address. The originate timestamp is a good nonce to
599 		 * reliably associate the reply with what was sent. If
600 		 * there is no match, that's curious and could be an
601 		 * intruder attempting to clog, so we just ignore it.
602 		 *
603 		 * First, make sure the packet is authentic. If so and
604 		 * the manycast association is found, we mobilize a
605 		 * client mode association, copy pertinent variables
606 		 * from the manycast to the client mode association and
607 		 * wind up the spring.
608 		 *
609 		 * There is an implosion hazard at the manycast client,
610 		 * since the manycast servers send the server packet
611 		 * immediately.
612 		 */
613 		if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
614 		    RES_NOPEER)) || (sys_authenticate &&
615 		    !is_authentic))
616 			return;
617 
618 		peer2 = findmanycastpeer(rbufp);
619 		if (peer2 == 0)
620 			return;
621 
622 		peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
623 		    MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
624 		    sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
625 		    (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
626 		    MDF_UCAST, 0, skeyid);
627 		if (peer == NULL)
628 			return;
629 		break;
630 
631 	case AM_NEWPASS:
632 
633 		/*
634 		 * This is the first packet received from a symmetric
635 		 * active peer. First, make sure the packet is
636 		 * authentic. If so, mobilize a symmetric passive
637 		 * association.
638 		 */
639 		if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
640 		    RES_NOPEER)) || (sys_authenticate &&
641 		    !is_authentic)) {
642 			fast_xmit(rbufp, MODE_PASSIVE, 0,
643 			    restrict_mask);
644 			return;
645 		}
646 		peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
647 		    MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
648 	 	    sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
649 		    FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
650 		if (peer == NULL)
651 			return;
652 		break;
653 
654 	case AM_NEWBCL:
655 
656 		/*
657 		 * This is the first packet received from a broadcast
658 		 * server. First, make sure the packet is authentic, not
659 		 * restricted and that we are a broadcast or multicast
660 		 * client. If so, mobilize a broadcast client
661 		 * association.
662 		 */
663 		if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
664 		    RES_NOPEER)) || (sys_authenticate &&
665 		    !is_authentic) || !sys_bclient)
666 			return;
667 
668 		peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
669 		    MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
670 		    sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
671 		    FLAG_IBURST | (sys_authenticate ?
672 		    FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
673 #ifdef AUTOKEY
674 #ifdef PUBKEY
675 		if (peer == NULL)
676 			return;
677 		if (peer->flags & FLAG_SKEY)
678 			crypto_recv(peer, rbufp);
679 #endif /* PUBKEY */
680 #endif /* AUTOKEY */
681 		return;
682 
683 	case AM_POSSBCL:
684 	case AM_PROCPKT:
685 
686 		/*
687 		 * Happiness and nothing broke. Earn some revenue.
688 		 */
689 		break;
690 
691 	default:
692 
693 		/*
694 		 * Invalid mode combination. Leave the island
695 		 * immediately.
696 		 */
697 #ifdef DEBUG
698 		if (debug)
699 			printf("receive: bad protocol %d\n", retcode);
700 #endif
701 		return;
702 	}
703 
704 	/*
705 	 * If the peer isn't configured, set his authenable and autokey
706 	 * status based on the packet. Once the status is set, it can't
707 	 * be unset. It seems like a silly idea to do this here, rather
708 	 * in the configuration routine, but in some goofy cases the
709 	 * first packet sent cannot be authenticated and we need a way
710 	 * for the dude to change his mind.
711 	 */
712 	oflags = peer->flags;
713 	peer->timereceived = current_time;
714 	peer->received++;
715 	if (!(peer->flags & FLAG_CONFIG) && has_mac) {
716 		peer->flags |= FLAG_AUTHENABLE;
717 #ifdef AUTOKEY
718 		if (skeyid > NTP_MAXKEY)
719 			peer->flags |= FLAG_SKEY;
720 #endif /* AUTOKEY */
721 	}
722 
723 	/*
724 	 * A valid packet must be from an authentic and allowed source.
725 	 * All packets must pass the authentication allowed tests.
726 	 * Autokey authenticated packets must pass additional tests and
727 	 * public-key authenticated packets must have the credentials
728 	 * verified. If all tests are passed, the packet is forwarded
729 	 * for processing. If not, the packet is discarded and the
730 	 * association demobilized if appropriate.
731 	 */
732 	peer->flash = 0;
733 	if (is_authentic) {
734 		peer->flags |= FLAG_AUTHENTIC;
735 	} else {
736 		peer->flags &= ~FLAG_AUTHENTIC;
737 	}
738 	if (peer->hmode == MODE_BROADCAST &&
739 	    (restrict_mask & RES_DONTTRUST))	/* test 4 */
740 		peer->flash |= TEST4;		/* access denied */
741 	if (peer->flags & FLAG_AUTHENABLE) {
742 		if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
743 			peer->flash |= TEST5;	/* auth failed */
744 		else if (!(oflags & FLAG_AUTHENABLE))
745 			report_event(EVNT_PEERAUTH, peer);
746 	}
747 	if (peer->flash) {
748 #ifdef DEBUG
749 		if (debug)
750 			printf("receive: bad auth %03x\n", peer->flash);
751 #endif
752 		return;
753 	}
754 
755 #ifdef AUTOKEY
756 	/*
757 	 * More autokey dance. The rules of the cha-cha are as follows:
758 	 *
759 	 * 1. If there is no key or the key is not auto, do nothing.
760 	 *
761 	 * 2. If an extension field contains a verified signature, it is
762 	 *    self-authenticated and we sit the dance.
763 	 *
764 	 * 3. If this is a server reply, check only to see that the
765 	 *    transmitted key ID matches the received key ID.
766 	 *
767 	 * 4. Check to see that one or more hashes of the current key ID
768 	 *    matches the previous key ID or ultimate original key ID
769 	 *    obtained from the broadcaster or symmetric peer. If no
770 	 *    match, sit the dance and wait for timeout.
771 	 */
772 	if (peer->flags & FLAG_SKEY) {
773 		peer->flash |= TEST10;
774 		crypto_recv(peer, rbufp);
775 		poll_update(peer, peer->hpoll);
776 		if (hismode == MODE_SERVER) {
777 			if (skeyid == peer->keyid)
778 				peer->flash &= ~TEST10;
779 		} else if (!peer->flash & TEST10) {
780 			peer->pkeyid = skeyid;
781 		} else {
782 			int i;
783 
784 			for (i = 0; ; i++) {
785 				if (tkeyid == peer->pkeyid ||
786 				    tkeyid == peer->recauto.key) {
787 					peer->flash &= ~TEST10;
788 					peer->pkeyid = skeyid;
789 					break;
790 				}
791 				if (i > peer->recauto.seq)
792 					break;
793 				tkeyid = session_key(
794 				    &rbufp->recv_srcadr, dstadr_sin,
795 				    tkeyid, pkeyid, 0);
796 			}
797 		}
798 #ifdef PUBKEY
799 
800 		/*
801 		 * This is delicious. Ordinarily, we kick out all errors
802 		 * at this point; however, in symmetric mode and just
803 		 * warming up, an unsynchronized peer must inject the
804 		 * timestamps, even if it fails further up the road. So,
805 		 * let the dude by here, but only if the jerk is not yet
806 		 * reachable. After that, he's on his own.
807 		 */
808 		if (!(peer->flags & FLAG_PROVEN))
809 			peer->flash |= TEST11;
810 		if (peer->flash && peer->reach) {
811 #ifdef DEBUG
812 			if (debug)
813 				printf("packet: bad autokey %03x\n",
814 				    peer->flash);
815 #endif
816 			return;
817 		}
818 #endif /* PUBKEY */
819 	}
820 #endif /* AUTOKEY */
821 
822 	/*
823 	 * We have survived the gaunt. Forward to the packet routine. If
824 	 * a symmetric passive association has been mobilized and the
825 	 * association doesn't deserve to live, it will die in the
826 	 * transmit routine if not reachable after timeout.
827 	 */
828 	process_packet(peer, pkt, &rbufp->recv_time);
829 }
830 
831 
832 /*
833  * process_packet - Packet Procedure, a la Section 3.4.4 of the
834  *	specification. Or almost, at least. If we're in here we have a
835  *	reasonable expectation that we will be having a long term
836  *	relationship with this host.
837  */
838 void
839 process_packet(
840 	register struct peer *peer,
841 	register struct pkt *pkt,
842 	l_fp *recv_ts
843 	)
844 {
845 	l_fp t10, t23;
846 	double p_offset, p_del, p_disp;
847 	double dtemp;
848 	l_fp p_rec, p_xmt, p_org, p_reftime;
849 	l_fp ci;
850 	int pmode, pleap, pstratum;
851 
852 	/*
853 	 * Swap header fields and keep the books. The books amount to
854 	 * the receive timestamp and poll interval in the header. We
855 	 * need these even if there are other problems in order to crank
856 	 * up the state machine.
857 	 */
858 	sys_processed++;
859 	peer->processed++;
860 	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
861 	p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
862 	NTOHL_FP(&pkt->reftime, &p_reftime);
863 	NTOHL_FP(&pkt->rec, &p_rec);
864 	NTOHL_FP(&pkt->xmt, &p_xmt);
865 	if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST)
866 		NTOHL_FP(&pkt->org, &p_org);
867 	else
868 		p_org = peer->rec;
869 
870 	/*
871 	 * Test for old, duplicate or unsynch packets (tests 1-3).
872 	 */
873 	peer->rec = *recv_ts;
874 	pmode = PKT_MODE(pkt->li_vn_mode);
875 	pleap = PKT_LEAP(pkt->li_vn_mode);
876 	pstratum = PKT_TO_STRATUM(pkt->stratum);
877 	if (L_ISHIS(&peer->org, &p_xmt))	/* count old packets */
878 		peer->oldpkt++;
879 	if (L_ISEQU(&peer->org, &p_xmt))	/* 1 */
880 		peer->flash |= TEST1;		/* dupe */
881 	if (pmode != MODE_BROADCAST) {
882 		if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
883 			peer->flash |= TEST2;	/* bogus */
884 		if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
885 			peer->flash |= TEST3;	/* unsynch */
886 	}
887 	if (L_ISZERO(&p_xmt))			/* 3 */
888 		peer->flash |= TEST3;		/* unsynch */
889 	peer->org = p_xmt;
890 
891 	/*
892 	 * If tests 1-3 fail, the packet is discarded leaving only the
893 	 * receive and origin timestamps and poll interval, which is
894 	 * enough to get the protocol started.
895 	 */
896 	if (peer->flash) {
897 #ifdef DEBUG
898 		if (debug)
899 			printf("packet: bad data %03x\n",
900 			    peer->flash);
901 #endif
902 		return;
903 	}
904 
905 	/*
906 	 * A kiss-of-death (kod) packet is returned by a server in case
907 	 * the client is denied access. It consists of the client
908 	 * request packet with the leap bits indicating never
909 	 * synchronized, stratum zero and reference ID field the ASCII
910 	 * string "DENY". If the packet originate timestamp matches the
911 	 * association transmit timestamp the kod is legitimate. If the
912 	 * peer leap bits indicate never synchronized, this must be
913 	 * access deny and the association is disabled; otherwise this
914 	 * must be a limit reject. In either case a naughty message is
915 	 * forced to the system log.
916 	 */
917 	if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
918 	    memcmp(&pkt->refid, "DENY", 4) == 0) {
919 		if (peer->leap == LEAP_NOTINSYNC) {
920 			peer->stratum = STRATUM_UNSPEC;
921 			peer->flash |= TEST4;
922 			memcpy(&peer->refid, &pkt->refid, 4);
923 			msyslog(LOG_INFO, "access denied");
924 		} else {
925 			msyslog(LOG_INFO, "limit reject");
926 		}
927 		return;
928 	}
929 
930 	/*
931 	 * Test for valid peer data (tests 6-8)
932 	 */
933 	ci = p_xmt;
934 	L_SUB(&ci, &p_reftime);
935 	LFPTOD(&ci, dtemp);
936 	if (pleap == LEAP_NOTINSYNC ||		/* 6 */
937 	    pstratum >= STRATUM_UNSPEC || dtemp < 0)
938 		peer->flash |= TEST6;		/* bad synch */
939 	if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
940 		if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
941 			peer->flash |= TEST7;	/* bad stratum */
942 			sys_badstratum++;
943 		}
944 	}
945 	if (p_del < 0 || p_disp < 0 || p_del /	/* 8 */
946 	    2 + p_disp >= MAXDISPERSE)
947 		peer->flash |= TEST8;		/* bad peer distance */
948 	if (peer->flash) {
949 #ifdef DEBUG
950 		if (debug)
951 			printf("packet: bad header %03x\n",
952 			    peer->flash);
953 #endif
954 		return;
955 	}
956 
957 	/*
958 	 * The header is valid. Capture the remaining header values and
959 	 * mark as reachable.
960 	 */
961 	record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
962 	    &p_rec, &p_xmt, &peer->rec);
963 	peer->leap = pleap;
964 	peer->pmode = pmode;
965 	peer->stratum = pstratum;
966 	peer->ppoll = pkt->ppoll;
967 	peer->precision = pkt->precision;
968 	peer->rootdelay = p_del;
969 	peer->rootdispersion = p_disp;
970 	peer->refid = pkt->refid;
971 	peer->reftime = p_reftime;
972 	if (!(peer->reach)) {
973 		report_event(EVNT_REACH, peer);
974 		peer->timereachable = current_time;
975 	}
976 	peer->reach |= 1;
977 	peer->unreach = 0;
978 	poll_update(peer, peer->hpoll);
979 
980 	/*
981 	 * If running in a client/server association, calculate the
982 	 * clock offset c, roundtrip delay d and dispersion e. We use
983 	 * the equations (reordered from those in the spec). Note that,
984 	 * in a broadcast association, org has been set to the time of
985 	 * last reception. Note the computation of dispersion includes
986 	 * the system precision plus that due to the frequency error
987 	 * since the originate time.
988 	 *
989 	 * c = ((t2 - t3) + (t1 - t0)) / 2
990 	 * d = (t2 - t3) - (t1 - t0)
991 	 * e = (org - rec) (seconds only)
992 	 */
993 	t10 = p_xmt;			/* compute t1 - t0 */
994 	L_SUB(&t10, &peer->rec);
995 	t23 = p_rec;			/* compute t2 - t3 */
996 	L_SUB(&t23, &p_org);
997 	ci = t10;
998 	p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
999 
1000 	/*
1001 	 * If running in a broadcast association, the clock offset is
1002 	 * (t1 - t0) corrected by the one-way delay, but we can't
1003 	 * measure that directly. Therefore, we start up in MODE_CLIENT
1004 	 * mode, set FLAG_MCAST and exchange eight messages to determine
1005 	 * the clock offset. When the last message is sent, we switch to
1006 	 * MODE_BCLIENT mode. The next broadcast message after that
1007 	 * computes the broadcast offset and clears FLAG_MCAST.
1008 	 */
1009 	if (pmode == MODE_BROADCAST) {
1010 		if (peer->flags & FLAG_MCAST) {
1011 			LFPTOD(&ci, p_offset);
1012 			peer->estbdelay = peer->offset - p_offset;
1013 			if (peer->hmode == MODE_CLIENT)
1014 				return;
1015 
1016 			peer->flags &= ~FLAG_MCAST;
1017 		}
1018 		DTOLFP(peer->estbdelay, &t10);
1019 		L_ADD(&ci, &t10);
1020 		p_del = peer->delay;
1021 	} else {
1022 		L_ADD(&ci, &t23);
1023 		L_RSHIFT(&ci);
1024 		L_SUB(&t23, &t10);
1025 		LFPTOD(&t23, p_del);
1026 	}
1027 	p_del = max(p_del, LOGTOD(sys_precision));
1028 	LFPTOD(&ci, p_offset);
1029 	if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1030 	    p_disp >= MAXDISPERSE)		/* 9 */
1031 		peer->flash |= TEST9;		/* bad peer distance */
1032 
1033 	/*
1034 	 * If any flasher bits remain set at this point, abandon ship.
1035 	 * Otherwise, forward to the clock filter.
1036 	 */
1037 	if (peer->flash) {
1038 #ifdef DEBUG
1039 		if (debug)
1040 			printf("packet: bad packet data %03x\n",
1041 			    peer->flash);
1042 #endif
1043 		return;
1044 	}
1045 	clock_filter(peer, p_offset, p_del, p_disp);
1046 	clock_select();
1047 	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1048 	    peer->offset, peer->delay, peer->disp,
1049 	    SQRT(peer->jitter));
1050 }
1051 
1052 
1053 /*
1054  * clock_update - Called at system process update intervals.
1055  */
1056 static void
1057 clock_update(void)
1058 {
1059 	u_char oleap;
1060 	u_char ostratum;
1061 
1062 	/*
1063 	 * Reset/adjust the system clock. Do this only if there is a
1064 	 * system peer and we haven't seen that peer lately. Watch for
1065 	 * timewarps here.
1066 	 */
1067 	if (sys_peer == NULL)
1068 		return;
1069 	if (sys_peer->pollsw == FALSE || sys_peer->burst > 0)
1070 		return;
1071 	sys_peer->pollsw = FALSE;
1072 #ifdef DEBUG
1073 	if (debug)
1074 		printf("clock_update: at %ld assoc %d \n", current_time,
1075 		    peer_associations);
1076 #endif
1077 	oleap = sys_leap;
1078 	ostratum = sys_stratum;
1079 	switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1080 
1081 	/*
1082 	 * Clock is too screwed up. Just exit for now.
1083 	 */
1084 	case -1:
1085 		report_event(EVNT_SYSFAULT, (struct peer *)0);
1086 		exit(1);
1087 		/*NOTREACHED*/
1088 
1089 	/*
1090 	 * Clock was stepped. Flush all time values of all peers.
1091 	 */
1092 	case 1:
1093 		clear_all();
1094 		sys_peer = NULL;
1095 		sys_stratum = STRATUM_UNSPEC;
1096 		sys_poll = NTP_MINPOLL;
1097 		NLOG(NLOG_SYNCSTATUS)
1098 		    msyslog(LOG_INFO, "synchronisation lost");
1099 		report_event(EVNT_CLOCKRESET, (struct peer *)0);
1100 		break;
1101 
1102 	/*
1103 	 * Update the system stratum, leap bits, root delay, root
1104 	 * dispersion, reference ID and reference time. We also update
1105 	 * select dispersion and max frequency error. If the leap
1106 	 * changes, we gotta reroll the keys.
1107 	 */
1108 	default:
1109 		sys_stratum = sys_peer->stratum + 1;
1110 		if (sys_stratum == 1)
1111 			sys_refid = sys_peer->refid;
1112 		else
1113 			sys_refid = sys_peer->srcadr.sin_addr.s_addr;
1114 		sys_reftime = sys_peer->rec;
1115 		sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1116 		sys_leap = leap_consensus;
1117 	}
1118 	if (oleap == LEAP_NOTINSYNC) {
1119 		report_event(EVNT_SYNCCHG, (struct peer *)0);
1120 #ifdef AUTOKEY
1121 		expire_all();
1122 #endif /* AUTOKEY */
1123 	}
1124 	if (ostratum != sys_stratum)
1125 		report_event(EVNT_PEERSTCHG, (struct peer *)0);
1126 }
1127 
1128 
1129 /*
1130  * poll_update - update peer poll interval
1131  */
1132 void
1133 poll_update(
1134 	struct peer *peer,
1135 	int hpoll
1136 	)
1137 {
1138 #ifdef AUTOKEY
1139 	int oldpoll;
1140 #endif /* AUTOKEY */
1141 
1142 	/*
1143 	 * A little foxtrot to determine what controls the poll
1144 	 * interval. If the peer is reachable, but the last four polls
1145 	 * have not been answered, use the minimum. If declared
1146 	 * truechimer, use the system poll interval. This allows each
1147 	 * association to ramp up the poll interval for useless sources
1148 	 * and to clamp it to the minimum when first starting up.
1149 	 */
1150 #ifdef AUTOKEY
1151 	oldpoll = peer->kpoll;
1152 #endif /* AUTOKEY */
1153 	if (hpoll > peer->maxpoll)
1154 		peer->hpoll = peer->maxpoll;
1155 	else if (hpoll < peer->minpoll)
1156 		peer->hpoll = peer->minpoll;
1157 	else
1158 		peer->hpoll = hpoll;
1159 
1160 	/*
1161 	 * Bit of adventure here. If during a burst and not timeout,
1162 	 * just slink away. If timeout, figure what the next timeout
1163 	 * should be. If IBURST or a reference clock, use one second. If
1164 	 * not and the dude was reachable during the previous poll
1165 	 * interval, randomize over 1-4 seconds; otherwise, randomize
1166 	 * over 15-18 seconds. This is to give time for a modem to
1167 	 * complete the call, for example. If not during a burst,
1168 	 * randomize over the poll interval -1 to +2 seconds.
1169 	 *
1170 	 * In case of manycast server, make the poll interval, which is
1171 	 * axtually the manycast beacon interval, eight times the system
1172 	 * poll interval. Normally when the host poll interval settles
1173 	 * up to 17.1 s, the beacon interval settles up to 2.3 hours.
1174 	 */
1175 	if (peer->burst > 0) {
1176 		if (peer->nextdate != current_time)
1177 			return;
1178 #ifdef REFCLOCK
1179 		else if (peer->flags & FLAG_REFCLOCK)
1180 			peer->nextdate++;
1181 #endif
1182 		else if (peer->reach & 0x1)
1183 			peer->nextdate += RANDPOLL(BURST_INTERVAL2);
1184 		else
1185 			peer->nextdate += RANDPOLL(BURST_INTERVAL1);
1186 	} else if (peer->cast_flags & MDF_ACAST) {
1187 		if (sys_survivors < NTP_MINCLOCK)
1188 			peer->kpoll = peer->hpoll;
1189 		else
1190 			peer->kpoll = peer->hpoll + 3;
1191 		peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1192 	} else {
1193 		peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1194 		    peer->minpoll);
1195 		peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1196 	}
1197 	if (peer->nextdate < current_time)
1198 		peer->nextdate = current_time;
1199 #ifdef AUTOKEY
1200 	/*
1201 	 * Bit of crass arrogance at this point. If the poll interval
1202 	 * has changed and we have a keylist, the lifetimes in the
1203 	 * keylist are probably bogus. In this case purge the keylist
1204 	 * and regenerate it later.
1205 	 */
1206 	if (peer->kpoll != oldpoll)
1207 		key_expire(peer);
1208 #endif /* AUTOKEY */
1209 #ifdef DEBUG
1210 	if (debug > 1)
1211 		printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1212 		    current_time, ntoa(&peer->srcadr), peer->flags,
1213 		    peer->kpoll, peer->burst, peer->outdate,
1214 		    peer->nextdate);
1215 #endif
1216 }
1217 
1218 
1219 /*
1220  * clear - clear peer filter registers.  See Section 3.4.8 of the spec.
1221  */
1222 void
1223 peer_clear(
1224 	register struct peer *peer
1225 	)
1226 {
1227 	register int i;
1228 	u_long u_rand;
1229 
1230 	/*
1231 	 * If cryptographic credentials have been acquired, toss them to
1232 	 * Valhalla. Note that autokeys are ephemeral, in that they are
1233 	 * tossed immediately upon use. Therefore, the keylist can be
1234 	 * purged anytime without needing to preserve random keys. Note
1235 	 * that, if the peer is purged, the cryptographic variables are
1236 	 * purged, too. This makes it much harder to sneak in some
1237 	 * unauthenticated data in the clock filter.
1238 	 */
1239 #ifdef DEBUG
1240 	if (debug)
1241 		printf("peer_clear: at %ld assoc ID %d\n", current_time,
1242 		    peer->associd);
1243 #endif
1244 #ifdef AUTOKEY
1245 	key_expire(peer);
1246 #ifdef PUBKEY
1247 	if (peer->keystr != NULL)
1248 		free(peer->keystr);
1249 	if (peer->pubkey.ptr != NULL)
1250 		free(peer->pubkey.ptr);
1251 	if (peer->certif.ptr != NULL)
1252 		free(peer->certif.ptr);
1253 #endif /* PUBKEY */
1254 #endif /* AUTOKEY */
1255 	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1256 
1257 	/*
1258 	 * If he dies as a broadcast client, he comes back to life as
1259 	 * a broadcast client in client mode in order to recover the
1260 	 * initial autokey values. Note that there is no need to call
1261 	 * clock_select(), since the perp has already been voted off
1262 	 * the island at this point.
1263 	 */
1264 	if (peer->cast_flags & MDF_BCLNT) {
1265 		peer->flags |= FLAG_MCAST;
1266 		peer->hmode = MODE_CLIENT;
1267 	}
1268 	peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1269 	peer->estbdelay = sys_bdelay;
1270 	peer->hpoll = peer->kpoll = peer->minpoll;
1271 	peer->ppoll = peer->maxpoll;
1272 	peer->pollsw = FALSE;
1273 	peer->jitter = MAXDISPERSE;
1274 	peer->epoch = current_time;
1275 #ifdef REFCLOCK
1276 	if (!(peer->flags & FLAG_REFCLOCK)) {
1277 		peer->leap = LEAP_NOTINSYNC;
1278 		peer->stratum = STRATUM_UNSPEC;
1279 	}
1280 #endif
1281 	for (i = 0; i < NTP_SHIFT; i++) {
1282 		peer->filter_order[i] = i;
1283 		peer->filter_disp[i] = MAXDISPERSE;
1284 		peer->filter_epoch[i] = current_time;
1285 	}
1286 
1287 	/*
1288 	 * Randomize the first poll over 1-16s to avoid bunching.
1289 	 */
1290 	peer->update = peer->outdate = current_time;
1291 	u_rand = RANDOM;
1292 	peer->nextdate = current_time + (u_rand & ((1 <<
1293 	    BURST_INTERVAL1) - 1)) + 1;
1294 }
1295 
1296 
1297 /*
1298  * clock_filter - add incoming clock sample to filter register and run
1299  *		  the filter procedure to find the best sample.
1300  */
1301 void
1302 clock_filter(
1303 	register struct peer *peer,	/* peer structure pointer */
1304 	double sample_offset,		/* clock offset */
1305 	double sample_delay,		/* roundtrip delay */
1306 	double sample_disp		/* dispersion */
1307 	)
1308 {
1309 	double dst[NTP_SHIFT];		/* distance vector */
1310 	int ord[NTP_SHIFT];		/* index vector */
1311 	register int i, j, k, m;
1312 	double dsp, jit, dtemp, etemp;
1313 
1314 	/*
1315 	 * Shift the new sample into the register and discard the oldest
1316 	 * one. The new offset and delay come directly from the
1317 	 * timestamp calculations. The dispersion grows from the last
1318 	 * outbound packet or reference clock update to the present time
1319 	 * and increased by the sum of the peer precision and the system
1320 	 * precision. The delay can sometimes swing negative due to
1321 	 * frequency skew, so it is clamped non-negative.
1322 	 */
1323 	dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1324 	    sample_disp, MAXDISPERSE);
1325 	j = peer->filter_nextpt;
1326 	peer->filter_offset[j] = sample_offset;
1327 	peer->filter_delay[j] = max(0, sample_delay);
1328 	peer->filter_disp[j] = dsp;
1329 	peer->filter_epoch[j] = current_time;
1330 	j++; j %=NTP_SHIFT;
1331 	peer->filter_nextpt = j;
1332 
1333 	/*
1334 	 * Update dispersions since the last update and at the same
1335 	 * time initialize the distance and index lists. The distance
1336 	 * list uses a compound metric. If the sample is valid and
1337 	 * younger than the minimum Allan intercept, use delay;
1338 	 * otherwise, use biased dispersion.
1339 	 */
1340 	dtemp = clock_phi * (current_time - peer->update);
1341 	peer->update = current_time;
1342 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
1343 		if (i != 0) {
1344 			peer->filter_disp[j] += dtemp;
1345 			if (peer->filter_disp[j] > MAXDISPERSE)
1346 				peer->filter_disp[j] = MAXDISPERSE;
1347 		}
1348 		if (peer->filter_disp[j] >= MAXDISPERSE)
1349 			dst[i] = MAXDISPERSE;
1350 		else if (peer->update - peer->filter_epoch[j] >
1351 		    allan_xpt)
1352 			dst[i] = MAXDISTANCE + peer->filter_disp[j];
1353 		else
1354  			dst[i] = peer->filter_delay[j];
1355 		ord[i] = j;
1356 		j++; j %= NTP_SHIFT;
1357 	}
1358 
1359         /*
1360 	 * Sort the samples in both lists by distance.
1361 	 */
1362 	for (i = 1; i < NTP_SHIFT; i++) {
1363 		for (j = 0; j < i; j++) {
1364 			if (dst[j] > dst[i]) {
1365 				k = ord[j];
1366 				ord[j] = ord[i];
1367 				ord[i] = k;
1368 				etemp = dst[j];
1369 				dst[j] = dst[i];
1370 				dst[i] = etemp;
1371 			}
1372 		}
1373 	}
1374 
1375 	/*
1376 	 * Copy the index list to the association structure so ntpq
1377 	 * can see it later. Prune the distance list to samples less
1378 	 * than MAXDISTANCE, but keep at least two valid samples for
1379 	 * jitter calculation.
1380 	 */
1381 	m = 0;
1382 	for (i = 0; i < NTP_SHIFT; i++) {
1383 		peer->filter_order[i] = ord[i];
1384 		if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1385 		    MAXDISTANCE))
1386 			continue;
1387 		m++;
1388 	}
1389 
1390 	/*
1391 	 * Compute the dispersion and jitter squares. The dispersion
1392 	 * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1393 	 * normalized close to 1.0. The jitter is the mean of the square
1394 	 * differences relative to the lowest delay sample. If no
1395 	 * acceptable samples remain in the shift register, quietly
1396 	 * tiptoe home leaving only the
1397 	 * dispersion.
1398 	 */
1399 	jit = 0;
1400 	peer->disp = 0;
1401 	k = ord[0];
1402 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
1403 
1404 		j = ord[i];
1405 		peer->disp = NTP_FWEIGHT * (peer->disp +
1406 		    peer->filter_disp[j]);
1407 		if (i < m)
1408 			jit += DIFF(peer->filter_offset[j],
1409 			    peer->filter_offset[k]);
1410 	}
1411 
1412 	/*
1413 	 * If no acceptable samples remain in the shift register,
1414 	 * quietly tiptoe home leaving only the dispersion. Otherwise,
1415 	 * save the offset, delay and jitter average. Note the jitter
1416 	 * must not be less than the system precision.
1417 	 */
1418 	if (m == 0)
1419 		return;
1420 	etemp = peer->offset;
1421 	peer->offset = peer->filter_offset[k];
1422 	peer->delay = peer->filter_delay[k];
1423 	if (m > 1)
1424 		jit /= m - 1;
1425 	peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1426 
1427 	/*
1428 	 * A new sample is useful only if it is younger than the last
1429 	 * one used.
1430 	 */
1431 	if (peer->filter_epoch[k] <= peer->epoch) {
1432 #ifdef DEBUG
1433 		if (debug)
1434 			printf("clock_filter: discard %lu\n",
1435 			    peer->epoch - peer->filter_epoch[k]);
1436 #endif
1437 		return;
1438 	}
1439 
1440 	/*
1441 	 * If the difference between the last offset and the current one
1442 	 * exceeds the jitter by CLOCK_SGATE (4) and the interval since
1443 	 * the last update is less than twice the system poll interval,
1444 	 * consider the update a popcorn spike and ignore it.
1445 	 */
1446 	if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
1447 	    CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
1448 	    (1 << (sys_poll + 1))) {
1449 #ifdef DEBUG
1450 		if (debug)
1451 			printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
1452 			    m, peer->offset, SQRT(peer->jitter));
1453 #endif
1454 		return;
1455 	}
1456 
1457 	/*
1458 	 * The mitigated sample statistics are saved for later
1459 	 * processing, but can be processed only once.
1460 	 */
1461 	peer->epoch = peer->filter_epoch[k];
1462 	peer->pollsw = TRUE;
1463 #ifdef DEBUG
1464 	if (debug)
1465 		printf(
1466 		    "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1467 		    m, peer->offset, peer->delay, peer->disp,
1468 		    SQRT(peer->jitter), peer->update - peer->epoch);
1469 #endif
1470 }
1471 
1472 
1473 /*
1474  * clock_select - find the pick-of-the-litter clock
1475  */
1476 void
1477 clock_select(void)
1478 {
1479 	register struct peer *peer;
1480 	int i, j, k, n;
1481 	int nreach, nlist, nl3;
1482 	double d, e, f;
1483 	int allow, found, sw;
1484 	double high, low;
1485 	double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1486 	struct peer *osys_peer;
1487 	struct peer *typeacts = NULL;
1488 	struct peer *typelocal = NULL;
1489 	struct peer *typepps = NULL;
1490 	struct peer *typesystem = NULL;
1491 
1492 	static int list_alloc = 0;
1493 	static struct endpoint *endpoint = NULL;
1494 	static int *indx = NULL;
1495 	static struct peer **peer_list = NULL;
1496 	static u_int endpoint_size = 0;
1497 	static u_int indx_size = 0;
1498 	static u_int peer_list_size = 0;
1499 
1500 	/*
1501 	 * Initialize and create endpoint, index and peer lists big
1502 	 * enough to handle all associations.
1503 	 */
1504 	osys_peer = sys_peer;
1505 	sys_peer = NULL;
1506 	sys_prefer = NULL;
1507 	nreach = nlist = 0;
1508 	low = 1e9;
1509 	high = -1e9;
1510 	for (n = 0; n < HASH_SIZE; n++)
1511 		nlist += peer_hash_count[n];
1512 	if (nlist > list_alloc) {
1513 		if (list_alloc > 0) {
1514 			free(endpoint);
1515 			free(indx);
1516 			free(peer_list);
1517 		}
1518 		while (list_alloc < nlist) {
1519 			list_alloc += 5;
1520 			endpoint_size += 5 * 3 * sizeof(*endpoint);
1521 			indx_size += 5 * 3 * sizeof(*indx);
1522 			peer_list_size += 5 * sizeof(*peer_list);
1523 		}
1524 		endpoint = (struct endpoint *)emalloc(endpoint_size);
1525 		indx = (int *)emalloc(indx_size);
1526 		peer_list = (struct peer **)emalloc(peer_list_size);
1527 	}
1528 
1529 	/*
1530 	 * Initially, we populate the island with all the rifraff peers
1531 	 * that happen to be lying around. Those with seriously
1532 	 * defective clocks are immediately booted off the island. Then,
1533 	 * the falsetickers are culled and put to sea. The truechimers
1534 	 * remaining are subject to repeated rounds where the most
1535 	 * unpopular at each round is kicked off. When the population
1536 	 * has dwindled to NTP_MINCLOCK (3), the survivors split a
1537 	 * million bucks and collectively crank the chimes.
1538 	 */
1539 	nlist = nl3 = 0;	/* none yet */
1540 	for (n = 0; n < HASH_SIZE; n++) {
1541 		for (peer = peer_hash[n]; peer != NULL; peer =
1542 		    peer->next) {
1543 			peer->flags &= ~FLAG_SYSPEER;
1544 			peer->status = CTL_PST_SEL_REJECT;
1545 
1546 			/*
1547 			 * A peer leaves the island immediately if
1548 			 * unreachable, synchronized to us or suffers
1549 			 * excessive root distance. Careful with the
1550 			 * root distance, since the poll interval can
1551 			 * increase to a day and a half.
1552 			 */
1553 			if (!peer->reach || (peer->stratum > 1 &&
1554 			    peer->refid ==
1555 			    peer->dstadr->sin.sin_addr.s_addr) ||
1556 			    peer->stratum >= STRATUM_UNSPEC ||
1557 			    (root_distance(peer) >= MAXDISTANCE + 2 *
1558 			    clock_phi * ULOGTOD(sys_poll)))
1559 				continue;
1560 
1561 			/*
1562 			 * Don't allow the local clock or modem drivers
1563 			 * in the kitchen at this point, unless the
1564 			 * prefer peer. Do that later, but only if
1565 			 * nobody else is around. These guys are all
1566 			 * configured, so we never throw them away.
1567 			 */
1568 			if (peer->refclktype == REFCLK_LOCALCLOCK
1569 #if defined(VMS) && defined(VMS_LOCALUNIT)
1570 				/* wjm: local unit VMS_LOCALUNIT taken seriously */
1571 				&& REFCLOCKUNIT(&peer->srcadr) != VMS_LOCALUNIT
1572 #endif	/* VMS && VMS_LOCALUNIT */
1573 				) {
1574 				typelocal = peer;
1575 				if (!(peer->flags & FLAG_PREFER))
1576 					continue; /* no local clock */
1577 			}
1578 			if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1579 				typeacts = peer;
1580 				if (!(peer->flags & FLAG_PREFER))
1581 					continue; /* no acts */
1582 			}
1583 
1584 			/*
1585 			 * If we get this far, the peer can stay on the
1586 			 * island, but does not yet have the immunity
1587 			 * idol.
1588 			 */
1589 			nreach++;
1590 			peer->status = CTL_PST_SEL_SANE;
1591 			peer_list[nlist++] = peer;
1592 
1593 			/*
1594 			 * Insert each interval endpoint on the sorted
1595 			 * list.
1596 			 */
1597 			e = peer->offset;	 /* Upper end */
1598 			f = root_distance(peer);
1599 			e = e + f;
1600 			for (i = nl3 - 1; i >= 0; i--) {
1601 				if (e >= endpoint[indx[i]].val)
1602 					break;
1603 				indx[i + 3] = indx[i];
1604 			}
1605 			indx[i + 3] = nl3;
1606 			endpoint[nl3].type = 1;
1607 			endpoint[nl3++].val = e;
1608 
1609 			e = e - f;		/* Center point */
1610 			for ( ; i >= 0; i--) {
1611 				if (e >= endpoint[indx[i]].val)
1612 					break;
1613 				indx[i + 2] = indx[i];
1614 			}
1615 			indx[i + 2] = nl3;
1616 			endpoint[nl3].type = 0;
1617 			endpoint[nl3++].val = e;
1618 
1619 			e = e - f;		/* Lower end */
1620 			for ( ; i >= 0; i--) {
1621 				if (e >= endpoint[indx[i]].val)
1622 					break;
1623 				indx[i + 1] = indx[i];
1624 			}
1625 			indx[i + 1] = nl3;
1626 			endpoint[nl3].type = -1;
1627 			endpoint[nl3++].val = e;
1628 		}
1629 	}
1630 #ifdef DEBUG
1631 	if (debug > 2)
1632 		for (i = 0; i < nl3; i++)
1633 			printf("select: endpoint %2d %.6f\n",
1634 			   endpoint[indx[i]].type,
1635 			   endpoint[indx[i]].val);
1636 #endif
1637 	i = 0;
1638 	j = nl3 - 1;
1639 	allow = nlist;		/* falsetickers assumed */
1640 	found = 0;
1641 	while (allow > 0) {
1642 		allow--;
1643 		for (n = 0; i <= j; i++) {
1644 			n += endpoint[indx[i]].type;
1645 			if (n < 0)
1646 				break;
1647 			if (endpoint[indx[i]].type == 0)
1648 				found++;
1649 		}
1650 		for (n = 0; i <= j; j--) {
1651 			n += endpoint[indx[j]].type;
1652 			if (n > 0)
1653 				break;
1654 			if (endpoint[indx[j]].type == 0)
1655 				found++;
1656 		}
1657 		if (found > allow)
1658 			break;
1659 		low = endpoint[indx[i++]].val;
1660 		high = endpoint[indx[j--]].val;
1661 	}
1662 
1663 	/*
1664 	 * If no survivors remain at this point, check if the local
1665 	 * clock or modem drivers have been found. If so, nominate one
1666 	 * of them as the only survivor. Otherwise, give up and declare
1667 	 * us unsynchronized.
1668 	 */
1669 	if ((allow << 1) >= nlist) {
1670 		if (typeacts != 0) {
1671 			typeacts->status = CTL_PST_SEL_SANE;
1672 			peer_list[0] = typeacts;
1673 			nlist = 1;
1674 		} else if (typelocal != 0) {
1675 			typelocal->status = CTL_PST_SEL_SANE;
1676 			peer_list[0] = typelocal;
1677 			nlist = 1;
1678 		} else {
1679 			if (osys_peer != NULL) {
1680 				sys_poll = NTP_MINPOLL;
1681 				NLOG(NLOG_SYNCSTATUS)
1682 				    msyslog(LOG_INFO,
1683 				    "synchronisation lost");
1684 				report_event(EVNT_PEERSTCHG,
1685 				    (struct peer *)0);
1686 			}
1687 			sys_survivors = 0;
1688 #ifdef AUTOKEY
1689 			resetmanycast();
1690 #endif /* AUTOKEY */
1691 			return;
1692 		}
1693 	}
1694 #ifdef DEBUG
1695 	if (debug > 2)
1696 		printf("select: low %.6f high %.6f\n", low, high);
1697 #endif
1698 
1699 	/*
1700 	 * Clustering algorithm. Construct candidate list in order first
1701 	 * by stratum then by root distance. If we have more than
1702 	 * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
1703 	 * list to find falsetickers, who leave the island immediately.
1704 	 * If a falseticker is not configured, his association raft is
1705 	 * drowned as well. We must leave at least one peer to collect
1706 	 * the million bucks.
1707 	 */
1708 	j = 0;
1709 	for (i = 0; i < nlist; i++) {
1710 		peer = peer_list[i];
1711 		if (nlist > 1 && (low >= peer->offset || peer->offset >=
1712 		    high)) {
1713 			if (!(peer->flags & FLAG_CONFIG))
1714 				unpeer(peer);
1715 			continue;
1716 		}
1717 		peer->status = CTL_PST_SEL_DISTSYSPEER;
1718 		d = root_distance(peer) + peer->stratum * MAXDISPERSE;
1719 		if (j >= NTP_MAXCLOCK) {
1720 			if (d >= synch[j - 1])
1721 				continue;
1722 			else
1723 				j--;
1724 		}
1725 		for (k = j; k > 0; k--) {
1726 			if (d >= synch[k - 1])
1727 				break;
1728 			peer_list[k] = peer_list[k - 1];
1729 			error[k] = error[k - 1];
1730 			synch[k] = synch[k - 1];
1731 		}
1732 		peer_list[k] = peer;
1733 		error[k] = peer->jitter;
1734 		synch[k] = d;
1735 		j++;
1736 	}
1737 	nlist = j;
1738 	for (i = 0; i < nlist; i++) {
1739 		peer_list[i]->status = CTL_PST_SEL_SELCAND;
1740 
1741 #ifdef DEBUG
1742 		if (debug > 2)
1743 			printf("select: %s distance %.6f\n",
1744 			    ntoa(&peer_list[i]->srcadr), synch[i]);
1745 #endif
1746 	}
1747 
1748 	/*
1749 	 * Now, vote outlyers off the island by select jitter weighted
1750 	 * by root dispersion. Continue voting as long as there are more
1751 	 * than NTP_MINCLOCK survivors and the minimum select jitter
1752 	 * squared is greater than the maximum peer jitter squared. Stop
1753 	 * if we are about to discard a prefer peer, who of course has
1754 	 * the immunity idol.
1755 	 */
1756 	while (1) {
1757 		d = 1e9;
1758 		e = -1e9;
1759 		k = 0;
1760 		for (i = 0; i < nlist; i++) {
1761 
1762 			if (error[i] < d)
1763 				d = error[i];
1764 			f = 0;
1765 			if (nlist > 1) {
1766 				for (j = 0; j < nlist; j++)
1767 					f += DIFF(peer_list[j]->offset,
1768 					    peer_list[i]->offset);
1769 				f /= nlist - 1;
1770 			}
1771 			f = max(f, SQUARE(LOGTOD(sys_precision)));
1772 			if (f * synch[i] > e) {
1773 				sys_selerr = f;
1774 				e = f * synch[i];
1775 				k = i;
1776 			}
1777 		}
1778 
1779 #ifdef DEBUG
1780 		if (debug > 2)
1781 			printf(
1782 			    "select: survivors %d select %.6f peer %.6f\n",
1783 			    k, SQRT(sys_selerr), SQRT(d));
1784 #endif
1785 		if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
1786 		    peer_list[k]->flags & FLAG_PREFER)
1787 			break;
1788 		if (!(peer_list[k]->flags & FLAG_CONFIG))
1789 			unpeer(peer_list[k]);
1790 		for (j = k + 1; j < nlist; j++) {
1791 			peer_list[j - 1] = peer_list[j];
1792 			error[j - 1] = error[j];
1793 		}
1794 		nlist--;
1795 	}
1796 
1797 #ifdef AUTOKEY
1798 	/*
1799 	 * In manycast client mode we may have spooked a sizeable number
1800 	 * of servers that we don't need. If there are at least
1801 	 * NTP_MINCLOCK of them, the manycast message will be turned
1802 	 * off. By the time we get here we nay be ready to prune some of
1803 	 * them back, but we want to make sure all the candicates have
1804 	 * had a chance. If they didn't pass the sanity and intersection
1805 	 * tests, they have already been voted off the island.
1806 	 */
1807 	if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
1808 		resetmanycast();
1809 #endif /* AUTOKEY */
1810 	sys_survivors = nlist;
1811 
1812 #ifdef DEBUG
1813 	if (debug > 2) {
1814 		for (i = 0; i < nlist; i++)
1815 			printf(
1816 			    "select: %s offset %.6f, distance %.6f poll %d\n",
1817 			    ntoa(&peer_list[i]->srcadr),
1818 			    peer_list[i]->offset, synch[i],
1819 			    peer_list[i]->pollsw);
1820 	}
1821 #endif
1822 
1823 	/*
1824 	 * What remains is a list of not greater than NTP_MINCLOCK
1825 	 * peers. We want only a peer at the lowest stratum to become
1826 	 * the system peer, although all survivors are eligible for the
1827 	 * combining algorithm. First record their order, diddle the
1828 	 * flags and clamp the poll intervals. Then, consider the peers
1829 	 * at the lowest stratum. Of these, OR the leap bits on the
1830 	 * assumption that, if some of them honk nonzero bits, they must
1831 	 * know what they are doing. Also, check for prefer and pps
1832 	 * peers. If a prefer peer is found within clock_max, update the
1833 	 * pps switch. Of the other peers not at the lowest stratum,
1834 	 * check if the system peer is among them and, if found, zap
1835 	 * him. We note that the head of the list is at the lowest
1836 	 * stratum and that unsynchronized peers cannot survive this
1837 	 * far.
1838 	 *
1839 	 * Note that we go no further, unless the number of survivors is
1840 	 * a majority of the suckers that have been found reachable and
1841 	 * no prior source is available. This avoids the transient when
1842 	 * one of a flock of sources is out to lunch and just happens
1843 	 * to be the first survivor.
1844 	 */
1845 	if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
1846 		return;
1847 	leap_consensus = 0;
1848 	for (i = nlist - 1; i >= 0; i--) {
1849 		peer = peer_list[i];
1850 		peer->status = CTL_PST_SEL_SYNCCAND;
1851 		peer->flags |= FLAG_SYSPEER;
1852 		poll_update(peer, peer->hpoll);
1853 		if (peer->stratum == peer_list[0]->stratum) {
1854 			leap_consensus |= peer->leap;
1855 			if (peer->refclktype == REFCLK_ATOM_PPS &&
1856 			    peer->stratum < STRATUM_UNSPEC)
1857 				typepps = peer;
1858 			if (peer == osys_peer)
1859 				typesystem = peer;
1860 			if (peer->flags & FLAG_PREFER)
1861 				sys_prefer = peer;
1862 		}
1863 	}
1864 
1865 	/*
1866 	 * Mitigation rules of the game. There are several types of
1867 	 * peers that make a difference here: (1) prefer local peers
1868 	 * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
1869 	 * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
1870 	 * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
1871 	 * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
1872 	 * the head of the survivor list. Note that only one peer can be
1873 	 * declared prefer. The order of preference is in the order
1874 	 * stated. Note that all of these must be at the lowest stratum,
1875 	 * i.e., the stratum of the head of the survivor list.
1876 	 */
1877 	if (sys_prefer)
1878 		sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
1879 		    sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
1880 		    !typepps;
1881 	else
1882 		sw = 0;
1883 	if (sw) {
1884 		sys_peer = sys_prefer;
1885 		sys_peer->status = CTL_PST_SEL_SYSPEER;
1886 		sys_offset = sys_peer->offset;
1887 		sys_syserr = sys_peer->jitter;
1888 #ifdef DEBUG
1889 		if (debug > 1)
1890 			printf("select: prefer offset %.6f\n",
1891 			    sys_offset);
1892 #endif
1893 	} else if (typepps) {
1894 		sys_peer = typepps;
1895 		sys_peer->status = CTL_PST_SEL_PPS;
1896 		sys_offset = sys_peer->offset;
1897 		sys_syserr = sys_peer->jitter;
1898 		if (!pps_control)
1899 			NLOG(NLOG_SYSEVENT)
1900 			    msyslog(LOG_INFO,
1901 			    "pps sync enabled");
1902 		pps_control = current_time;
1903 #ifdef DEBUG
1904 		if (debug > 1)
1905 			printf("select: pps offset %.6f\n",
1906 			    sys_offset);
1907 #endif
1908 	} else {
1909 		if (typesystem)
1910 			sys_peer = osys_peer;
1911 		else
1912 			sys_peer = peer_list[0];
1913 		sys_peer->status = CTL_PST_SEL_SYSPEER;
1914 		sys_offset = clock_combine(peer_list, nlist);
1915 		sys_syserr = sys_peer->jitter + sys_selerr;
1916 #ifdef DEBUG
1917 		if (debug > 1)
1918 			printf("select: combine offset %.6f\n",
1919 			   sys_offset);
1920 #endif
1921 	}
1922 	if (osys_peer != sys_peer)
1923 		report_event(EVNT_PEERSTCHG, (struct peer *)0);
1924 	clock_update();
1925 }
1926 
1927 /*
1928  * clock_combine - combine offsets from selected peers
1929  */
1930 static double
1931 clock_combine(
1932 	struct peer **peers,
1933 	int npeers
1934 	)
1935 {
1936 	int i;
1937 	double x, y, z;
1938 	y = z = 0;
1939 	for (i = 0; i < npeers; i++) {
1940 		x = root_distance(peers[i]);
1941 		y += 1. / x;
1942 		z += peers[i]->offset / x;
1943 	}
1944 	return (z / y);
1945 }
1946 
1947 /*
1948  * root_distance - compute synchronization distance from peer to root
1949  */
1950 static double
1951 root_distance(
1952 	struct peer *peer
1953 	)
1954 {
1955 	/*
1956 	 * Careful squeak here. The value returned must be greater than
1957 	 * zero blamed on the peer jitter, which must be at least the
1958 	 * square of sys_precision.
1959 	 */
1960 	return ((peer->rootdelay + peer->delay) / 2 +
1961 	    peer->rootdispersion + peer->disp + clock_phi *
1962 	    (current_time - peer->update) + SQRT(peer->jitter));
1963 }
1964 
1965 /*
1966  * peer_xmit - send packet for persistent association.
1967  */
1968 static void
1969 peer_xmit(
1970 	struct peer *peer	/* peer structure pointer */
1971 	)
1972 {
1973 	struct pkt xpkt;	/* transmit packet */
1974 	int sendlen, authlen;
1975 	keyid_t xkeyid;		/* transmit key ID */
1976 	l_fp xmt_tx;
1977 
1978 	/*
1979 	 * Initialize transmit packet header fields.
1980 	 */
1981 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
1982 	    peer->hmode);
1983 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
1984 	xpkt.ppoll = peer->hpoll;
1985 	xpkt.precision = sys_precision;
1986 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
1987 	xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
1988 	xpkt.refid = sys_refid;
1989 	HTONL_FP(&sys_reftime, &xpkt.reftime);
1990 	HTONL_FP(&peer->org, &xpkt.org);
1991 	HTONL_FP(&peer->rec, &xpkt.rec);
1992 
1993 	/*
1994 	 * If the received packet contains a MAC, the transmitted packet
1995 	 * is authenticated and contains a MAC. If not, the transmitted
1996 	 * packet is not authenticated.
1997 	 *
1998 	 * In the current I/O semantics the default interface is set
1999 	 * until after receiving a packet and setting the right
2000 	 * interface. So, the first packet goes out unauthenticated.
2001 	 * That's why the really icky test next is here.
2002 	 */
2003 	sendlen = LEN_PKT_NOMAC;
2004 	if (!(peer->flags & FLAG_AUTHENABLE)) {
2005 		get_systime(&peer->xmt);
2006 		HTONL_FP(&peer->xmt, &xpkt.xmt);
2007 		sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
2008 		    sendlen);
2009 		peer->sent++;
2010 #ifdef DEBUG
2011 		if (debug)
2012 			printf("transmit: at %ld %s->%s mode %d\n",
2013 			    current_time, ntoa(&peer->dstadr->sin),
2014 			    ntoa(&peer->srcadr), peer->hmode);
2015 #endif
2016 		return;
2017 	}
2018 
2019 	/*
2020 	 * The received packet contains a MAC, so the transmitted packet
2021 	 * must be authenticated. If autokey is enabled, fuss with the
2022 	 * various modes; otherwise, private key cryptography is used.
2023 	 */
2024 #ifdef AUTOKEY
2025 	if ((peer->flags & FLAG_SKEY)) {
2026 		u_int cmmd;
2027 
2028 		/*
2029 		 * The Public Key Dance (PKD): Cryptographic credentials
2030 		 * are contained in extension fields, each including a
2031 		 * 4-octet length/code word followed by a 4-octet
2032 		 * association ID and optional additional data. Optional
2033 		 * data includes a 4-octet data length field followed by
2034 		 * the data itself. Request messages are sent from a
2035 		 * configured association; response messages can be sent
2036 		 * from a configured association or can take the fast
2037 		 * path without ever matching an association. Response
2038 		 * messages have the same code as the request, but have
2039 		 * a response bit and possibly an error bit set. In this
2040 		 * implementation, a message may contain no more than
2041 		 * one command and no more than one response.
2042 		 *
2043 		 * Cryptographic session keys include both a public and
2044 		 * a private componet. Request and response messages
2045 		 * using extension fields are always sent with the
2046 		 * private component set to zero. Packets without
2047 		 * extension fields indlude the private component when
2048 		 * the session key is generated.
2049 		 */
2050 		while (1) {
2051 
2052 			/*
2053 			 * Allocate and initialize a keylist if not
2054 			 * already done. Then, use the list in inverse
2055 			 * order, discarding keys once used. Keep the
2056 			 * latest key around until the next one, so
2057 			 * clients can use client/server packets to
2058 			 * compute propagation delay.
2059 			 *
2060 			 * Note that once a key is used from the list,
2061 			 * it is retained in the key cache until the
2062 			 * next key is used. This is to allow a client
2063 			 * to retrieve the encrypted session key
2064 			 * identifier to verify authenticity.
2065 			 *
2066 			 * If for some reason a key is no longer in the
2067 			 * key cache, a birthday has happened and the
2068 			 * pseudo-random sequence is probably broken. In
2069 			 * that case, purge the keylist and regenerate
2070 			 * it.
2071 			 */
2072 			if (peer->keynumber == 0)
2073 				make_keylist(peer, peer->dstadr);
2074 			else
2075 				peer->keynumber--;
2076 			xkeyid = peer->keylist[peer->keynumber];
2077 			if (authistrusted(xkeyid))
2078 				break;
2079 			else
2080 				key_expire(peer);
2081 		}
2082 		peer->keyid = xkeyid;
2083 		switch (peer->hmode) {
2084 
2085 		/*
2086 		 * In broadcast mode the autokey values are required.
2087 		 * Send them when a new keylist is generated; otherwise,
2088 		 * send the association ID so the client can request
2089 		 * them at other times.
2090 		 */
2091 		case MODE_BROADCAST:
2092 			if (peer->flags & FLAG_ASSOC)
2093 				cmmd = CRYPTO_AUTO | CRYPTO_RESP;
2094 			else
2095 				cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
2096 			sendlen += crypto_xmit((u_int32 *)&xpkt,
2097 			    sendlen, cmmd, 0, peer->associd);
2098 			break;
2099 
2100 		/*
2101 		 * In symmetric modes the public key, leapsecond table,
2102 		 * agreement parameters and autokey values are required.
2103  		 *
2104 		 * 1. If a response is pending, always send it first.
2105 		 *
2106 		 * 2. Don't send anything except a public-key request
2107 		 *    until the public key has been stored.
2108 		 *
2109 		 * 3. Once the public key has been stored, don't send
2110 		 *    anything except an agreement parameter request
2111 		 *    until the agreement parameters have been stored.
2112 		 *
2113 		 * 4. Once the argeement parameters have been stored,
2114 		 *    don't send anything except a public value request
2115 		 *    until the agreed key has been stored.
2116 		 *
2117 		 * 5. When the agreed key has been stored and the key
2118 		 *    list is regenerated, send the autokey values
2119 		 *    gratis unless they have already been sent.
2120 		 */
2121 		case MODE_ACTIVE:
2122 		case MODE_PASSIVE:
2123 #ifdef PUBKEY
2124 			if (peer->cmmd != 0)
2125 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2126 				    sendlen, (peer->cmmd >> 16) |
2127 				    CRYPTO_RESP, peer->hcookie,
2128 				    peer->associd);
2129 			if (!peer->crypto)
2130 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2131 				    sendlen, CRYPTO_ASSOC,
2132 				    peer->hcookie, peer->assoc);
2133 			else if (!crypto_flags &&
2134 			    peer->pcookie.tstamp == 0 && sys_leap !=
2135 			    LEAP_NOTINSYNC)
2136 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2137 				    sendlen, CRYPTO_PRIV, peer->hcookie,
2138 				    peer->assoc);
2139 			else if (crypto_flags && peer->pubkey.ptr ==
2140 			    NULL)
2141 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2142 				    sendlen, CRYPTO_NAME, peer->hcookie,
2143 				    peer->assoc);
2144 			else if (peer->crypto & CRYPTO_FLAG_CERT)
2145 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2146 				    sendlen, CRYPTO_CERT, peer->hcookie,
2147 				    peer->assoc);
2148 			else if (crypto_flags && peer->crypto &
2149 			    CRYPTO_FLAG_DH && sys_leap !=
2150 			    LEAP_NOTINSYNC)
2151 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2152 				    sendlen, CRYPTO_DHPAR,
2153 				    peer->hcookie, peer->assoc);
2154 			else if (crypto_flags && peer->pcookie.tstamp ==
2155 			    0 && sys_leap != LEAP_NOTINSYNC)
2156 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2157 				    sendlen, CRYPTO_DH, peer->hcookie,
2158 				    peer->assoc);
2159 #else
2160 			if (peer->cmmd != 0)
2161 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2162 				    sendlen, (peer->cmmd >> 16) |
2163 				    CRYPTO_RESP, peer->hcookie,
2164 				    peer->associd);
2165 			if (peer->pcookie.tstamp == 0 && sys_leap !=
2166 			    LEAP_NOTINSYNC)
2167 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2168 				    sendlen, CRYPTO_PRIV, peer->hcookie,
2169 				    peer->assoc);
2170 #endif /* PUBKEY */
2171 			else if (!(peer->flags & FLAG_AUTOKEY))
2172 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2173 				    sendlen, CRYPTO_AUTO, peer->hcookie,
2174 				    peer->assoc);
2175 			else if ((peer->flags & FLAG_ASSOC) &&
2176 			    (peer->cmmd >> 16) != CRYPTO_AUTO)
2177 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2178 				    sendlen, CRYPTO_AUTO | CRYPTO_RESP,
2179 				    peer->hcookie, peer->associd);
2180 #ifdef PUBKEY
2181 			else if (peer->crypto & CRYPTO_FLAG_TAI)
2182 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2183 				    sendlen, CRYPTO_TAI, peer->hcookie,
2184 				    peer->assoc);
2185 #endif /* PUBKEY */
2186 			peer->cmmd = 0;
2187 			break;
2188 
2189 		/*
2190 		 * In client mode, the public key, host cookie and
2191 		 * autokey values are required. In broadcast client
2192 		 * mode, these values must be acquired during the
2193 		 * client/server exchange to avoid having to wait until
2194 		 * the next key list regeneration. Otherwise, the poor
2195 		 * dude may die a lingering death until becoming
2196 		 * unreachable and attempting rebirth. Note that we ask
2197 		 * for the cookie at each key list regeneration anyway.
2198 		 */
2199 		case MODE_CLIENT:
2200 			if (peer->cmmd != 0)
2201 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2202 				    sendlen, (peer->cmmd >> 16) |
2203 				    CRYPTO_RESP, peer->hcookie,
2204 				    peer->associd);
2205 			if (!peer->crypto)
2206 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2207 				    sendlen, CRYPTO_ASSOC,
2208 				    peer->hcookie, peer->assoc);
2209 #ifdef PUBKEY
2210 			else if (crypto_flags && peer->pubkey.ptr ==
2211 			    NULL)
2212 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2213 				    sendlen, CRYPTO_NAME, peer->hcookie,
2214 				    peer->assoc);
2215 			else if (peer->crypto & CRYPTO_FLAG_CERT)
2216 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2217 				    sendlen, CRYPTO_CERT, peer->hcookie,
2218 				    peer->assoc);
2219 #endif /* PUBKEY */
2220 			else if (peer->pcookie.tstamp == 0)
2221 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2222 				    sendlen, CRYPTO_PRIV, peer->hcookie,
2223 				    peer->assoc);
2224 			else if (!(peer->flags & FLAG_AUTOKEY) &&
2225 			    (peer->cast_flags & MDF_BCLNT))
2226 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2227 				    sendlen, CRYPTO_AUTO, peer->hcookie,
2228 				    peer->assoc);
2229 #ifdef PUBKEY
2230 			else if (peer->crypto & CRYPTO_FLAG_TAI)
2231 				sendlen += crypto_xmit((u_int32 *)&xpkt,
2232 				    sendlen, CRYPTO_TAI, peer->hcookie,
2233 				    peer->assoc);
2234 #endif /* PUBKEY */
2235 			peer->cmmd = 0;
2236 			break;
2237 		}
2238 
2239 		/*
2240 		 * If extension fields are present, we must use a
2241 		 * private value of zero and force min poll interval.
2242 		 * Most intricate.
2243 		 */
2244 		if (sendlen > LEN_PKT_NOMAC)
2245 			session_key(&peer->dstadr->sin, &peer->srcadr,
2246 			    xkeyid, 0, 2);
2247 	}
2248 #endif /* AUTOKEY */
2249 	xkeyid = peer->keyid;
2250 	get_systime(&peer->xmt);
2251 	L_ADD(&peer->xmt, &sys_authdelay);
2252 	HTONL_FP(&peer->xmt, &xpkt.xmt);
2253 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2254 	if (authlen == 0) {
2255 		msyslog(LOG_NOTICE,
2256 			"transmit: no encryption key found");
2257 		peer->flash |= TEST4 | TEST5;
2258 		return;
2259 	}
2260 	sendlen += authlen;
2261 #ifdef AUTOKEY
2262 	if (xkeyid > NTP_MAXKEY)
2263 		authtrust(xkeyid, 0);
2264 #endif /* AUTOKEY */
2265 	get_systime(&xmt_tx);
2266 	if (sendlen > sizeof(xpkt)) {
2267 		msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2268 		exit(-1);
2269 	}
2270 	sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
2271 
2272 	/*
2273 	 * Calculate the encryption delay. Keep the minimum over
2274 	 * the latest two samples.
2275 	 */
2276 	L_SUB(&xmt_tx, &peer->xmt);
2277 	L_ADD(&xmt_tx, &sys_authdelay);
2278 	sys_authdly[1] = sys_authdly[0];
2279 	sys_authdly[0] = xmt_tx.l_uf;
2280 	if (sys_authdly[0] < sys_authdly[1])
2281 		sys_authdelay.l_uf = sys_authdly[0];
2282 	else
2283 		sys_authdelay.l_uf = sys_authdly[1];
2284 	peer->sent++;
2285 #ifdef AUTOKEY
2286 #ifdef DEBUG
2287 	if (debug)
2288 		printf(
2289 		    "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2290 		    current_time, ntoa(&peer->dstadr->sin),
2291 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2292 		    authlen, peer->keynumber);
2293 #endif
2294 #else
2295 #ifdef DEBUG
2296 	if (debug)
2297 		printf(
2298 		    "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2299 		    current_time, ntoa(&peer->dstadr->sin),
2300 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2301 		    authlen);
2302 #endif
2303 #endif /* AUTOKEY */
2304 }
2305 
2306 
2307 /*
2308  * fast_xmit - Send packet for nonpersistent association. Note that
2309  * neither the source or destination can be a broadcast address.
2310  */
2311 static void
2312 fast_xmit(
2313 	struct recvbuf *rbufp,	/* receive packet pointer */
2314 	int xmode,		/* transmit mode */
2315 	keyid_t xkeyid,		/* transmit key ID */
2316 	int mask		/* restrict mask */
2317 	)
2318 {
2319 	struct pkt xpkt;	/* transmit packet structure */
2320 	struct pkt *rpkt;	/* receive packet structure */
2321 	l_fp xmt_ts;		/* transmit timestamp */
2322 	l_fp xmt_tx;		/* transmit timestamp after authent */
2323 	int sendlen, authlen;
2324 
2325 	/*
2326 	 * Initialize transmit packet header fields from the receive
2327 	 * buffer provided. We leave some fields intact as received. If
2328 	 * the gazinta was from a multicast address, the gazouta must go
2329 	 * out another way.
2330 	 */
2331 	rpkt = &rbufp->recv_pkt;
2332 	if (rbufp->dstadr->flags & INT_MULTICAST)
2333 		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2334 
2335 	/*
2336 	 * If the caller is restricted, return a kiss-of-death packet;
2337 	 * otherwise, smooch politely.
2338 	 */
2339 	if (mask & (RES_DONTSERVE | RES_LIMITED)) {
2340 		if (!(mask & RES_DEMOBILIZE)) {
2341 			return;
2342 		} else {
2343 			xpkt.li_vn_mode =
2344 			    PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2345 			    PKT_VERSION(rpkt->li_vn_mode), xmode);
2346 			xpkt.stratum = STRATUM_UNSPEC;
2347 			memcpy(&xpkt.refid, "DENY", 4);
2348 		}
2349 	} else {
2350 		xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2351 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
2352 		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2353 		xpkt.refid = sys_refid;
2354 	}
2355 	xpkt.ppoll = rpkt->ppoll;
2356 	xpkt.precision = sys_precision;
2357 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2358 	xpkt.rootdispersion =
2359 	    HTONS_FP(DTOUFP(sys_rootdispersion));
2360 	HTONL_FP(&sys_reftime, &xpkt.reftime);
2361 	xpkt.org = rpkt->xmt;
2362 	HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2363 
2364 	/*
2365 	 * If the received packet contains a MAC, the transmitted packet
2366 	 * is authenticated and contains a MAC. If not, the transmitted
2367 	 * packet is not authenticated.
2368 	 */
2369 	sendlen = LEN_PKT_NOMAC;
2370 	if (rbufp->recv_length == sendlen) {
2371 		get_systime(&xmt_ts);
2372 		HTONL_FP(&xmt_ts, &xpkt.xmt);
2373 		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2374 		    sendlen);
2375 #ifdef DEBUG
2376 		if (debug)
2377 			printf("transmit: at %ld %s->%s mode %d\n",
2378 			    current_time, ntoa(&rbufp->dstadr->sin),
2379 			    ntoa(&rbufp->recv_srcadr), xmode);
2380 #endif
2381 		return;
2382 	}
2383 
2384 	/*
2385 	 * The received packet contains a MAC, so the transmitted packet
2386 	 * must be authenticated. For private-key cryptography, use the
2387 	 * predefined private keys to generate the cryptosum. For
2388 	 * autokey cryptography, use the server private value to
2389 	 * generate the cookie, which is unique for every source-
2390 	 * destination-key ID combination.
2391 	 */
2392 #ifdef AUTOKEY
2393 	if (xkeyid > NTP_MAXKEY) {
2394 		keyid_t cookie;
2395 		u_int code, associd;
2396 
2397 		/*
2398 		 * The only way to get here is a reply to a legitimate
2399 		 * client request message, so the mode must be
2400 		 * MODE_SERVER. If an extension field is present, there
2401 		 * can be only one and that must be a command. Do what
2402 		 * needs, but with private value of zero so the poor
2403 		 * jerk can decode it. If no extension field is present,
2404 		 * use the cookie to generate the session key.
2405 		 */
2406 		code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
2407 		cookie = session_key(&rbufp->recv_srcadr,
2408 		    &rbufp->dstadr->sin, 0, sys_private, 0);
2409 		associd = htonl(rpkt->exten[1]);
2410 		if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
2411 		    sizeof(u_int32)) {
2412 			session_key(&rbufp->dstadr->sin,
2413 			    &rbufp->recv_srcadr, xkeyid, 0, 2);
2414 			sendlen += crypto_xmit((u_int32 *)&xpkt,
2415 			    sendlen, code, cookie, associd);
2416 		} else {
2417 			session_key(&rbufp->dstadr->sin,
2418 			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
2419 		}
2420 	}
2421 #endif /* AUTOKEY */
2422 	get_systime(&xmt_ts);
2423 	L_ADD(&xmt_ts, &sys_authdelay);
2424 	HTONL_FP(&xmt_ts, &xpkt.xmt);
2425 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2426 	sendlen += authlen;
2427 #ifdef AUTOKEY
2428 	if (xkeyid > NTP_MAXKEY)
2429 		authtrust(xkeyid, 0);
2430 #endif /* AUTOKEY */
2431 	get_systime(&xmt_tx);
2432 	if (sendlen > sizeof(xpkt)) {
2433 		msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2434 		exit(-1);
2435 	}
2436 	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2437 
2438 	/*
2439 	 * Calculate the encryption delay. Keep the minimum over the
2440 	 * latest two samples.
2441 	 */
2442 	L_SUB(&xmt_tx, &xmt_ts);
2443 	L_ADD(&xmt_tx, &sys_authdelay);
2444 	sys_authdly[1] = sys_authdly[0];
2445 	sys_authdly[0] = xmt_tx.l_uf;
2446 	if (sys_authdly[0] < sys_authdly[1])
2447 		sys_authdelay.l_uf = sys_authdly[0];
2448 	else
2449 		sys_authdelay.l_uf = sys_authdly[1];
2450 #ifdef DEBUG
2451 	if (debug)
2452 		printf(
2453 		    "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2454 		    current_time, ntoa(&rbufp->dstadr->sin),
2455 		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
2456 		    authlen);
2457 #endif
2458 }
2459 
2460 
2461 #ifdef AUTOKEY
2462 /*
2463  * key_expire - purge the key list
2464  */
2465 void
2466 key_expire(
2467 	struct peer *peer	/* peer structure pointer */
2468 	)
2469 {
2470 	int i;
2471 
2472  	if (peer->keylist != NULL) {
2473 		for (i = 0; i <= peer->keynumber; i++)
2474 			authtrust(peer->keylist[i], 0);
2475 		free(peer->keylist);
2476 		peer->keylist = NULL;
2477 	}
2478 	peer->keynumber = peer->sndauto.seq = 0;
2479 #ifdef DEBUG
2480 	if (debug)
2481 		printf("key_expire: at %lu\n", current_time);
2482 #endif
2483 }
2484 #endif /* AUTOKEY */
2485 
2486 /*
2487  * Find the precision of this particular machine
2488  */
2489 #define DUSECS	1000000 /* us in a s */
2490 #define HUSECS	(1 << 20) /* approx DUSECS for shifting etc */
2491 #define MINSTEP 5	/* minimum clock increment (us) */
2492 #define MAXSTEP 20000	/* maximum clock increment (us) */
2493 #define MINLOOPS 5	/* minimum number of step samples */
2494 
2495 /*
2496  * This routine calculates the differences between successive calls to
2497  * gettimeofday(). If a difference is less than zero, the us field
2498  * has rolled over to the next second, so we add a second in us. If
2499  * the difference is greater than zero and less than MINSTEP, the
2500  * clock has been advanced by a small amount to avoid standing still.
2501  * If the clock has advanced by a greater amount, then a timer interrupt
2502  * has occurred and this amount represents the precision of the clock.
2503  * In order to guard against spurious values, which could occur if we
2504  * happen to hit a fat interrupt, we do this for MINLOOPS times and
2505  * keep the minimum value obtained.
2506  */
2507 int
2508 default_get_precision(void)
2509 {
2510 	struct timeval tp;
2511 #if !defined(SYS_WINNT) && !defined(VMS) && !defined(_SEQUENT_)
2512 	struct timezone tzp;
2513 #elif defined(VMS) || defined(_SEQUENT_)
2514 	struct timezone {
2515 		int tz_minuteswest;
2516 		int tz_dsttime;
2517 	} tzp;
2518 #endif /* defined(VMS) || defined(_SEQUENT_) */
2519 	long last;
2520 	int i;
2521 	long diff;
2522 	long val;
2523 	long usec;
2524 #ifdef HAVE_GETCLOCK
2525 	struct timespec ts;
2526 #endif
2527 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
2528 	u_long freq;
2529 	size_t j;
2530 
2531 	/* Try to see if we can find the frequency of of the counter
2532 	 * which drives our timekeeping
2533 	 */
2534 	j = sizeof freq;
2535 	i = sysctlbyname("kern.timecounter.frequency", &freq, &j , 0,
2536 	    0);
2537 	if (i)
2538 		i = sysctlbyname("machdep.tsc_freq", &freq, &j , 0, 0);
2539 	if (i)
2540 		i = sysctlbyname("machdep.i586_freq", &freq, &j , 0, 0);
2541 	if (i)
2542 		i = sysctlbyname("machdep.i8254_freq", &freq, &j , 0,
2543 		    0);
2544 	if (!i) {
2545 		for (i = 1; freq ; i--)
2546 			freq >>= 1;
2547 		return (i);
2548 	}
2549 #endif
2550 	usec = 0;
2551 	val = MAXSTEP;
2552 #ifdef HAVE_GETCLOCK
2553 	(void) getclock(TIMEOFDAY, &ts);
2554 	tp.tv_sec = ts.tv_sec;
2555 	tp.tv_usec = ts.tv_nsec / 1000;
2556 #else /*  not HAVE_GETCLOCK */
2557 	GETTIMEOFDAY(&tp, &tzp);
2558 #endif /* not HAVE_GETCLOCK */
2559 	last = tp.tv_usec;
2560 	for (i = 0; i < MINLOOPS && usec < HUSECS;) {
2561 #ifdef HAVE_GETCLOCK
2562 		(void) getclock(TIMEOFDAY, &ts);
2563 		tp.tv_sec = ts.tv_sec;
2564 		tp.tv_usec = ts.tv_nsec / 1000;
2565 #else /*  not HAVE_GETCLOCK */
2566 		GETTIMEOFDAY(&tp, &tzp);
2567 #endif /* not HAVE_GETCLOCK */
2568 		diff = tp.tv_usec - last;
2569 		last = tp.tv_usec;
2570 		if (diff < 0)
2571 			diff += DUSECS;
2572 		usec += diff;
2573 		if (diff > MINSTEP) {
2574 			i++;
2575 			if (diff < val)
2576 				val = diff;
2577 		}
2578 	}
2579 	NLOG(NLOG_SYSINFO)
2580 		msyslog(LOG_INFO, "precision = %ld usec", val);
2581 	if (usec >= HUSECS)
2582 		val = MINSTEP;	/* val <= MINSTEP; fast machine */
2583 	diff = HUSECS;
2584 	for (i = 0; diff > val; i--)
2585 		diff >>= 1;
2586 	return (i);
2587 }
2588 
2589 /*
2590  * init_proto - initialize the protocol module's data
2591  */
2592 void
2593 init_proto(void)
2594 {
2595 	l_fp dummy;
2596 
2597 	/*
2598 	 * Fill in the sys_* stuff.  Default is don't listen to
2599 	 * broadcasting, authenticate.
2600 	 */
2601 	sys_leap = LEAP_NOTINSYNC;
2602 	sys_stratum = STRATUM_UNSPEC;
2603 	sys_precision = (s_char)default_get_precision();
2604 	sys_jitter = LOGTOD(sys_precision);
2605 	sys_rootdelay = 0;
2606 	sys_rootdispersion = 0;
2607 	sys_refid = 0;
2608 	L_CLR(&sys_reftime);
2609 	sys_peer = NULL;
2610 	sys_survivors = 0;
2611 	get_systime(&dummy);
2612 	sys_bclient = 0;
2613 	sys_bdelay = DEFBROADDELAY;
2614 	sys_authenticate = 1;
2615 	L_CLR(&sys_authdelay);
2616 	sys_authdly[0] = sys_authdly[1] = 0;
2617 	sys_stattime = 0;
2618 	sys_badstratum = 0;
2619 	sys_oldversionpkt = 0;
2620 	sys_newversionpkt = 0;
2621 	sys_badlength = 0;
2622 	sys_unknownversion = 0;
2623 	sys_processed = 0;
2624 	sys_badauth = 0;
2625 	sys_manycastserver = 0;
2626 #ifdef AUTOKEY
2627 	sys_automax = 1 << NTP_AUTOMAX;
2628 #endif /* AUTOKEY */
2629 
2630 	/*
2631 	 * Default these to enable
2632 	 */
2633 	ntp_enable = 1;
2634 #ifndef KERNEL_FLL_BUG
2635 	kern_enable = 1;
2636 #endif
2637 	pps_enable = 0;
2638 	stats_control = 1;
2639 
2640 	/*
2641 	 * Some system clocks should only be adjusted in 10ms
2642 	 * increments.
2643 	 */
2644 #if defined RELIANTUNIX_CLOCK
2645 	systime_10ms_ticks = 1;		  /* Reliant UNIX */
2646 #elif defined SCO5_CLOCK
2647 	if (sys_precision >= (s_char)-10) /* pre-SCO OpenServer 5.0.6 */
2648 		systime_10ms_ticks = 1;
2649 #endif
2650 	if (systime_10ms_ticks)
2651 		msyslog(LOG_INFO, "using 10ms tick adjustments");
2652 }
2653 
2654 
2655 /*
2656  * proto_config - configure the protocol module
2657  */
2658 void
2659 proto_config(
2660 	int item,
2661 	u_long value,
2662 	double dvalue
2663 	)
2664 {
2665 	/*
2666 	 * Figure out what he wants to change, then do it
2667 	 */
2668 	switch (item) {
2669 	case PROTO_KERNEL:
2670 
2671 		/*
2672 		 * Turn on/off kernel discipline
2673 		 */
2674 		kern_enable = (int)value;
2675 		break;
2676 
2677 	case PROTO_NTP:
2678 
2679 		/*
2680 		 * Turn on/off clock discipline
2681 		 */
2682 		ntp_enable = (int)value;
2683 		break;
2684 
2685 	case PROTO_MONITOR:
2686 
2687 		/*
2688 		 * Turn on/off monitoring
2689 		 */
2690 		if (value)
2691 			mon_start(MON_ON);
2692 		else
2693 			mon_stop(MON_ON);
2694 		break;
2695 
2696 	case PROTO_FILEGEN:
2697 
2698 		/*
2699 		 * Turn on/off statistics
2700 		 */
2701 		stats_control = (int)value;
2702 		break;
2703 
2704 	case PROTO_BROADCLIENT:
2705 
2706 		/*
2707 		 * Turn on/off facility to listen to broadcasts
2708 		 */
2709 		sys_bclient = (int)value;
2710 		if (value)
2711 			io_setbclient();
2712 		else
2713 			io_unsetbclient();
2714 		break;
2715 
2716 	case PROTO_MULTICAST_ADD:
2717 
2718 		/*
2719 		 * Add muliticast group address
2720 		 */
2721 		io_multicast_add(value);
2722 		break;
2723 
2724 	case PROTO_MULTICAST_DEL:
2725 
2726 		/*
2727 		 * Delete multicast group address
2728 		 */
2729 		io_multicast_del(value);
2730 		break;
2731 
2732 	case PROTO_BROADDELAY:
2733 
2734 		/*
2735 		 * Set default broadcast delay
2736 		 */
2737 		sys_bdelay = dvalue;
2738 		break;
2739 
2740 	case PROTO_AUTHENTICATE:
2741 
2742 		/*
2743 		 * Specify the use of authenticated data
2744 		 */
2745 		sys_authenticate = (int)value;
2746 		break;
2747 
2748 	case PROTO_PPS:
2749 
2750 		/*
2751 		 * Turn on/off PPS discipline
2752 		 */
2753 		pps_enable = (int)value;
2754 		break;
2755 
2756 #ifdef REFCLOCK
2757 	case PROTO_CAL:
2758 
2759 		/*
2760 		 * Turn on/off refclock calibrate
2761 		 */
2762 		cal_enable = (int)value;
2763 		break;
2764 #endif
2765 
2766 	default:
2767 
2768 		/*
2769 		 * Log this error
2770 		 */
2771 		msyslog(LOG_ERR,
2772 		    "proto_config: illegal item %d, value %ld",
2773 			item, value);
2774 		break;
2775 	}
2776 }
2777 
2778 
2779 /*
2780  * proto_clr_stats - clear protocol stat counters
2781  */
2782 void
2783 proto_clr_stats(void)
2784 {
2785 	sys_badstratum = 0;
2786 	sys_oldversionpkt = 0;
2787 	sys_newversionpkt = 0;
2788 	sys_unknownversion = 0;
2789 	sys_badlength = 0;
2790 	sys_processed = 0;
2791 	sys_badauth = 0;
2792 	sys_stattime = current_time;
2793 	sys_limitrejected = 0;
2794 }
2795