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