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