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