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