154359Sroberto/*
254359Sroberto * ntp_proto.c - NTP version 4 protocol machinery
354363Sroberto *
4132454Sroberto * ATTENTION: Get approval from Dave Mills on all changes to this file!
5132454Sroberto *
654359Sroberto */
754359Sroberto#ifdef HAVE_CONFIG_H
854359Sroberto#include <config.h>
954359Sroberto#endif
1054359Sroberto
1154359Sroberto#include "ntpd.h"
1254359Sroberto#include "ntp_stdlib.h"
1354359Sroberto#include "ntp_unixtime.h"
1454359Sroberto#include "ntp_control.h"
1554359Sroberto#include "ntp_string.h"
16290000Sglebius#include "ntp_leapsec.h"
17290000Sglebius#include "refidsmear.h"
18293894Sglebius#include "lib_strbuf.h"
1954359Sroberto
2082505Sroberto#include <stdio.h>
21290000Sglebius#ifdef HAVE_LIBSCF_H
22290000Sglebius#include <libscf.h>
2354359Sroberto#endif
24290000Sglebius#ifdef HAVE_UNISTD_H
25290000Sglebius#include <unistd.h>
2654359Sroberto#endif
2754359Sroberto
28298770Sdelphij/* [Bug 3031] define automatic broadcastdelay cutoff preset */
29298770Sdelphij#ifndef BDELAY_DEFAULT
30298770Sdelphij# define BDELAY_DEFAULT (-0.050)
31298770Sdelphij#endif
32298770Sdelphij
3354359Sroberto/*
34182007Sroberto * This macro defines the authentication state. If x is 1 authentication
35182007Sroberto * is required; othewise it is optional.
36182007Sroberto */
37290000Sglebius#define	AUTH(x, y)	((x) ? (y) == AUTH_OK \
38290000Sglebius			     : (y) == AUTH_OK || (y) == AUTH_NONE)
39182007Sroberto
40290000Sglebius#define	AUTH_NONE	0	/* authentication not required */
41290000Sglebius#define	AUTH_OK		1	/* authentication OK */
42290000Sglebius#define	AUTH_ERROR	2	/* authentication error */
43290000Sglebius#define	AUTH_CRYPTO	3	/* crypto_NAK */
44290000Sglebius
45182007Sroberto/*
46290000Sglebius * Set up Kiss Code values
4754359Sroberto */
48290000Sglebius
49290000Sglebiusenum kiss_codes {
50290000Sglebius	NOKISS,				/* No Kiss Code */
51290000Sglebius	RATEKISS,			/* Rate limit Kiss Code */
52290000Sglebius	DENYKISS,			/* Deny Kiss */
53290000Sglebius	RSTRKISS,			/* Restricted Kiss */
54290000Sglebius	XKISS,				/* Experimental Kiss */
55290000Sglebius	UNKNOWNKISS			/* Unknown Kiss Code */
56290000Sglebius};
57290000Sglebius
58298770Sdelphijenum nak_error_codes {
59298770Sdelphij	NONAK,				/* No NAK seen */
60298770Sdelphij	INVALIDNAK,			/* NAK cannot be used */
61298770Sdelphij	VALIDNAK			/* NAK is valid */
62298770Sdelphij};
63298770Sdelphij
64290000Sglebius/*
65290000Sglebius * traffic shaping parameters
66290000Sglebius */
67290000Sglebius#define	NTP_IBURST	6	/* packets in iburst */
68290000Sglebius#define	RESP_DELAY	1	/* refclock burst delay (s) */
69290000Sglebius
70290000Sglebius/*
71290000Sglebius * pool soliciting restriction duration (s)
72290000Sglebius */
73290000Sglebius#define	POOL_SOLICIT_WINDOW	8
74290000Sglebius
75290000Sglebius/*
76290000Sglebius * peer_select groups statistics for a peer used by clock_select() and
77290000Sglebius * clock_cluster().
78290000Sglebius */
79290000Sglebiustypedef struct peer_select_tag {
80290000Sglebius	struct peer *	peer;
81290000Sglebius	double		synch;	/* sync distance */
82290000Sglebius	double		error;	/* jitter */
83290000Sglebius	double		seljit;	/* selection jitter */
84290000Sglebius} peer_select;
85290000Sglebius
86290000Sglebius/*
87290000Sglebius * System variables are declared here. Unless specified otherwise, all
88290000Sglebius * times are in seconds.
89290000Sglebius */
90290000Sglebiusu_char	sys_leap;		/* system leap indicator, use set_sys_leap() to change this */
91290000Sglebiusu_char	xmt_leap;		/* leap indicator sent in client requests, set up by set_sys_leap() */
92290000Sglebiusu_char	sys_stratum;		/* system stratum */
93182007Srobertos_char	sys_precision;		/* local clock precision (log2 s) */
9482505Srobertodouble	sys_rootdelay;		/* roundtrip delay to primary source */
95290000Sglebiusdouble	sys_rootdisp;		/* dispersion to primary source */
96290000Sglebiusu_int32 sys_refid;		/* reference id (network byte order) */
97290000Sglebiusl_fp	sys_reftime;		/* last update time */
98290000Sglebiusstruct	peer *sys_peer;		/* current peer */
9954359Sroberto
100290000Sglebius#ifdef LEAP_SMEAR
101290000Sglebiusstruct leap_smear_info leap_smear;
102290000Sglebius#endif
103290000Sglebiusint leap_sec_in_progress;
104290000Sglebius
10554359Sroberto/*
106290000Sglebius * Rate controls. Leaky buckets are used to throttle the packet
107290000Sglebius * transmission rates in order to protect busy servers such as at NIST
108290000Sglebius * and USNO. There is a counter for each association and another for KoD
109290000Sglebius * packets. The association counter decrements each second, but not
110290000Sglebius * below zero. Each time a packet is sent the counter is incremented by
111290000Sglebius * a configurable value representing the average interval between
112290000Sglebius * packets. A packet is delayed as long as the counter is greater than
113290000Sglebius * zero. Note this does not affect the time value computations.
11454359Sroberto */
115290000Sglebius/*
116290000Sglebius * Nonspecified system state variables
117290000Sglebius */
118132454Srobertoint	sys_bclient;		/* broadcast client enable */
119132454Srobertodouble	sys_bdelay;		/* broadcast client default delay */
12054359Srobertoint	sys_authenticate;	/* requre authentication for config */
12154359Srobertol_fp	sys_authdelay;		/* authentication delay */
122290000Sglebiusdouble	sys_offset;	/* current local clock offset */
123290000Sglebiusdouble	sys_mindisp = MINDISPERSE; /* minimum distance (s) */
124290000Sglebiusdouble	sys_maxdist = MAXDISTANCE; /* selection threshold */
125290000Sglebiusdouble	sys_jitter;		/* system jitter */
126290000Sglebiusu_long	sys_epoch;		/* last clock update time */
127290000Sglebiusstatic	double sys_clockhop;	/* clockhop threshold */
128290000Sglebiusstatic int leap_vote_ins;	/* leap consensus for insert */
129290000Sglebiusstatic int leap_vote_del;	/* leap consensus for delete */
13082505Srobertokeyid_t	sys_private;		/* private value for session seed */
13182505Srobertoint	sys_manycastserver;	/* respond to manycast client pkts */
132290000Sglebiusint	ntp_mode7;		/* respond to ntpdc (mode7) */
13382505Srobertoint	peer_ntpdate;		/* active peers in ntpdate mode */
134132454Srobertoint	sys_survivors;		/* truest of the truechimers */
135290000Sglebiuschar	*sys_ident = NULL;	/* identity scheme */
13654359Sroberto
13754359Sroberto/*
138132454Sroberto * TOS and multicast mapping stuff
139132454Sroberto */
140182007Srobertoint	sys_floor = 0;		/* cluster stratum floor */
141310419Sdelphiju_char	sys_bcpollbstep = 0;	/* Broadcast Poll backstep gate */
142290000Sglebiusint	sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
143132454Srobertoint	sys_minsane = 1;	/* minimum candidates */
144290000Sglebiusint	sys_minclock = NTP_MINCLOCK; /* minimum candidates */
145182007Srobertoint	sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
146132454Srobertoint	sys_cohort = 0;		/* cohort switch */
147182007Srobertoint	sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
148290000Sglebiusint	sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
149182007Srobertoint	sys_beacon = BEACON;	/* manycast beacon interval */
150132454Srobertoint	sys_ttlmax;		/* max ttl mapping vector index */
151132454Srobertou_char	sys_ttl[MAX_TTL];	/* ttl mapping vector */
152132454Sroberto
153132454Sroberto/*
154290000Sglebius * Statistics counters - first the good, then the bad
15554359Sroberto */
156290000Sglebiusu_long	sys_stattime;		/* elapsed time */
157132454Srobertou_long	sys_received;		/* packets received */
158290000Sglebiusu_long	sys_processed;		/* packets for this host */
159290000Sglebiusu_long	sys_newversion;		/* current version */
160290000Sglebiusu_long	sys_oldversion;		/* old version */
161132454Srobertou_long	sys_restricted;		/* access denied */
162132454Srobertou_long	sys_badlength;		/* bad length or format */
163132454Srobertou_long	sys_badauth;		/* bad authentication */
164290000Sglebiusu_long	sys_declined;		/* declined */
165132454Srobertou_long	sys_limitrejected;	/* rate exceeded */
166290000Sglebiusu_long	sys_kodsent;		/* KoD sent */
16754359Sroberto
168294904Sdelphij/*
169301301Sdelphij * Mechanism knobs: how soon do we peer_clear() or unpeer()?
170294904Sdelphij *
171294904Sdelphij * The default way is "on-receipt".  If this was a packet from a
172294904Sdelphij * well-behaved source, on-receipt will offer the fastest recovery.
173294904Sdelphij * If this was from a DoS attack, the default way makes it easier
174294904Sdelphij * for a bad-guy to DoS us.  So look and see what bites you harder
175294904Sdelphij * and choose according to your environment.
176294904Sdelphij */
177301301Sdelphijint peer_clear_digest_early	= 1;	/* bad digest (TEST5) and Autokey */
178294904Sdelphijint unpeer_crypto_early		= 1;	/* bad crypto (TEST9) */
179294904Sdelphijint unpeer_crypto_nak_early	= 1;	/* crypto_NAK (TEST5) */
180294904Sdelphijint unpeer_digest_early		= 1;	/* bad digest (TEST5) */
181294904Sdelphij
182298770Sdelphijint dynamic_interleave = DYNAMIC_INTERLEAVE;	/* Bug 2978 mitigation */
183298770Sdelphij
184298770Sdelphijint kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
185298770Sdelphijenum nak_error_codes valid_NAK(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
186290000Sglebiusstatic	double	root_distance	(struct peer *);
187290000Sglebiusstatic	void	clock_combine	(peer_select *, int, int);
188290000Sglebiusstatic	void	peer_xmit	(struct peer *);
189290000Sglebiusstatic	void	fast_xmit	(struct recvbuf *, int, keyid_t, int);
190290000Sglebiusstatic	void	pool_xmit	(struct peer *);
191290000Sglebiusstatic	void	clock_update	(struct peer *);
192290000Sglebiusstatic	void	measure_precision(void);
193290000Sglebiusstatic	double	measure_tick_fuzz(void);
194290000Sglebiusstatic	int	local_refid	(struct peer *);
195290000Sglebiusstatic	int	peer_unfit	(struct peer *);
196290000Sglebius#ifdef AUTOKEY
197290000Sglebiusstatic	int	group_test	(char *, char *);
198290000Sglebius#endif /* AUTOKEY */
199290000Sglebius#ifdef WORKER
200290000Sglebiusvoid	pool_name_resolved	(int, int, void *, const char *,
201290000Sglebius				 const char *, const struct addrinfo *,
202290000Sglebius				 const struct addrinfo *);
203290000Sglebius#endif /* WORKER */
20454359Sroberto
205293894Sglebiusconst char *	amtoa		(int am);
206293894Sglebius
207293894Sglebius
208290000Sglebiusvoid
209293894Sglebiusset_sys_leap(
210293894Sglebius	u_char new_sys_leap
211293894Sglebius	)
212293894Sglebius{
213290000Sglebius	sys_leap = new_sys_leap;
214290000Sglebius	xmt_leap = sys_leap;
215182007Sroberto
216290000Sglebius	/*
217290000Sglebius	 * Under certain conditions we send faked leap bits to clients, so
218290000Sglebius	 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
219290000Sglebius	 */
220290000Sglebius	if (xmt_leap != LEAP_NOTINSYNC) {
221290000Sglebius		if (leap_sec_in_progress) {
222290000Sglebius			/* always send "not sync" */
223290000Sglebius			xmt_leap = LEAP_NOTINSYNC;
224290000Sglebius		}
225290000Sglebius#ifdef LEAP_SMEAR
226290000Sglebius		else {
227290000Sglebius			/*
228293894Sglebius			 * If leap smear is enabled in general we must
229293894Sglebius			 * never send a leap second warning to clients,
230293894Sglebius			 * so make sure we only send "in sync".
231290000Sglebius			 */
232290000Sglebius			if (leap_smear.enabled)
233290000Sglebius				xmt_leap = LEAP_NOWARNING;
234290000Sglebius		}
235290000Sglebius#endif	/* LEAP_SMEAR */
236290000Sglebius	}
237290000Sglebius}
238290000Sglebius
239293894Sglebius
24054359Sroberto/*
241290000Sglebius * Kiss Code check
24254359Sroberto */
243293894Sglebiusint
244293894Sglebiuskiss_code_check(
245293894Sglebius	u_char hisleap,
246293894Sglebius	u_char hisstratum,
247293894Sglebius	u_char hismode,
248293894Sglebius	u_int32 refid
249293894Sglebius	)
250293894Sglebius{
251290000Sglebius
252293894Sglebius	if (   hismode == MODE_SERVER
253293894Sglebius	    && hisleap == LEAP_NOTINSYNC
254293894Sglebius	    && hisstratum == STRATUM_UNSPEC) {
255293894Sglebius		if(memcmp(&refid,"RATE", 4) == 0) {
256293894Sglebius			return (RATEKISS);
257293894Sglebius		} else if(memcmp(&refid,"DENY", 4) == 0) {
258293894Sglebius			return (DENYKISS);
259293894Sglebius		} else if(memcmp(&refid,"RSTR", 4) == 0) {
260293894Sglebius			return (RSTRKISS);
261293894Sglebius		} else if(memcmp(&refid,"X", 1) == 0) {
262293894Sglebius			return (XKISS);
263293894Sglebius		} else {
264293894Sglebius			return (UNKNOWNKISS);
265290000Sglebius		}
266293894Sglebius	} else {
267293894Sglebius		return (NOKISS);
268293894Sglebius	}
269290000Sglebius}
270293894Sglebius
271293894Sglebius
272298770Sdelphij/*
273298770Sdelphij * Check that NAK is valid
274298770Sdelphij */
275298770Sdelphijenum nak_error_codes
276298770Sdelphijvalid_NAK(
277298770Sdelphij	  struct peer *peer,
278298770Sdelphij	  struct recvbuf *rbufp,
279298770Sdelphij	  u_char hismode
280298770Sdelphij	  )
281298770Sdelphij{
282310419Sdelphij	int		base_packet_length = MIN_V4_PKT_LEN;
283301301Sdelphij	int		remainder_size;
284301301Sdelphij	struct pkt *	rpkt;
285301301Sdelphij	int		keyid;
286301301Sdelphij	l_fp		p_org;	/* origin timestamp */
287301301Sdelphij	const l_fp *	myorg;	/* selected peer origin */
288298770Sdelphij
289298770Sdelphij	/*
290298770Sdelphij	 * Check to see if there is something beyond the basic packet
291298770Sdelphij	 */
292298770Sdelphij	if (rbufp->recv_length == base_packet_length) {
293298770Sdelphij		return NONAK;
294298770Sdelphij	}
295298770Sdelphij
296298770Sdelphij	remainder_size = rbufp->recv_length - base_packet_length;
297298770Sdelphij	/*
298298770Sdelphij	 * Is this a potential NAK?
299298770Sdelphij	 */
300298770Sdelphij	if (remainder_size != 4) {
301298770Sdelphij		return NONAK;
302298770Sdelphij	}
303298770Sdelphij
304298770Sdelphij	/*
305298770Sdelphij	 * Only server responses can contain NAK's
306298770Sdelphij	 */
307298770Sdelphij
308298770Sdelphij	if (hismode != MODE_SERVER &&
309298770Sdelphij	    hismode != MODE_ACTIVE &&
310298770Sdelphij	    hismode != MODE_PASSIVE
311298770Sdelphij	    ) {
312301301Sdelphij		return INVALIDNAK;
313298770Sdelphij	}
314298770Sdelphij
315298770Sdelphij	/*
316298770Sdelphij	 * Make sure that the extra field in the packet is all zeros
317298770Sdelphij	 */
318298770Sdelphij	rpkt = &rbufp->recv_pkt;
319298770Sdelphij	keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
320298770Sdelphij	if (keyid != 0) {
321301301Sdelphij		return INVALIDNAK;
322298770Sdelphij	}
323298770Sdelphij
324298770Sdelphij	/*
325298770Sdelphij	 * Only valid if peer uses a key
326298770Sdelphij	 */
327301301Sdelphij	if (!peer || !peer->keyid || !(peer->flags & FLAG_SKEY)) {
328301301Sdelphij		return INVALIDNAK;
329298770Sdelphij	}
330301301Sdelphij
331301301Sdelphij	/*
332301301Sdelphij	 * The ORIGIN must match, or this cannot be a valid NAK, either.
333301301Sdelphij	 */
334301301Sdelphij	NTOHL_FP(&rpkt->org, &p_org);
335301301Sdelphij	if (peer->flip > 0)
336301301Sdelphij		myorg = &peer->borg;
337301301Sdelphij	else
338301301Sdelphij		myorg = &peer->aorg;
339310419Sdelphij
340301301Sdelphij	if (L_ISZERO(&p_org) ||
341301301Sdelphij	    L_ISZERO( myorg) ||
342301301Sdelphij	    !L_ISEQU(&p_org, myorg)) {
343301301Sdelphij		return INVALIDNAK;
344298770Sdelphij	}
345301301Sdelphij
346301301Sdelphij	/* If we ever passed all that checks, we should be safe. Well,
347301301Sdelphij	 * as safe as we can ever be with an unauthenticated crypto-nak.
348301301Sdelphij	 */
349301301Sdelphij	return VALIDNAK;
350298770Sdelphij}
351298770Sdelphij
352298770Sdelphij
353290000Sglebius/*
354290000Sglebius * transmit - transmit procedure called by poll timeout
355290000Sglebius */
35654359Srobertovoid
35754359Srobertotransmit(
35854359Sroberto	struct peer *peer	/* peer structure pointer */
35954359Sroberto	)
36054359Sroberto{
361290000Sglebius	u_char	hpoll;
36254359Sroberto
363132454Sroberto	/*
364132454Sroberto	 * The polling state machine. There are two kinds of machines,
365132454Sroberto	 * those that never expect a reply (broadcast and manycast
366132454Sroberto	 * server modes) and those that do (all other modes). The dance
367132454Sroberto	 * is intricate...
368132454Sroberto	 */
36954359Sroberto	hpoll = peer->hpoll;
370182007Sroberto
371182007Sroberto	/*
372182007Sroberto	 * In broadcast mode the poll interval is never changed from
373182007Sroberto	 * minpoll.
374182007Sroberto	 */
375132454Sroberto	if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
376182007Sroberto		peer->outdate = current_time;
377290000Sglebius		if (sys_leap != LEAP_NOTINSYNC)
378290000Sglebius			peer_xmit(peer);
379182007Sroberto		poll_update(peer, hpoll);
380182007Sroberto		return;
381182007Sroberto	}
38254359Sroberto
383182007Sroberto	/*
384182007Sroberto	 * In manycast mode we start with unity ttl. The ttl is
385182007Sroberto	 * increased by one for each poll until either sys_maxclock
386182007Sroberto	 * servers have been found or the maximum ttl is reached. When
387182007Sroberto	 * sys_maxclock servers are found we stop polling until one or
388290000Sglebius	 * more servers have timed out or until less than sys_minclock
389182007Sroberto	 * associations turn up. In this case additional better servers
390290000Sglebius	 * are dragged in and preempt the existing ones.  Once every
391290000Sglebius	 * sys_beacon seconds we are to transmit unconditionally, but
392290000Sglebius	 * this code is not quite right -- peer->unreach counts polls
393290000Sglebius	 * and is being compared with sys_beacon, so the beacons happen
394290000Sglebius	 * every sys_beacon polls.
395182007Sroberto	 */
396182007Sroberto	if (peer->cast_flags & MDF_ACAST) {
397182007Sroberto		peer->outdate = current_time;
398182007Sroberto		if (peer->unreach > sys_beacon) {
399182007Sroberto			peer->unreach = 0;
400182007Sroberto			peer->ttl = 0;
401182007Sroberto			peer_xmit(peer);
402290000Sglebius		} else if (   sys_survivors < sys_minclock
403290000Sglebius			   || peer_associations < sys_maxclock) {
404290000Sglebius			if (peer->ttl < (u_int32)sys_ttlmax)
405182007Sroberto				peer->ttl++;
406182007Sroberto			peer_xmit(peer);
407182007Sroberto		}
408182007Sroberto		peer->unreach++;
409182007Sroberto		poll_update(peer, hpoll);
410182007Sroberto		return;
411182007Sroberto	}
41282505Sroberto
413182007Sroberto	/*
414290000Sglebius	 * Pool associations transmit unicast solicitations when there
415290000Sglebius	 * are less than a hard limit of 2 * sys_maxclock associations,
416290000Sglebius	 * and either less than sys_minclock survivors or less than
417290000Sglebius	 * sys_maxclock associations.  The hard limit prevents unbounded
418290000Sglebius	 * growth in associations if the system clock or network quality
419290000Sglebius	 * result in survivor count dipping below sys_minclock often.
420290000Sglebius	 * This was observed testing with pool, where sys_maxclock == 12
421290000Sglebius	 * resulted in 60 associations without the hard limit.  A
422290000Sglebius	 * similar hard limit on manycastclient ephemeral associations
423290000Sglebius	 * may be appropriate.
424290000Sglebius	 */
425290000Sglebius	if (peer->cast_flags & MDF_POOL) {
426290000Sglebius		peer->outdate = current_time;
427290000Sglebius		if (   (peer_associations <= 2 * sys_maxclock)
428290000Sglebius		    && (   peer_associations < sys_maxclock
429293894Sglebius			|| sys_survivors < sys_minclock))
430290000Sglebius			pool_xmit(peer);
431290000Sglebius		poll_update(peer, hpoll);
432290000Sglebius		return;
433290000Sglebius	}
434290000Sglebius
435290000Sglebius	/*
436182007Sroberto	 * In unicast modes the dance is much more intricate. It is
437290000Sglebius	 * designed to back off whenever possible to minimize network
438182007Sroberto	 * traffic.
439182007Sroberto	 */
440182007Sroberto	if (peer->burst == 0) {
441182007Sroberto		u_char oreach;
442182007Sroberto
443132454Sroberto		/*
444182007Sroberto		 * Update the reachability status. If not heard for
445182007Sroberto		 * three consecutive polls, stuff infinity in the clock
446290000Sglebius		 * filter.
447132454Sroberto		 */
448182007Sroberto		oreach = peer->reach;
449182007Sroberto		peer->outdate = current_time;
450290000Sglebius		peer->unreach++;
451182007Sroberto		peer->reach <<= 1;
452182007Sroberto		if (!peer->reach) {
45382505Sroberto
454182007Sroberto			/*
455182007Sroberto			 * Here the peer is unreachable. If it was
456290000Sglebius			 * previously reachable raise a trap. Send a
457290000Sglebius			 * burst if enabled.
458182007Sroberto			 */
459290000Sglebius			clock_filter(peer, 0., 0., MAXDISPERSE);
460182007Sroberto			if (oreach) {
461290000Sglebius				peer_unfit(peer);
462290000Sglebius				report_event(PEVNT_UNREACH, peer, NULL);
463182007Sroberto			}
464290000Sglebius			if (   (peer->flags & FLAG_IBURST)
465290000Sglebius			    && peer->retry == 0)
466290000Sglebius				peer->retry = NTP_RETRY;
467182007Sroberto		} else {
468182007Sroberto
469182007Sroberto			/*
470290000Sglebius			 * Here the peer is reachable. Send a burst if
471290000Sglebius			 * enabled and the peer is fit.  Reset unreach
472290000Sglebius			 * for persistent and ephemeral associations.
473290000Sglebius			 * Unreach is also reset for survivors in
474290000Sglebius			 * clock_select().
475182007Sroberto			 */
476290000Sglebius			hpoll = sys_poll;
477290000Sglebius			if (!(peer->flags & FLAG_PREEMPT))
478182007Sroberto				peer->unreach = 0;
479290000Sglebius			if (   (peer->flags & FLAG_BURST)
480290000Sglebius			    && peer->retry == 0
481290000Sglebius			    && !peer_unfit(peer))
482290000Sglebius				peer->retry = NTP_RETRY;
483182007Sroberto		}
484182007Sroberto
485132454Sroberto		/*
486290000Sglebius		 * Watch for timeout.  If ephemeral, toss the rascal;
487290000Sglebius		 * otherwise, bump the poll interval. Note the
488290000Sglebius		 * poll_update() routine will clamp it to maxpoll.
489290000Sglebius		 * If preemptible and we have more peers than maxclock,
490290000Sglebius		 * and this peer has the minimum score of preemptibles,
491290000Sglebius		 * demobilize.
492290000Sglebius		 */
493132454Sroberto		if (peer->unreach >= NTP_UNREACH) {
494290000Sglebius			hpoll++;
495290000Sglebius			/* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
496290000Sglebius			if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
497290000Sglebius				report_event(PEVNT_RESTART, peer, "timeout");
498182007Sroberto				peer_clear(peer, "TIME");
49982505Sroberto				unpeer(peer);
50082505Sroberto				return;
50182505Sroberto			}
502290000Sglebius			if (   (peer->flags & FLAG_PREEMPT)
503290000Sglebius			    && (peer_associations > sys_maxclock)
504290000Sglebius			    && score_all(peer)) {
505290000Sglebius				report_event(PEVNT_RESTART, peer, "timeout");
506290000Sglebius				peer_clear(peer, "TIME");
507290000Sglebius				unpeer(peer);
508290000Sglebius				return;
509290000Sglebius			}
51082505Sroberto		}
511182007Sroberto	} else {
512182007Sroberto		peer->burst--;
513132454Sroberto		if (peer->burst == 0) {
51454359Sroberto
51554359Sroberto			/*
516182007Sroberto			 * If ntpdate mode and the clock has not been
517182007Sroberto			 * set and all peers have completed the burst,
518182007Sroberto			 * we declare a successful failure.
51954359Sroberto			 */
520182007Sroberto			if (mode_ntpdate) {
521182007Sroberto				peer_ntpdate--;
522182007Sroberto				if (peer_ntpdate == 0) {
523132454Sroberto					msyslog(LOG_NOTICE,
524290000Sglebius					    "ntpd: no servers found");
525290000Sglebius					if (!msyslog_term)
526290000Sglebius						printf(
527290000Sglebius						    "ntpd: no servers found\n");
528132454Sroberto					exit (0);
529132454Sroberto				}
53054359Sroberto			}
53154359Sroberto		}
53254359Sroberto	}
533290000Sglebius	if (peer->retry > 0)
534290000Sglebius		peer->retry--;
53554359Sroberto
53654359Sroberto	/*
537290000Sglebius	 * Do not transmit if in broadcast client mode.
53854359Sroberto	 */
539182007Sroberto	if (peer->hmode != MODE_BCLIENT)
540182007Sroberto		peer_xmit(peer);
541132454Sroberto	poll_update(peer, hpoll);
542293894Sglebius
543293894Sglebius	return;
54454359Sroberto}
54554359Sroberto
546182007Sroberto
547293894Sglebiusconst char *
548293894Sglebiusamtoa(
549293894Sglebius	int am
550293894Sglebius	)
551293894Sglebius{
552293894Sglebius	char *bp;
553293894Sglebius
554293894Sglebius	switch(am) {
555293894Sglebius	    case AM_ERR:	return "AM_ERR";
556293894Sglebius	    case AM_NOMATCH:	return "AM_NOMATCH";
557293894Sglebius	    case AM_PROCPKT:	return "AM_PROCPKT";
558293894Sglebius	    case AM_BCST:	return "AM_BCST";
559293894Sglebius	    case AM_FXMIT:	return "AM_FXMIT";
560293894Sglebius	    case AM_MANYCAST:	return "AM_MANYCAST";
561293894Sglebius	    case AM_NEWPASS:	return "AM_NEWPASS";
562293894Sglebius	    case AM_NEWBCL:	return "AM_NEWBCL";
563293894Sglebius	    case AM_POSSBCL:	return "AM_POSSBCL";
564293894Sglebius	    default:
565293894Sglebius		LIB_GETBUF(bp);
566293894Sglebius		snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
567293894Sglebius		return bp;
568293894Sglebius	}
569293894Sglebius}
570293894Sglebius
571293894Sglebius
57254359Sroberto/*
573290000Sglebius * receive - receive procedure called for each packet received
57454359Sroberto */
57554359Srobertovoid
57654359Srobertoreceive(
57754359Sroberto	struct recvbuf *rbufp
57854359Sroberto	)
57954359Sroberto{
580132454Sroberto	register struct peer *peer;	/* peer structure pointer */
581132454Sroberto	register struct pkt *pkt;	/* receive packet pointer */
582290000Sglebius	u_char	hisversion;		/* packet version */
583290000Sglebius	u_char	hisleap;		/* packet leap indicator */
584290000Sglebius	u_char	hismode;		/* packet mode */
585290000Sglebius	u_char	hisstratum;		/* packet stratum */
586290000Sglebius	u_short	restrict_mask;		/* restrict bits */
587293894Sglebius	const char *hm_str;		/* hismode string */
588293894Sglebius	const char *am_str;		/* association match string */
589293894Sglebius	int	kissCode = NOKISS;	/* Kiss Code */
590132454Sroberto	int	has_mac;		/* length of MAC field */
591132454Sroberto	int	authlen;		/* offset of MAC field */
592301301Sdelphij	int	is_authentic = AUTH_NONE;	/* cryptosum ok */
593298770Sdelphij	int	crypto_nak_test;	/* result of crypto-NAK check */
594290000Sglebius	int	retcode = AM_NOMATCH;	/* match code */
595290000Sglebius	keyid_t	skeyid = 0;		/* key IDs */
596290000Sglebius	u_int32	opcode = 0;		/* extension field opcode */
597293894Sglebius	sockaddr_u *dstadr_sin;		/* active runway */
598132454Sroberto	struct peer *peer2;		/* aux peer structure pointer */
599293894Sglebius	endpt	*match_ep;		/* newpeer() local address */
600182007Sroberto	l_fp	p_org;			/* origin timestamp */
601182007Sroberto	l_fp	p_rec;			/* receive timestamp */
602132454Sroberto	l_fp	p_xmt;			/* transmit timestamp */
603290000Sglebius#ifdef AUTOKEY
604290000Sglebius	char	hostname[NTP_MAXSTRLEN + 1];
605290000Sglebius	char	*groupname = NULL;
606132454Sroberto	struct autokey *ap;		/* autokey structure pointer */
607132454Sroberto	int	rval;			/* cookie snatcher */
608290000Sglebius	keyid_t	pkeyid = 0, tkeyid = 0;	/* key IDs */
609290000Sglebius#endif	/* AUTOKEY */
610290000Sglebius#ifdef HAVE_NTP_SIGND
611290000Sglebius	static unsigned char zero_key[16];
612290000Sglebius#endif /* HAVE_NTP_SIGND */
61354359Sroberto
61454359Sroberto	/*
61582505Sroberto	 * Monitor the packet and get restrictions. Note that the packet
61682505Sroberto	 * length for control and private mode packets must be checked
617290000Sglebius	 * by the service routines. Some restrictions have to be handled
618290000Sglebius	 * later in order to generate a kiss-o'-death packet.
61954359Sroberto	 */
620132454Sroberto	/*
621132454Sroberto	 * Bogus port check is before anything, since it probably
622132454Sroberto	 * reveals a clogging attack.
623132454Sroberto	 */
624132454Sroberto	sys_received++;
625290000Sglebius	if (0 == SRCPORT(&rbufp->recv_srcadr)) {
626132454Sroberto		sys_badlength++;
627132454Sroberto		return;				/* bogus port */
628132454Sroberto	}
629290000Sglebius	restrict_mask = restrictions(&rbufp->recv_srcadr);
630293894Sglebius	pkt = &rbufp->recv_pkt;
631293894Sglebius	DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\n",
632132454Sroberto		    current_time, stoa(&rbufp->dstadr->sin),
633293894Sglebius		    stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,
634293894Sglebius		    restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
635293894Sglebius		    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
636182007Sroberto	hisversion = PKT_VERSION(pkt->li_vn_mode);
637182007Sroberto	hisleap = PKT_LEAP(pkt->li_vn_mode);
638132454Sroberto	hismode = (int)PKT_MODE(pkt->li_vn_mode);
639182007Sroberto	hisstratum = PKT_TO_STRATUM(pkt->stratum);
640301301Sdelphij	INSIST(0 != hisstratum);
641301301Sdelphij
642290000Sglebius	if (restrict_mask & RES_IGNORE) {
643290000Sglebius		sys_restricted++;
644290000Sglebius		return;				/* ignore everything */
645290000Sglebius	}
646132454Sroberto	if (hismode == MODE_PRIVATE) {
647290000Sglebius		if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
648132454Sroberto			sys_restricted++;
64982505Sroberto			return;			/* no query private */
650132454Sroberto		}
65156749Sroberto		process_private(rbufp, ((restrict_mask &
65256749Sroberto		    RES_NOMODIFY) == 0));
65354359Sroberto		return;
65454359Sroberto	}
655132454Sroberto	if (hismode == MODE_CONTROL) {
656132454Sroberto		if (restrict_mask & RES_NOQUERY) {
657132454Sroberto			sys_restricted++;
65882505Sroberto			return;			/* no query control */
659132454Sroberto		}
66054359Sroberto		process_control(rbufp, restrict_mask);
66154359Sroberto		return;
66254359Sroberto	}
663132454Sroberto	if (restrict_mask & RES_DONTSERVE) {
664132454Sroberto		sys_restricted++;
665290000Sglebius		return;				/* no time serve */
666132454Sroberto	}
667290000Sglebius
668290000Sglebius	/*
669290000Sglebius	 * This is for testing. If restricted drop ten percent of
670290000Sglebius	 * surviving packets.
671290000Sglebius	 */
672290000Sglebius	if (restrict_mask & RES_FLAKE) {
673290000Sglebius		if ((double)ntp_random() / 0x7fffffff < .1) {
674290000Sglebius			sys_restricted++;
675290000Sglebius			return;			/* no flakeway */
676290000Sglebius		}
67782505Sroberto	}
678290000Sglebius
679132454Sroberto	/*
680132454Sroberto	 * Version check must be after the query packets, since they
681290000Sglebius	 * intentionally use an early version.
682132454Sroberto	 */
683182007Sroberto	if (hisversion == NTP_VERSION) {
684290000Sglebius		sys_newversion++;		/* new version */
685290000Sglebius	} else if (   !(restrict_mask & RES_VERSION)
686290000Sglebius		   && hisversion >= NTP_OLDVERSION) {
687290000Sglebius		sys_oldversion++;		/* previous version */
688132454Sroberto	} else {
689290000Sglebius		sys_badlength++;
690132454Sroberto		return;				/* old version */
691132454Sroberto	}
69254359Sroberto
69354359Sroberto	/*
694132454Sroberto	 * Figure out his mode and validate the packet. This has some
695132454Sroberto	 * legacy raunch that probably should be removed. In very early
696132454Sroberto	 * NTP versions mode 0 was equivalent to what later versions
697132454Sroberto	 * would interpret as client mode.
69854359Sroberto	 */
69982505Sroberto	if (hismode == MODE_UNSPEC) {
700182007Sroberto		if (hisversion == NTP_OLDVERSION) {
701132454Sroberto			hismode = MODE_CLIENT;
702132454Sroberto		} else {
703132454Sroberto			sys_badlength++;
704132454Sroberto			return;                 /* invalid mode */
705132454Sroberto		}
70682505Sroberto	}
70754359Sroberto
70854359Sroberto	/*
70982505Sroberto	 * Parse the extension field if present. We figure out whether
71082505Sroberto	 * an extension field is present by measuring the MAC size. If
711182007Sroberto	 * the number of words following the packet header is 0, no MAC
712182007Sroberto	 * is present and the packet is not authenticated. If 1, the
713182007Sroberto	 * packet is a crypto-NAK; if 3, the packet is authenticated
714290000Sglebius	 * with DES; if 5, the packet is authenticated with MD5; if 6,
715290000Sglebius	 * the packet is authenticated with SHA. If 2 or * 4, the packet
716290000Sglebius	 * is a runt and discarded forthwith. If greater than 6, an
717290000Sglebius	 * extension field is present, so we subtract the length of the
718290000Sglebius	 * field and go around again.
71954359Sroberto	 */
720298770Sdelphij
72154359Sroberto	authlen = LEN_PKT_NOMAC;
722132454Sroberto	has_mac = rbufp->recv_length - authlen;
723132454Sroberto	while (has_mac > 0) {
724290000Sglebius		u_int32	len;
725290000Sglebius#ifdef AUTOKEY
726290000Sglebius		u_int32	hostlen;
727290000Sglebius		struct exten *ep;
728290000Sglebius#endif /*AUTOKEY */
72982505Sroberto
730290000Sglebius		if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
73154359Sroberto			sys_badlength++;
732290000Sglebius			return;			/* bad length */
73354359Sroberto		}
734290000Sglebius		if (has_mac <= (int)MAX_MAC_LEN) {
73582505Sroberto			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
73682505Sroberto			break;
73754359Sroberto
738290000Sglebius		} else {
739290000Sglebius			opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
740290000Sglebius			len = opcode & 0xffff;
741290000Sglebius			if (   len % 4 != 0
742290000Sglebius			    || len < 4
743290000Sglebius			    || (int)len + authlen > rbufp->recv_length) {
74482505Sroberto				sys_badlength++;
745290000Sglebius				return;		/* bad length */
74682505Sroberto			}
747290000Sglebius#ifdef AUTOKEY
748290000Sglebius			/*
749290000Sglebius			 * Extract calling group name for later.  If
750290000Sglebius			 * sys_groupname is non-NULL, there must be
751290000Sglebius			 * a group name provided to elicit a response.
752290000Sglebius			 */
753290000Sglebius			if (   (opcode & 0x3fff0000) == CRYPTO_ASSOC
754290000Sglebius			    && sys_groupname != NULL) {
755290000Sglebius				ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
756290000Sglebius				hostlen = ntohl(ep->vallen);
757290000Sglebius				if (   hostlen >= sizeof(hostname)
758290000Sglebius				    || hostlen > len -
759290000Sglebius						offsetof(struct exten, pkt)) {
760290000Sglebius					sys_badlength++;
761290000Sglebius					return;		/* bad length */
762290000Sglebius				}
763290000Sglebius				memcpy(hostname, &ep->pkt, hostlen);
764290000Sglebius				hostname[hostlen] = '\0';
765290000Sglebius				groupname = strchr(hostname, '@');
766290000Sglebius				if (groupname == NULL) {
767290000Sglebius					sys_declined++;
768290000Sglebius					return;
769290000Sglebius				}
770290000Sglebius				groupname++;
771290000Sglebius			}
772290000Sglebius#endif /* AUTOKEY */
773290000Sglebius			authlen += len;
774290000Sglebius			has_mac -= len;
77582505Sroberto		}
77654359Sroberto	}
777290000Sglebius
778281232Sdelphij	/*
779281232Sdelphij	 * If has_mac is < 0 we had a malformed packet.
780281232Sdelphij	 */
781281232Sdelphij	if (has_mac < 0) {
782281232Sdelphij		sys_badlength++;
783281232Sdelphij		return;		/* bad length */
784281232Sdelphij	}
78554359Sroberto
78654359Sroberto	/*
787290000Sglebius	 * If authentication required, a MAC must be present.
788290000Sglebius	 */
789290000Sglebius	if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
790290000Sglebius		sys_restricted++;
791290000Sglebius		return;				/* access denied */
792290000Sglebius	}
793290000Sglebius
794290000Sglebius	/*
795290000Sglebius	 * Update the MRU list and finger the cloggers. It can be a
796290000Sglebius	 * little expensive, so turn it off for production use.
797290000Sglebius	 * RES_LIMITED and RES_KOD will be cleared in the returned
798290000Sglebius	 * restrict_mask unless one or both actions are warranted.
799290000Sglebius	 */
800290000Sglebius	restrict_mask = ntp_monitor(rbufp, restrict_mask);
801290000Sglebius	if (restrict_mask & RES_LIMITED) {
802290000Sglebius		sys_limitrejected++;
803290000Sglebius		if (   !(restrict_mask & RES_KOD)
804290000Sglebius		    || MODE_BROADCAST == hismode
805290000Sglebius		    || MODE_SERVER == hismode) {
806290000Sglebius			if (MODE_SERVER == hismode)
807290000Sglebius				DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
808290000Sglebius					stoa(&rbufp->recv_srcadr)));
809290000Sglebius			return;			/* rate exceeded */
810290000Sglebius		}
811290000Sglebius		if (hismode == MODE_CLIENT)
812290000Sglebius			fast_xmit(rbufp, MODE_SERVER, skeyid,
813290000Sglebius			    restrict_mask);
814290000Sglebius		else
815290000Sglebius			fast_xmit(rbufp, MODE_ACTIVE, skeyid,
816290000Sglebius			    restrict_mask);
817290000Sglebius		return;				/* rate exceeded */
818290000Sglebius	}
819290000Sglebius	restrict_mask &= ~RES_KOD;
820290000Sglebius
821290000Sglebius	/*
82282505Sroberto	 * We have tossed out as many buggy packets as possible early in
82382505Sroberto	 * the game to reduce the exposure to a clogging attack. Now we
82482505Sroberto	 * have to burn some cycles to find the association and
82582505Sroberto	 * authenticate the packet if required. Note that we burn only
826290000Sglebius	 * digest cycles, again to reduce exposure. There may be no
82782505Sroberto	 * matching association and that's okay.
82882505Sroberto	 *
82982505Sroberto	 * More on the autokey mambo. Normally the local interface is
83082505Sroberto	 * found when the association was mobilized with respect to a
83182505Sroberto	 * designated remote address. We assume packets arriving from
83282505Sroberto	 * the remote address arrive via this interface and the local
83382505Sroberto	 * address used to construct the autokey is the unicast address
83482505Sroberto	 * of the interface. However, if the sender is a broadcaster,
83582505Sroberto	 * the interface broadcast address is used instead.
836290000Sglebius	 * Notwithstanding this technobabble, if the sender is a
83782505Sroberto	 * multicaster, the broadcast address is null, so we use the
83882505Sroberto	 * unicast address anyway. Don't ask.
83954359Sroberto	 */
840290000Sglebius	peer = findpeer(rbufp,  hismode, &retcode);
84182505Sroberto	dstadr_sin = &rbufp->dstadr->sin;
842182007Sroberto	NTOHL_FP(&pkt->org, &p_org);
843182007Sroberto	NTOHL_FP(&pkt->rec, &p_rec);
844182007Sroberto	NTOHL_FP(&pkt->xmt, &p_xmt);
845293894Sglebius	hm_str = modetoa(hismode);
846293894Sglebius	am_str = amtoa(retcode);
847182007Sroberto
848182007Sroberto	/*
849182007Sroberto	 * Authentication is conditioned by three switches:
850182007Sroberto	 *
851182007Sroberto	 * NOPEER  (RES_NOPEER) do not mobilize an association unless
852182007Sroberto	 *         authenticated
853182007Sroberto	 * NOTRUST (RES_DONTTRUST) do not allow access unless
854182007Sroberto	 *         authenticated (implies NOPEER)
855182007Sroberto	 * enable  (sys_authenticate) master NOPEER switch, by default
856182007Sroberto	 *         on
857182007Sroberto	 *
858182007Sroberto	 * The NOPEER and NOTRUST can be specified on a per-client basis
859182007Sroberto	 * using the restrict command. The enable switch if on implies
860182007Sroberto	 * NOPEER for all clients. There are four outcomes:
861182007Sroberto	 *
862182007Sroberto	 * NONE    The packet has no MAC.
863182007Sroberto	 * OK      the packet has a MAC and authentication succeeds
864182007Sroberto	 * ERROR   the packet has a MAC and authentication fails
865182007Sroberto	 * CRYPTO  crypto-NAK. The MAC has four octets only.
866182007Sroberto	 *
867182007Sroberto	 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
868182007Sroberto	 * is zero, acceptable outcomes of y are NONE and OK. If x is
869182007Sroberto	 * one, the only acceptable outcome of y is OK.
870182007Sroberto	 */
871298770Sdelphij	crypto_nak_test = valid_NAK(peer, rbufp, hismode);
872290000Sglebius
873298770Sdelphij	/*
874298770Sdelphij	 * Drop any invalid crypto-NAKs
875298770Sdelphij	 */
876298770Sdelphij	if (crypto_nak_test == INVALIDNAK) {
877298770Sdelphij		report_event(PEVNT_AUTH, peer, "Invalid_NAK");
878298770Sdelphij		if (0 != peer) {
879298770Sdelphij			peer->badNAK++;
880298770Sdelphij		}
881298770Sdelphij		msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
882298770Sdelphij			current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
883298770Sdelphij		return;
884298770Sdelphij	}
885298770Sdelphij
88654359Sroberto	if (has_mac == 0) {
887290000Sglebius		restrict_mask &= ~RES_MSSNTP;
888182007Sroberto		is_authentic = AUTH_NONE; /* not required */
889293894Sglebius		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
890182007Sroberto			    current_time, stoa(dstadr_sin),
891293894Sglebius			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
892293894Sglebius			    authlen,
893293894Sglebius			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
894293894Sglebius			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
895298770Sdelphij	} else if (crypto_nak_test == VALIDNAK) {
896290000Sglebius		restrict_mask &= ~RES_MSSNTP;
897290000Sglebius		is_authentic = AUTH_CRYPTO; /* crypto-NAK */
898293894Sglebius		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\n",
899182007Sroberto			    current_time, stoa(dstadr_sin),
900293894Sglebius			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
901293894Sglebius			    skeyid, authlen + has_mac, is_authentic,
902293894Sglebius			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
903293894Sglebius			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
904290000Sglebius
905290000Sglebius#ifdef HAVE_NTP_SIGND
906290000Sglebius		/*
907290000Sglebius		 * If the signature is 20 bytes long, the last 16 of
908290000Sglebius		 * which are zero, then this is a Microsoft client
909290000Sglebius		 * wanting AD-style authentication of the server's
910290000Sglebius		 * reply.
911290000Sglebius		 *
912290000Sglebius		 * This is described in Microsoft's WSPP docs, in MS-SNTP:
913290000Sglebius		 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
914290000Sglebius		 */
915290000Sglebius	} else if (   has_mac == MAX_MD5_LEN
916290000Sglebius		   && (restrict_mask & RES_MSSNTP)
917290000Sglebius		   && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
918290000Sglebius		   && (memcmp(zero_key, (char *)pkt + authlen + 4,
919293894Sglebius			      MAX_MD5_LEN - 4) == 0)) {
920290000Sglebius		is_authentic = AUTH_NONE;
921290000Sglebius#endif /* HAVE_NTP_SIGND */
922290000Sglebius
92354359Sroberto	} else {
924290000Sglebius		restrict_mask &= ~RES_MSSNTP;
925290000Sglebius#ifdef AUTOKEY
92682505Sroberto		/*
92782505Sroberto		 * For autokey modes, generate the session key
92882505Sroberto		 * and install in the key cache. Use the socket
92982505Sroberto		 * broadcast or unicast address as appropriate.
93082505Sroberto		 */
931290000Sglebius		if (crypto_flags && skeyid > NTP_MAXKEY) {
932290000Sglebius
93382505Sroberto			/*
93482505Sroberto			 * More on the autokey dance (AKD). A cookie is
93582505Sroberto			 * constructed from public and private values.
93682505Sroberto			 * For broadcast packets, the cookie is public
93782505Sroberto			 * (zero). For packets that match no
93882505Sroberto			 * association, the cookie is hashed from the
93982505Sroberto			 * addresses and private value. For server
94082505Sroberto			 * packets, the cookie was previously obtained
94182505Sroberto			 * from the server. For symmetric modes, the
94282505Sroberto			 * cookie was previously constructed using an
94382505Sroberto			 * agreement protocol; however, should PKI be
94482505Sroberto			 * unavailable, we construct a fake agreement as
94582505Sroberto			 * the EXOR of the peer and host cookies.
94682505Sroberto			 *
94782505Sroberto			 * hismode	ephemeral	persistent
94882505Sroberto			 * =======================================
94982505Sroberto			 * active	0		cookie#
95082505Sroberto			 * passive	0%		cookie#
95182505Sroberto			 * client	sys cookie	0%
95282505Sroberto			 * server	0%		sys cookie
95382505Sroberto			 * broadcast	0		0
95482505Sroberto			 *
95582505Sroberto			 * # if unsync, 0
95682505Sroberto			 * % can't happen
95782505Sroberto			 */
958290000Sglebius			if (has_mac < (int)MAX_MD5_LEN) {
959290000Sglebius				sys_badauth++;
960290000Sglebius				return;
961290000Sglebius			}
96282505Sroberto			if (hismode == MODE_BROADCAST) {
96354359Sroberto
96482505Sroberto				/*
96582505Sroberto				 * For broadcaster, use the interface
96682505Sroberto				 * broadcast address when available;
96782505Sroberto				 * otherwise, use the unicast address
96882505Sroberto				 * found when the association was
969182007Sroberto				 * mobilized. However, if this is from
970182007Sroberto				 * the wildcard interface, game over.
97182505Sroberto				 */
972290000Sglebius				if (   crypto_flags
973290000Sglebius				    && rbufp->dstadr ==
974290000Sglebius				       ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
975182007Sroberto					sys_restricted++;
976182007Sroberto					return;	     /* no wildcard */
977182007Sroberto				}
97882505Sroberto				pkeyid = 0;
979290000Sglebius				if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
98082505Sroberto					dstadr_sin =
98182505Sroberto					    &rbufp->dstadr->bcast;
98282505Sroberto			} else if (peer == NULL) {
98382505Sroberto				pkeyid = session_key(
98482505Sroberto				    &rbufp->recv_srcadr, dstadr_sin, 0,
98582505Sroberto				    sys_private, 0);
98682505Sroberto			} else {
987132454Sroberto				pkeyid = peer->pcookie;
98882505Sroberto			}
98982505Sroberto
99054359Sroberto			/*
99182505Sroberto			 * The session key includes both the public
99282505Sroberto			 * values and cookie. In case of an extension
99382505Sroberto			 * field, the cookie used for authentication
99482505Sroberto			 * purposes is zero. Note the hash is saved for
99582505Sroberto			 * use later in the autokey mambo.
99654359Sroberto			 */
997290000Sglebius			if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
99882505Sroberto				session_key(&rbufp->recv_srcadr,
99982505Sroberto				    dstadr_sin, skeyid, 0, 2);
100054359Sroberto				tkeyid = session_key(
100182505Sroberto				    &rbufp->recv_srcadr, dstadr_sin,
100282505Sroberto				    skeyid, pkeyid, 0);
100382505Sroberto			} else {
100454359Sroberto				tkeyid = session_key(
100582505Sroberto				    &rbufp->recv_srcadr, dstadr_sin,
100682505Sroberto				    skeyid, pkeyid, 2);
100754359Sroberto			}
100854359Sroberto
100954359Sroberto		}
1010290000Sglebius#endif	/* AUTOKEY */
101154359Sroberto
101254359Sroberto		/*
101354359Sroberto		 * Compute the cryptosum. Note a clogging attack may
101482505Sroberto		 * succeed in bloating the key cache. If an autokey,
101582505Sroberto		 * purge it immediately, since we won't be needing it
1016182007Sroberto		 * again. If the packet is authentic, it can mobilize an
1017182007Sroberto		 * association. Note that there is no key zero.
101854359Sroberto		 */
1019182007Sroberto		if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1020290000Sglebius		    has_mac))
1021182007Sroberto			is_authentic = AUTH_ERROR;
1022290000Sglebius		else
1023182007Sroberto			is_authentic = AUTH_OK;
1024290000Sglebius#ifdef AUTOKEY
1025290000Sglebius		if (crypto_flags && skeyid > NTP_MAXKEY)
102682505Sroberto			authtrust(skeyid, 0);
1027290000Sglebius#endif	/* AUTOKEY */
1028293894Sglebius		DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n",
1029132454Sroberto			    current_time, stoa(dstadr_sin),
1030293894Sglebius			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1031293894Sglebius			    skeyid, authlen + has_mac, is_authentic,
1032293894Sglebius			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1033293894Sglebius			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
103454359Sroberto	}
103554359Sroberto
103654359Sroberto	/*
103782505Sroberto	 * The association matching rules are implemented by a set of
1038182007Sroberto	 * routines and an association table. A packet matching an
1039182007Sroberto	 * association is processed by the peer process for that
1040182007Sroberto	 * association. If there are no errors, an ephemeral association
1041182007Sroberto	 * is mobilized: a broadcast packet mobilizes a broadcast client
1042132454Sroberto	 * aassociation; a manycast server packet mobilizes a manycast
1043132454Sroberto	 * client association; a symmetric active packet mobilizes a
1044182007Sroberto	 * symmetric passive association.
104554359Sroberto	 */
104654359Sroberto	switch (retcode) {
1047182007Sroberto
1048182007Sroberto	/*
1049182007Sroberto	 * This is a client mode packet not matching any association. If
1050182007Sroberto	 * an ordinary client, simply toss a server mode packet back
1051182007Sroberto	 * over the fence. If a manycast client, we have to work a
1052182007Sroberto	 * little harder.
1053182007Sroberto	 */
105454359Sroberto	case AM_FXMIT:
105554359Sroberto
105656749Sroberto		/*
1057290000Sglebius		 * If authentication OK, send a server reply; otherwise,
1058290000Sglebius		 * send a crypto-NAK.
105956749Sroberto		 */
1060182007Sroberto		if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1061182007Sroberto			if (AUTH(restrict_mask & RES_DONTTRUST,
1062290000Sglebius			   is_authentic)) {
1063182007Sroberto				fast_xmit(rbufp, MODE_SERVER, skeyid,
1064182007Sroberto				    restrict_mask);
1065290000Sglebius			} else if (is_authentic == AUTH_ERROR) {
1066182007Sroberto				fast_xmit(rbufp, MODE_SERVER, 0,
1067182007Sroberto				    restrict_mask);
1068290000Sglebius				sys_badauth++;
1069290000Sglebius			} else {
1070290000Sglebius				sys_restricted++;
1071290000Sglebius			}
1072182007Sroberto			return;			/* hooray */
107356749Sroberto		}
107454359Sroberto
107556749Sroberto		/*
1076182007Sroberto		 * This must be manycast. Do not respond if not
1077182007Sroberto		 * configured as a manycast server.
107856749Sroberto		 */
1079182007Sroberto		if (!sys_manycastserver) {
1080182007Sroberto			sys_restricted++;
1081182007Sroberto			return;			/* not enabled */
1082182007Sroberto		}
1083182007Sroberto
1084290000Sglebius#ifdef AUTOKEY
1085182007Sroberto		/*
1086290000Sglebius		 * Do not respond if not the same group.
1087182007Sroberto		 */
1088290000Sglebius		if (group_test(groupname, NULL)) {
1089290000Sglebius			sys_declined++;
1090290000Sglebius			return;
1091290000Sglebius		}
1092290000Sglebius#endif /* AUTOKEY */
1093182007Sroberto
1094182007Sroberto		/*
1095290000Sglebius		 * Do not respond if we are not synchronized or our
1096290000Sglebius		 * stratum is greater than the manycaster or the
1097290000Sglebius		 * manycaster has already synchronized to us.
1098182007Sroberto		 */
1099290000Sglebius		if (   sys_leap == LEAP_NOTINSYNC
1100290000Sglebius		    || sys_stratum >= hisstratum
1101290000Sglebius		    || (!sys_cohort && sys_stratum == hisstratum + 1)
1102290000Sglebius		    || rbufp->dstadr->addr_refid == pkt->refid) {
1103290000Sglebius			sys_declined++;
1104182007Sroberto			return;			/* no help */
1105290000Sglebius		}
1106182007Sroberto
1107182007Sroberto		/*
1108182007Sroberto		 * Respond only if authentication succeeds. Don't do a
1109182007Sroberto		 * crypto-NAK, as that would not be useful.
1110182007Sroberto		 */
1111182007Sroberto		if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
111282505Sroberto			fast_xmit(rbufp, MODE_SERVER, skeyid,
111382505Sroberto			    restrict_mask);
1114182007Sroberto		return;				/* hooray */
1115182007Sroberto
1116182007Sroberto	/*
1117182007Sroberto	 * This is a server mode packet returned in response to a client
1118290000Sglebius	 * mode packet sent to a multicast group address (for
1119290000Sglebius	 * manycastclient) or to a unicast address (for pool). The
1120290000Sglebius	 * origin timestamp is a good nonce to reliably associate the
1121290000Sglebius	 * reply with what was sent. If there is no match, that's
1122290000Sglebius	 * curious and could be an intruder attempting to clog, so we
1123290000Sglebius	 * just ignore it.
1124182007Sroberto	 *
1125290000Sglebius	 * If the packet is authentic and the manycastclient or pool
1126290000Sglebius	 * association is found, we mobilize a client association and
1127290000Sglebius	 * copy pertinent variables from the manycastclient or pool
1128290000Sglebius	 * association to the new client association. If not, just
1129290000Sglebius	 * ignore the packet.
1130182007Sroberto	 *
1131182007Sroberto	 * There is an implosion hazard at the manycast client, since
1132182007Sroberto	 * the manycast servers send the server packet immediately. If
1133182007Sroberto	 * the guy is already here, don't fire up a duplicate.
1134182007Sroberto	 */
113554359Sroberto	case AM_MANYCAST:
113654359Sroberto
1137290000Sglebius#ifdef AUTOKEY
1138290000Sglebius		/*
1139290000Sglebius		 * Do not respond if not the same group.
1140290000Sglebius		 */
1141290000Sglebius		if (group_test(groupname, NULL)) {
1142290000Sglebius			sys_declined++;
1143290000Sglebius			return;
1144290000Sglebius		}
1145290000Sglebius#endif /* AUTOKEY */
1146182007Sroberto		if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1147132454Sroberto			sys_restricted++;
1148182007Sroberto			return;			/* not enabled */
1149132454Sroberto		}
1150290000Sglebius		if (!AUTH(  (!(peer2->cast_flags & MDF_POOL)
1151290000Sglebius			     && sys_authenticate)
1152290000Sglebius			  || (restrict_mask & (RES_NOPEER |
1153290000Sglebius			      RES_DONTTRUST)), is_authentic)) {
1154290000Sglebius			sys_restricted++;
1155290000Sglebius			return;			/* access denied */
1156290000Sglebius		}
1157132454Sroberto
1158132454Sroberto		/*
1159290000Sglebius		 * Do not respond if unsynchronized or stratum is below
1160290000Sglebius		 * the floor or at or above the ceiling.
1161132454Sroberto		 */
1162290000Sglebius		if (   hisleap == LEAP_NOTINSYNC
1163290000Sglebius		    || hisstratum < sys_floor
1164290000Sglebius		    || hisstratum >= sys_ceiling) {
1165290000Sglebius			sys_declined++;
1166290000Sglebius			return;			/* no help */
1167290000Sglebius		}
1168290000Sglebius		peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1169290000Sglebius			       MODE_CLIENT, hisversion, peer2->minpoll,
1170290000Sglebius			       peer2->maxpoll, FLAG_PREEMPT |
1171290000Sglebius			       (FLAG_IBURST & peer2->flags), MDF_UCAST |
1172290000Sglebius			       MDF_UCLNT, 0, skeyid, sys_ident);
1173290000Sglebius		if (NULL == peer) {
1174290000Sglebius			sys_declined++;
1175290000Sglebius			return;			/* ignore duplicate  */
1176290000Sglebius		}
117756749Sroberto
1178290000Sglebius		/*
1179290000Sglebius		 * After each ephemeral pool association is spun,
1180290000Sglebius		 * accelerate the next poll for the pool solicitor so
1181290000Sglebius		 * the pool will fill promptly.
1182290000Sglebius		 */
1183290000Sglebius		if (peer2->cast_flags & MDF_POOL)
1184290000Sglebius			peer2->nextdate = current_time + 1;
1185290000Sglebius
1186290000Sglebius		/*
1187290000Sglebius		 * Further processing of the solicitation response would
1188290000Sglebius		 * simply detect its origin timestamp as bogus for the
1189290000Sglebius		 * brand-new association (it matches the prototype
1190290000Sglebius		 * association) and tinker with peer->nextdate delaying
1191290000Sglebius		 * first sync.
1192290000Sglebius		 */
1193290000Sglebius		return;		/* solicitation response handled */
1194290000Sglebius
1195182007Sroberto	/*
1196182007Sroberto	 * This is the first packet received from a broadcast server. If
1197182007Sroberto	 * the packet is authentic and we are enabled as broadcast
1198182007Sroberto	 * client, mobilize a broadcast client association. We don't
1199182007Sroberto	 * kiss any frogs here.
1200182007Sroberto	 */
1201182007Sroberto	case AM_NEWBCL:
1202290000Sglebius
1203290000Sglebius#ifdef AUTOKEY
1204290000Sglebius		/*
1205290000Sglebius		 * Do not respond if not the same group.
1206290000Sglebius		 */
1207290000Sglebius		if (group_test(groupname, sys_ident)) {
1208290000Sglebius			sys_declined++;
1209290000Sglebius			return;
1210290000Sglebius		}
1211290000Sglebius#endif /* AUTOKEY */
1212290000Sglebius		if (sys_bclient == 0) {
1213290000Sglebius			sys_restricted++;
1214290000Sglebius			return;			/* not enabled */
1215290000Sglebius		}
1216182007Sroberto		if (!AUTH(sys_authenticate | (restrict_mask &
1217290000Sglebius		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1218290000Sglebius			sys_restricted++;
1219290000Sglebius			return;			/* access denied */
1220290000Sglebius		}
122154359Sroberto
122256749Sroberto		/*
1223182007Sroberto		 * Do not respond if unsynchronized or stratum is below
1224182007Sroberto		 * the floor or at or above the ceiling.
122556749Sroberto		 */
1226290000Sglebius		if (   hisleap == LEAP_NOTINSYNC
1227290000Sglebius		    || hisstratum < sys_floor
1228290000Sglebius		    || hisstratum >= sys_ceiling) {
1229290000Sglebius			sys_declined++;
1230290000Sglebius			return;			/* no help */
1231290000Sglebius		}
1232132454Sroberto
1233290000Sglebius#ifdef AUTOKEY
123456749Sroberto		/*
1235290000Sglebius		 * Do not respond if Autokey and the opcode is not a
1236290000Sglebius		 * CRYPTO_ASSOC response with association ID.
123756749Sroberto		 */
1238290000Sglebius		if (   crypto_flags && skeyid > NTP_MAXKEY
1239290000Sglebius		    && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1240290000Sglebius			sys_declined++;
1241290000Sglebius			return;			/* protocol error */
1242290000Sglebius		}
1243290000Sglebius#endif	/* AUTOKEY */
124482505Sroberto
1245132454Sroberto		/*
1246290000Sglebius		 * Broadcasts received via a multicast address may
1247290000Sglebius		 * arrive after a unicast volley has begun
1248290000Sglebius		 * with the same remote address.  newpeer() will not
1249290000Sglebius		 * find duplicate associations on other local endpoints
1250290000Sglebius		 * if a non-NULL endpoint is supplied.  multicastclient
1251290000Sglebius		 * ephemeral associations are unique across all local
1252290000Sglebius		 * endpoints.
1253132454Sroberto		 */
1254290000Sglebius		if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1255290000Sglebius			match_ep = rbufp->dstadr;
1256290000Sglebius		else
1257290000Sglebius			match_ep = NULL;
125856749Sroberto
1259132454Sroberto		/*
1260290000Sglebius		 * Determine whether to execute the initial volley.
126156749Sroberto		 */
1262298770Sdelphij		if (sys_bdelay > 0.0) {
1263290000Sglebius#ifdef AUTOKEY
1264182007Sroberto			/*
1265182007Sroberto			 * If a two-way exchange is not possible,
1266182007Sroberto			 * neither is Autokey.
1267182007Sroberto			 */
1268290000Sglebius			if (crypto_flags && skeyid > NTP_MAXKEY) {
1269290000Sglebius				sys_restricted++;
1270182007Sroberto				return;		/* no autokey */
1271182007Sroberto			}
1272290000Sglebius#endif	/* AUTOKEY */
1273290000Sglebius
1274290000Sglebius			/*
1275290000Sglebius			 * Do not execute the volley. Start out in
1276290000Sglebius			 * broadcast client mode.
1277290000Sglebius			 */
1278290000Sglebius			peer = newpeer(&rbufp->recv_srcadr, NULL,
1279290000Sglebius			    match_ep, MODE_BCLIENT, hisversion,
1280290000Sglebius			    pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1281290000Sglebius			    MDF_BCLNT, 0, skeyid, sys_ident);
1282290000Sglebius			if (NULL == peer) {
1283290000Sglebius				sys_restricted++;
1284290000Sglebius				return;		/* ignore duplicate */
1285290000Sglebius
1286290000Sglebius			} else {
1287290000Sglebius				peer->delay = sys_bdelay;
1288294904Sdelphij				peer->bxmt = p_xmt;
1289290000Sglebius			}
1290290000Sglebius			break;
1291132454Sroberto		}
129256749Sroberto
1293290000Sglebius		/*
1294290000Sglebius		 * Execute the initial volley in order to calibrate the
1295290000Sglebius		 * propagation delay and run the Autokey protocol.
1296290000Sglebius		 *
1297290000Sglebius		 * Note that the minpoll is taken from the broadcast
1298290000Sglebius		 * packet, normally 6 (64 s) and that the poll interval
1299290000Sglebius		 * is fixed at this value.
1300290000Sglebius		 */
1301290000Sglebius		peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1302290000Sglebius		    MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1303290000Sglebius		    FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1304290000Sglebius		    0, skeyid, sys_ident);
1305290000Sglebius		if (NULL == peer) {
1306290000Sglebius			sys_restricted++;
1307290000Sglebius			return;			/* ignore duplicate */
1308290000Sglebius		}
1309294904Sdelphij		peer->bxmt = p_xmt;
1310290000Sglebius#ifdef AUTOKEY
1311290000Sglebius		if (skeyid > NTP_MAXKEY)
1312290000Sglebius			crypto_recv(peer, rbufp);
1313290000Sglebius#endif	/* AUTOKEY */
1314290000Sglebius
1315290000Sglebius		return;				/* hooray */
1316290000Sglebius
1317182007Sroberto	/*
1318182007Sroberto	 * This is the first packet received from a symmetric active
1319182007Sroberto	 * peer. If the packet is authentic and the first he sent,
1320182007Sroberto	 * mobilize a passive association. If not, kiss the frog.
1321182007Sroberto	 */
1322182007Sroberto	case AM_NEWPASS:
132356749Sroberto
1324290000Sglebius#ifdef AUTOKEY
132556749Sroberto		/*
1326290000Sglebius		 * Do not respond if not the same group.
132756749Sroberto		 */
1328290000Sglebius		if (group_test(groupname, sys_ident)) {
1329290000Sglebius			sys_declined++;
1330290000Sglebius			return;
1331290000Sglebius		}
1332290000Sglebius#endif /* AUTOKEY */
1333290000Sglebius		if (!AUTH(sys_authenticate | (restrict_mask &
1334290000Sglebius		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1335290000Sglebius
1336290000Sglebius			/*
1337290000Sglebius			 * If authenticated but cannot mobilize an
1338290000Sglebius			 * association, send a symmetric passive
1339290000Sglebius			 * response without mobilizing an association.
1340290000Sglebius			 * This is for drat broken Windows clients. See
1341290000Sglebius			 * Microsoft KB 875424 for preferred workaround.
1342290000Sglebius			 */
1343290000Sglebius			if (AUTH(restrict_mask & RES_DONTTRUST,
1344290000Sglebius			    is_authentic)) {
1345290000Sglebius				fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1346290000Sglebius				    restrict_mask);
1347290000Sglebius				return;			/* hooray */
1348290000Sglebius			}
1349290000Sglebius			if (is_authentic == AUTH_ERROR) {
1350182007Sroberto				fast_xmit(rbufp, MODE_ACTIVE, 0,
1351182007Sroberto				    restrict_mask);
1352290000Sglebius				sys_restricted++;
1353290000Sglebius				return;
1354290000Sglebius			}
1355290000Sglebius			/* [Bug 2941]
1356290000Sglebius			 * If we got here, the packet isn't part of an
1357290000Sglebius			 * existing association, it isn't correctly
1358290000Sglebius			 * authenticated, and it didn't meet either of
1359290000Sglebius			 * the previous two special cases so we should
1360290000Sglebius			 * just drop it on the floor.  For example,
1361290000Sglebius			 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1362290000Sglebius			 * will make it this far.  This is just
1363290000Sglebius			 * debug-printed and not logged to avoid log
1364290000Sglebius			 * flooding.
1365290000Sglebius			 */
1366293894Sglebius			DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1367293894Sglebius				    " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1368290000Sglebius				    current_time, stoa(&rbufp->recv_srcadr),
1369293894Sglebius				    hismode, hm_str, am_str, skeyid,
1370293894Sglebius				    (authlen + has_mac), is_authentic));
1371290000Sglebius			sys_declined++;
1372290000Sglebius			return;
1373182007Sroberto		}
1374290000Sglebius
1375290000Sglebius		/*
1376290000Sglebius		 * Do not respond if synchronized and if stratum is
1377290000Sglebius		 * below the floor or at or above the ceiling. Note,
1378290000Sglebius		 * this allows an unsynchronized peer to synchronize to
1379290000Sglebius		 * us. It would be very strange if he did and then was
1380290000Sglebius		 * nipped, but that could only happen if we were
1381290000Sglebius		 * operating at the top end of the range.  It also means
1382290000Sglebius		 * we will spin an ephemeral association in response to
1383290000Sglebius		 * MODE_ACTIVE KoDs, which will time out eventually.
1384290000Sglebius		 */
1385290000Sglebius		if (   hisleap != LEAP_NOTINSYNC
1386290000Sglebius		    && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1387290000Sglebius			sys_declined++;
1388290000Sglebius			return;			/* no help */
1389182007Sroberto		}
139054359Sroberto
1391182007Sroberto		/*
1392290000Sglebius		 * The message is correctly authenticated and allowed.
1393290000Sglebius		 * Mobilize a symmetric passive association.
1394182007Sroberto		 */
1395290000Sglebius		if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1396290000Sglebius		    rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1397290000Sglebius		    NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1398290000Sglebius		    sys_ident)) == NULL) {
1399290000Sglebius			sys_declined++;
1400290000Sglebius			return;			/* ignore duplicate */
1401290000Sglebius		}
1402182007Sroberto		break;
1403182007Sroberto
1404290000Sglebius
140554359Sroberto	/*
1406182007Sroberto	 * Process regular packet. Nothing special.
140754359Sroberto	 */
1408182007Sroberto	case AM_PROCPKT:
1409290000Sglebius
1410290000Sglebius#ifdef AUTOKEY
1411290000Sglebius		/*
1412290000Sglebius		 * Do not respond if not the same group.
1413290000Sglebius		 */
1414290000Sglebius		if (group_test(groupname, peer->ident)) {
1415290000Sglebius			sys_declined++;
1416290000Sglebius			return;
1417290000Sglebius		}
1418290000Sglebius#endif /* AUTOKEY */
1419294904Sdelphij
1420294904Sdelphij		if (MODE_BROADCAST == hismode) {
1421298770Sdelphij			int	bail = 0;
1422298770Sdelphij			l_fp	tdiff;
1423298770Sdelphij			u_long	deadband;
1424294904Sdelphij
1425294904Sdelphij			DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1426294904Sdelphij				    (current_time - peer->timelastrec),
1427294904Sdelphij				    peer->ppoll, (1 << peer->ppoll)
1428294904Sdelphij				    ));
1429294904Sdelphij			/* Things we can check:
1430294904Sdelphij			 *
1431294904Sdelphij			 * Did the poll interval change?
1432294904Sdelphij			 * Is the poll interval in the packet in-range?
1433294904Sdelphij			 * Did this packet arrive too soon?
1434294904Sdelphij			 * Is the timestamp in this packet monotonic
1435294904Sdelphij			 *  with respect to the previous packet?
1436294904Sdelphij			 */
1437294904Sdelphij
1438294904Sdelphij			/* This is noteworthy, not error-worthy */
1439294904Sdelphij			if (pkt->ppoll != peer->ppoll) {
1440294904Sdelphij				msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud",
1441294904Sdelphij					stoa(&rbufp->recv_srcadr),
1442294904Sdelphij					peer->ppoll, pkt->ppoll);
1443294904Sdelphij			}
1444294904Sdelphij
1445294904Sdelphij			/* This is error-worthy */
1446298770Sdelphij			if (pkt->ppoll < peer->minpoll ||
1447298770Sdelphij			    pkt->ppoll > peer->maxpoll  ) {
1448294904Sdelphij				msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!",
1449294904Sdelphij					pkt->ppoll, stoa(&rbufp->recv_srcadr),
1450294904Sdelphij					peer->minpoll, peer->maxpoll);
1451294904Sdelphij				++bail;
1452294904Sdelphij			}
1453294904Sdelphij
1454310419Sdelphij			/* too early? worth an error, too!
1455310419Sdelphij			 *
1456310419Sdelphij			 * [Bug 3113] Ensure that at least one poll
1457310419Sdelphij			 * interval has elapsed since the last **clean**
1458310419Sdelphij			 * packet was received.  We limit the check to
1459310419Sdelphij			 * **clean** packets to prevent replayed packets
1460310419Sdelphij			 * and incorrectly authenticated packets, which
1461310419Sdelphij			 * we'll discard, from being used to create a
1462310419Sdelphij			 * denial of service condition.
1463310419Sdelphij			 */
1464298770Sdelphij			deadband = (1u << pkt->ppoll);
1465298770Sdelphij			if (FLAG_BC_VOL & peer->flags)
1466298770Sdelphij				deadband -= 3;	/* allow greater fuzz after volley */
1467310419Sdelphij			if ((current_time - peer->timereceived) < deadband) {
1468298770Sdelphij				msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1469294904Sdelphij					stoa(&rbufp->recv_srcadr),
1470310419Sdelphij					(current_time - peer->timereceived),
1471298770Sdelphij					deadband);
1472294904Sdelphij				++bail;
1473294904Sdelphij			}
1474294904Sdelphij
1475310419Sdelphij			/* Alert if time from the server is non-monotonic.
1476310419Sdelphij			 *
1477310419Sdelphij			 * [Bug 3114] is about Broadcast mode replay DoS.
1478310419Sdelphij			 *
1479310419Sdelphij			 * Broadcast mode *assumes* a trusted network.
1480310419Sdelphij			 * Even so, it's nice to be robust in the face
1481310419Sdelphij			 * of attacks.
1482310419Sdelphij			 *
1483310419Sdelphij			 * If we get an authenticated broadcast packet
1484310419Sdelphij			 * with an "earlier" timestamp, it means one of
1485310419Sdelphij			 * two things:
1486310419Sdelphij			 *
1487310419Sdelphij			 * - the broadcast server had a backward step.
1488310419Sdelphij			 *
1489310419Sdelphij			 * - somebody is trying a replay attack.
1490310419Sdelphij			 *
1491310419Sdelphij			 * deadband: By default, we assume the broadcast
1492310419Sdelphij			 * network is trustable, so we take our accepted
1493310419Sdelphij			 * broadcast packets as we receive them.  But
1494310419Sdelphij			 * some folks might want to take additional poll
1495310419Sdelphij			 * delays before believing a backward step.
1496310419Sdelphij			 */
1497310419Sdelphij			if (sys_bcpollbstep) {
1498310419Sdelphij				/* pkt->ppoll or peer->ppoll ? */
1499310419Sdelphij				deadband = (1u << pkt->ppoll)
1500310419Sdelphij					   * sys_bcpollbstep + 2;
1501310419Sdelphij			} else {
1502310419Sdelphij				deadband = 0;
1503310419Sdelphij			}
1504310419Sdelphij
1505310419Sdelphij			if (L_ISZERO(&peer->bxmt)) {
1506310419Sdelphij				tdiff.l_ui = tdiff.l_uf = 0;
1507310419Sdelphij			} else {
1508310419Sdelphij				tdiff = p_xmt;
1509310419Sdelphij				L_SUB(&tdiff, &peer->bxmt);
1510310419Sdelphij			}
1511310419Sdelphij			if (tdiff.l_i < 0 &&
1512310419Sdelphij			    (current_time - peer->timereceived) < deadband)
1513310419Sdelphij			{
1514294904Sdelphij				msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1515294904Sdelphij					stoa(&rbufp->recv_srcadr),
1516294904Sdelphij					peer->bxmt.l_ui, peer->bxmt.l_uf,
1517294904Sdelphij					p_xmt.l_ui, p_xmt.l_uf
1518294904Sdelphij					);
1519294904Sdelphij				++bail;
1520294904Sdelphij			}
1521294904Sdelphij
1522294904Sdelphij			if (bail) {
1523294904Sdelphij				peer->timelastrec = current_time;
1524294904Sdelphij				sys_declined++;
1525294904Sdelphij				return;
1526294904Sdelphij			}
1527294904Sdelphij		}
1528294904Sdelphij
1529182007Sroberto		break;
153054359Sroberto
153154359Sroberto	/*
1532182007Sroberto	 * A passive packet matches a passive association. This is
1533182007Sroberto	 * usually the result of reconfiguring a client on the fly. As
1534290000Sglebius	 * this association might be legitimate and this packet an
1535182007Sroberto	 * attempt to deny service, just ignore it.
153654359Sroberto	 */
1537182007Sroberto	case AM_ERR:
1538290000Sglebius		sys_declined++;
1539182007Sroberto		return;
1540132454Sroberto
1541132454Sroberto	/*
1542182007Sroberto	 * For everything else there is the bit bucket.
1543132454Sroberto	 */
1544182007Sroberto	default:
1545290000Sglebius		sys_declined++;
1546182007Sroberto		return;
1547182007Sroberto	}
1548290000Sglebius
1549290000Sglebius#ifdef AUTOKEY
1550290000Sglebius	/*
1551290000Sglebius	 * If the association is configured for Autokey, the packet must
1552290000Sglebius	 * have a public key ID; if not, the packet must have a
1553290000Sglebius	 * symmetric key ID.
1554290000Sglebius	 */
1555290000Sglebius	if (   is_authentic != AUTH_CRYPTO
1556290000Sglebius	    && (   ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1557290000Sglebius	        || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1558290000Sglebius		sys_badauth++;
1559290000Sglebius		return;
1560290000Sglebius	}
1561290000Sglebius#endif	/* AUTOKEY */
1562298770Sdelphij
1563290000Sglebius	peer->received++;
1564182007Sroberto	peer->flash &= ~PKT_TEST_MASK;
1565290000Sglebius	if (peer->flags & FLAG_XBOGUS) {
1566290000Sglebius		peer->flags &= ~FLAG_XBOGUS;
1567290000Sglebius		peer->flash |= TEST3;
1568290000Sglebius	}
1569132454Sroberto
1570132454Sroberto	/*
1571182007Sroberto	 * Next comes a rigorous schedule of timestamp checking. If the
1572290000Sglebius	 * transmit timestamp is zero, the server has not initialized in
1573290000Sglebius	 * interleaved modes or is horribly broken.
1574298770Sdelphij	 *
1575298770Sdelphij	 * A KoD packet we pay attention to cannot have a 0 transmit
1576298770Sdelphij	 * timestamp.
1577132454Sroberto	 */
1578182007Sroberto	if (L_ISZERO(&p_xmt)) {
1579290000Sglebius		peer->flash |= TEST3;			/* unsynch */
1580301301Sdelphij		if (STRATUM_UNSPEC == hisstratum) {	/* KoD packet */
1581298770Sdelphij			peer->bogusorg++;		/* for TEST2 or TEST3 */
1582298770Sdelphij			msyslog(LOG_INFO,
1583298770Sdelphij				"receive: Unexpected zero transmit timestamp in KoD from %s",
1584298770Sdelphij				ntoa(&peer->srcadr));
1585298770Sdelphij			return;
1586298770Sdelphij		}
1587132454Sroberto
1588132454Sroberto	/*
1589298770Sdelphij	 * If the transmit timestamp duplicates our previous one, the
1590182007Sroberto	 * packet is a replay. This prevents the bad guys from replaying
1591182007Sroberto	 * the most recent packet, authenticated or not.
1592132454Sroberto	 */
1593290000Sglebius	} else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1594290000Sglebius		peer->flash |= TEST1;			/* duplicate */
1595182007Sroberto		peer->oldpkt++;
1596290000Sglebius		return;
1597132454Sroberto
1598132454Sroberto	/*
1599301301Sdelphij	 * If this is a broadcast mode packet, make sure hisstratum
1600301301Sdelphij	 * is appropriate.  Don't do anything else here - we wait to
1601301301Sdelphij	 * see if this is an interleave broadcast packet until after
1602301301Sdelphij	 * we've validated the MAC that SHOULD be provided.
1603301301Sdelphij	 *
1604301301Sdelphij	 * hisstratum should never be 0.
1605301301Sdelphij	 * If hisstratum is 15, then we'll advertise as UNSPEC but
1606301301Sdelphij	 * at least we'll be able to sync with the broadcast server.
1607132454Sroberto	 */
1608290000Sglebius	} else if (hismode == MODE_BROADCAST) {
1609301301Sdelphij		if (   0 == hisstratum
1610301301Sdelphij		    || STRATUM_UNSPEC <= hisstratum) {
1611301301Sdelphij			/* Is this a ++sys_declined or ??? */
1612301301Sdelphij			msyslog(LOG_INFO,
1613301301Sdelphij				"receive: Unexpected stratum (%d) in broadcast from %s",
1614301301Sdelphij				hisstratum, ntoa(&peer->srcadr));
1615290000Sglebius			return;
1616290000Sglebius		}
1617132454Sroberto
1618132454Sroberto	/*
1619298770Sdelphij	 * Basic KoD validation checking:
1620298770Sdelphij	 *
1621298770Sdelphij	 * KoD packets are a mixed-blessing.  Forged KoD packets
1622298770Sdelphij	 * are DoS attacks.  There are rare situations where we might
1623298770Sdelphij	 * get a valid KoD response, though.  Since KoD packets are
1624298770Sdelphij	 * a special case that complicate the checks we do next, we
1625298770Sdelphij	 * handle the basic KoD checks here.
1626298770Sdelphij	 *
1627298770Sdelphij	 * Note that we expect the incoming KoD packet to have its
1628298770Sdelphij	 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1629298770Sdelphij	 * that we have previously sent out.  Watch interleave mode.
1630298770Sdelphij	 */
1631301301Sdelphij	} else if (STRATUM_UNSPEC == hisstratum) {
1632298770Sdelphij		DEBUG_INSIST(!L_ISZERO(&p_xmt));
1633298770Sdelphij		if (   L_ISZERO(&p_org)		/* We checked p_xmt above */
1634298770Sdelphij		    || L_ISZERO(&p_rec)) {
1635298770Sdelphij			peer->bogusorg++;
1636298770Sdelphij			msyslog(LOG_INFO,
1637298770Sdelphij				"receive: KoD packet from %s has a zero org or rec timestamp.  Ignoring.",
1638298770Sdelphij				ntoa(&peer->srcadr));
1639298770Sdelphij			return;
1640298770Sdelphij		}
1641298770Sdelphij
1642298770Sdelphij		if (   !L_ISEQU(&p_xmt, &p_org)
1643298770Sdelphij		    || !L_ISEQU(&p_xmt, &p_rec)) {
1644298770Sdelphij			peer->bogusorg++;
1645298770Sdelphij			msyslog(LOG_INFO,
1646298770Sdelphij				"receive: KoD packet from %s has inconsistent xmt/org/rec timestamps.  Ignoring.",
1647298770Sdelphij				ntoa(&peer->srcadr));
1648298770Sdelphij			return;
1649298770Sdelphij		}
1650298770Sdelphij
1651298770Sdelphij		/* Be conservative */
1652298770Sdelphij		if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1653298770Sdelphij			peer->bogusorg++;
1654298770Sdelphij			msyslog(LOG_INFO,
1655298770Sdelphij				"receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1656298770Sdelphij				p_org.l_ui, p_org.l_uf,
1657298770Sdelphij				ntoa(&peer->srcadr),
1658298770Sdelphij				peer->aorg.l_ui, peer->aorg.l_uf);
1659298770Sdelphij			return;
1660298770Sdelphij		} else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1661298770Sdelphij			peer->bogusorg++;
1662298770Sdelphij			msyslog(LOG_INFO,
1663298770Sdelphij				"receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1664298770Sdelphij				p_org.l_ui, p_org.l_uf,
1665298770Sdelphij				ntoa(&peer->srcadr),
1666298770Sdelphij				peer->borg.l_ui, peer->borg.l_uf);
1667298770Sdelphij			return;
1668298770Sdelphij		}
1669310419Sdelphij
1670298770Sdelphij	/*
1671293894Sglebius	 * Basic mode checks:
1672290000Sglebius	 *
1673294904Sdelphij	 * If there is no origin timestamp, it's either an initial packet
1674294904Sdelphij	 * or we've already received a response to our query.  Of course,
1675294904Sdelphij	 * should 'aorg' be all-zero because this really was the original
1676298770Sdelphij	 * transmit timestamp, we'll ignore this reply.  There is a window
1677298770Sdelphij	 * of one nanosecond once every 136 years' time where this is
1678298770Sdelphij	 * possible.  We currently ignore this situation.
1679293894Sglebius	 *
1680293894Sglebius	 * Otherwise, check for bogus packet in basic mode.
1681293894Sglebius	 * If it is bogus, switch to interleaved mode and resynchronize,
1682293894Sglebius	 * but only after confirming the packet is not bogus in
1683293894Sglebius	 * symmetric interleaved mode.
1684293894Sglebius	 *
1685290000Sglebius	 * This could also mean somebody is forging packets claiming to
1686290000Sglebius	 * be from us, attempting to cause our server to KoD us.
1687132454Sroberto	 */
1688290000Sglebius	} else if (peer->flip == 0) {
1689298770Sdelphij		INSIST(0 != hisstratum);
1690301301Sdelphij		INSIST(STRATUM_UNSPEC != hisstratum);
1691310419Sdelphij
1692298770Sdelphij		if (0) {
1693298770Sdelphij		} else if (L_ISZERO(&p_org)) {
1694310419Sdelphij			char *action;
1695310419Sdelphij
1696310419Sdelphij			L_CLR(&peer->aorg);
1697310419Sdelphij			/**/
1698310419Sdelphij			switch (hismode) {
1699310419Sdelphij			/* We allow 0org for: */
1700310419Sdelphij			    case UCHAR_MAX:
1701310419Sdelphij				action = "Allow";
1702310419Sdelphij				break;
1703310419Sdelphij			/* We disallow 0org for: */
1704310419Sdelphij			    case MODE_UNSPEC:
1705310419Sdelphij			    case MODE_ACTIVE:
1706310419Sdelphij			    case MODE_PASSIVE:
1707310419Sdelphij			    case MODE_CLIENT:
1708310419Sdelphij			    case MODE_SERVER:
1709310419Sdelphij			    case MODE_BROADCAST:
1710310419Sdelphij				action = "Drop";
1711310419Sdelphij				peer->bogusorg++;
1712310419Sdelphij				peer->flash |= TEST2;	/* bogus */
1713310419Sdelphij				break;
1714310419Sdelphij			    default:
1715310419Sdelphij				INSIST(!"receive(): impossible hismode");
1716310419Sdelphij				break;
1717310419Sdelphij			}
1718310419Sdelphij			/**/
1719298770Sdelphij			msyslog(LOG_INFO,
1720310419Sdelphij				"receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
1721310419Sdelphij				action, hm_str, ntoa(&peer->srcadr),
1722298770Sdelphij				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1723298770Sdelphij		} else if (!L_ISEQU(&p_org, &peer->aorg)) {
1724298770Sdelphij			/* are there cases here where we should bail? */
1725298770Sdelphij			/* Should we set TEST2 if we decide to try xleave? */
1726290000Sglebius			peer->bogusorg++;
1727290000Sglebius			peer->flash |= TEST2;	/* bogus */
1728290000Sglebius			msyslog(LOG_INFO,
1729298770Sdelphij				"receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1730293894Sglebius				ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1731298770Sdelphij				peer->aorg.l_ui, peer->aorg.l_uf,
1732298770Sdelphij				hm_str, ntoa(&peer->srcadr),
1733293894Sglebius				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1734290000Sglebius			if (  !L_ISZERO(&peer->dst)
1735290000Sglebius			    && L_ISEQU(&p_org, &peer->dst)) {
1736293894Sglebius				/* Might be the start of an interleave */
1737298770Sdelphij				if (dynamic_interleave) {
1738298770Sdelphij					peer->flip = 1;
1739298770Sdelphij					report_event(PEVNT_XLEAVE, peer, NULL);
1740298770Sdelphij				} else {
1741298770Sdelphij					msyslog(LOG_INFO,
1742298770Sdelphij						"receive: Dynamic interleave from %s@%s denied",
1743298770Sdelphij						hm_str, ntoa(&peer->srcadr));
1744298770Sdelphij				}
1745182007Sroberto			}
1746290000Sglebius		} else {
1747290000Sglebius			L_CLR(&peer->aorg);
1748182007Sroberto		}
1749290000Sglebius
1750290000Sglebius	/*
1751290000Sglebius	 * Check for valid nonzero timestamp fields.
1752290000Sglebius	 */
1753301301Sdelphij	} else if (   L_ISZERO(&p_org)
1754301301Sdelphij		   || L_ISZERO(&p_rec)
1755301301Sdelphij		   || L_ISZERO(&peer->dst)) {
1756290000Sglebius		peer->flash |= TEST3;		/* unsynch */
1757290000Sglebius
1758290000Sglebius	/*
1759290000Sglebius	 * Check for bogus packet in interleaved symmetric mode. This
1760290000Sglebius	 * can happen if a packet is lost, duplicated or crossed. If
1761290000Sglebius	 * found, flip and resynchronize.
1762290000Sglebius	 */
1763290000Sglebius	} else if (   !L_ISZERO(&peer->dst)
1764290000Sglebius		   && !L_ISEQU(&p_org, &peer->dst)) {
1765290000Sglebius		peer->bogusorg++;
1766290000Sglebius		peer->flags |= FLAG_XBOGUS;
1767290000Sglebius		peer->flash |= TEST2;		/* bogus */
1768290000Sglebius		return; /* Bogus packet, we are done */
1769182007Sroberto	}
1770132454Sroberto
1771301301Sdelphij	/**/
1772301301Sdelphij
1773132454Sroberto	/*
1774290000Sglebius	 * If this is a crypto_NAK, the server cannot authenticate a
1775290000Sglebius	 * client packet. The server might have just changed keys. Clear
1776290000Sglebius	 * the association and restart the protocol.
1777132454Sroberto	 */
1778298770Sdelphij	if (crypto_nak_test == VALIDNAK) {
1779290000Sglebius		report_event(PEVNT_AUTH, peer, "crypto_NAK");
1780290000Sglebius		peer->flash |= TEST5;		/* bad auth */
1781290000Sglebius		peer->badauth++;
1782290000Sglebius		if (peer->flags & FLAG_PREEMPT) {
1783294904Sdelphij			if (unpeer_crypto_nak_early) {
1784294904Sdelphij				unpeer(peer);
1785294904Sdelphij			}
1786290000Sglebius			return;
1787290000Sglebius		}
1788290000Sglebius#ifdef AUTOKEY
1789301301Sdelphij		if (peer->crypto) {
1790290000Sglebius			peer_clear(peer, "AUTH");
1791301301Sdelphij		}
1792290000Sglebius#endif	/* AUTOKEY */
1793290000Sglebius		return;
1794182007Sroberto
1795290000Sglebius	/*
1796290000Sglebius	 * If the digest fails or it's missing for authenticated
1797290000Sglebius	 * associations, the client cannot authenticate a server
1798290000Sglebius	 * reply to a client packet previously sent. The loopback check
1799290000Sglebius	 * is designed to avoid a bait-and-switch attack, which was
1800290000Sglebius	 * possible in past versions. If symmetric modes, return a
1801290000Sglebius	 * crypto-NAK. The peer should restart the protocol.
1802182007Sroberto	 */
1803281232Sdelphij	} else if (!AUTH(peer->keyid || has_mac ||
1804290000Sglebius			 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1805301301Sdelphij
1806301301Sdelphij		if (peer->flash & PKT_TEST_MASK) {
1807301301Sdelphij			msyslog(LOG_INFO,
1808301301Sdelphij				"receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
1809301301Sdelphij				ntoa(&peer->srcadr));
1810301301Sdelphij			return;
1811301301Sdelphij		}
1812301301Sdelphij
1813290000Sglebius		report_event(PEVNT_AUTH, peer, "digest");
1814290000Sglebius		peer->flash |= TEST5;		/* bad auth */
1815290000Sglebius		peer->badauth++;
1816290000Sglebius		if (   has_mac
1817301301Sdelphij		    && (   hismode == MODE_ACTIVE
1818301301Sdelphij			|| hismode == MODE_PASSIVE))
1819132454Sroberto			fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1820290000Sglebius		if (peer->flags & FLAG_PREEMPT) {
1821294904Sdelphij			if (unpeer_digest_early) {
1822294904Sdelphij				unpeer(peer);
1823294904Sdelphij			}
1824290000Sglebius		}
1825290000Sglebius#ifdef AUTOKEY
1826301301Sdelphij		else if (peer_clear_digest_early && peer->crypto) {
1827290000Sglebius			peer_clear(peer, "AUTH");
1828301301Sdelphij		}
1829290000Sglebius#endif	/* AUTOKEY */
1830290000Sglebius		return;
183154359Sroberto	}
183254359Sroberto
1833182007Sroberto	/*
1834301301Sdelphij	 * For broadcast packets:
1835301301Sdelphij	 *
1836301301Sdelphij	 * HMS: This next line never made much sense to me, even
1837301301Sdelphij	 * when it was up higher:
1838301301Sdelphij	 *   If an initial volley, bail out now and let the
1839301301Sdelphij	 *   client do its stuff.
1840301301Sdelphij	 *
1841301301Sdelphij	 * If the packet has not failed authentication, then
1842301301Sdelphij	 * - if the origin timestamp is nonzero this is an
1843301301Sdelphij	 *   interleaved broadcast, so restart the protocol.
1844301301Sdelphij	 * - else, this is not an interleaved broadcast packet.
1845290000Sglebius	 */
1846301301Sdelphij	if (hismode == MODE_BROADCAST) {
1847301301Sdelphij		if (   is_authentic == AUTH_OK
1848301301Sdelphij		    || is_authentic == AUTH_NONE) {
1849301301Sdelphij			if (!L_ISZERO(&p_org)) {
1850301301Sdelphij				if (!(peer->flags & FLAG_XB)) {
1851301301Sdelphij					msyslog(LOG_INFO,
1852301301Sdelphij						"receive: Broadcast server at %s is in interleave mode",
1853301301Sdelphij						ntoa(&peer->srcadr));
1854301301Sdelphij					peer->flags |= FLAG_XB;
1855301301Sdelphij					peer->aorg = p_xmt;
1856301301Sdelphij					peer->borg = rbufp->recv_time;
1857301301Sdelphij					report_event(PEVNT_XLEAVE, peer, NULL);
1858301301Sdelphij					return;
1859301301Sdelphij				}
1860301301Sdelphij			} else if (peer->flags & FLAG_XB) {
1861301301Sdelphij				msyslog(LOG_INFO,
1862301301Sdelphij					"receive: Broadcast server at %s is no longer in interleave mode",
1863301301Sdelphij					ntoa(&peer->srcadr));
1864301301Sdelphij				peer->flags &= ~FLAG_XB;
1865301301Sdelphij			}
1866301301Sdelphij		} else {
1867301301Sdelphij			msyslog(LOG_INFO,
1868301301Sdelphij				"receive: Bad broadcast auth (%d) from %s",
1869301301Sdelphij				is_authentic, ntoa(&peer->srcadr));
1870301301Sdelphij		}
1871310419Sdelphij
1872310419Sdelphij		/*
1873310419Sdelphij		 * Now that we know the packet is correctly authenticated,
1874310419Sdelphij		 * update peer->bxmt.
1875310419Sdelphij		 */
1876310419Sdelphij		peer->bxmt = p_xmt;
1877301301Sdelphij	}
1878301301Sdelphij
1879301301Sdelphij
1880301301Sdelphij	/*
1881301301Sdelphij	** Update the state variables.
1882301301Sdelphij	*/
1883290000Sglebius	if (peer->flip == 0) {
1884290000Sglebius		if (hismode != MODE_BROADCAST)
1885290000Sglebius			peer->rec = p_xmt;
1886290000Sglebius		peer->dst = rbufp->recv_time;
1887290000Sglebius	}
1888290000Sglebius	peer->xmt = p_xmt;
1889290000Sglebius
1890290000Sglebius	/*
1891290000Sglebius	 * Set the peer ppoll to the maximum of the packet ppoll and the
1892290000Sglebius	 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1893290000Sglebius	 * this maximum and advance the headway to give the sender some
1894290000Sglebius	 * headroom. Very intricate.
1895290000Sglebius	 */
1896290000Sglebius
1897290000Sglebius	/*
1898290000Sglebius	 * Check for any kiss codes. Note this is only used when a server
1899290000Sglebius	 * responds to a packet request
1900290000Sglebius	 */
1901290000Sglebius
1902290000Sglebius	kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1903290000Sglebius
1904290000Sglebius	/*
1905290000Sglebius	 * Check to see if this is a RATE Kiss Code
1906290000Sglebius	 * Currently this kiss code will accept whatever poll
1907290000Sglebius	 * rate that the server sends
1908290000Sglebius	 */
1909290000Sglebius	peer->ppoll = max(peer->minpoll, pkt->ppoll);
1910290000Sglebius	if (kissCode == RATEKISS) {
1911290000Sglebius		peer->selbroken++;	/* Increment the KoD count */
1912290000Sglebius		report_event(PEVNT_RATE, peer, NULL);
1913290000Sglebius		if (pkt->ppoll > peer->minpoll)
1914290000Sglebius			peer->minpoll = peer->ppoll;
1915290000Sglebius		peer->burst = peer->retry = 0;
1916290000Sglebius		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1917290000Sglebius		poll_update(peer, pkt->ppoll);
1918290000Sglebius		return;				/* kiss-o'-death */
1919290000Sglebius	}
1920290000Sglebius	if (kissCode != NOKISS) {
1921290000Sglebius		peer->selbroken++;	/* Increment the KoD count */
1922290000Sglebius		return;		/* Drop any other kiss code packets */
1923290000Sglebius	}
1924290000Sglebius
1925301301Sdelphij
1926294904Sdelphij	/*
1927301301Sdelphij	 * XXX
1928301301Sdelphij	 */
1929301301Sdelphij
1930301301Sdelphij
1931301301Sdelphij	/*
1932294904Sdelphij	 * If:
1933294904Sdelphij	 *	- this is a *cast (uni-, broad-, or m-) server packet
1934298770Sdelphij	 *	- and it's symmetric-key authenticated
1935294904Sdelphij	 * then see if the sender's IP is trusted for this keyid.
1936294904Sdelphij	 * If it is, great - nothing special to do here.
1937294904Sdelphij	 * Otherwise, we should report and bail.
1938298770Sdelphij	 *
1939298770Sdelphij	 * Autokey-authenticated packets are accepted.
1940294904Sdelphij	 */
1941290000Sglebius
1942294904Sdelphij	switch (hismode) {
1943294904Sdelphij	    case MODE_SERVER:		/* server mode */
1944294904Sdelphij	    case MODE_BROADCAST:	/* broadcast mode */
1945294904Sdelphij	    case MODE_ACTIVE:		/* symmetric active mode */
1946298770Sdelphij	    case MODE_PASSIVE:		/* symmetric passive mode */
1947294904Sdelphij		if (   is_authentic == AUTH_OK
1948298770Sdelphij		    && skeyid
1949298770Sdelphij		    && skeyid <= NTP_MAXKEY
1950294904Sdelphij		    && !authistrustedip(skeyid, &peer->srcadr)) {
1951294904Sdelphij			report_event(PEVNT_AUTH, peer, "authIP");
1952294904Sdelphij			peer->badauth++;
1953294904Sdelphij			return;
1954294904Sdelphij		}
1955310419Sdelphij		break;
1956294904Sdelphij
1957294904Sdelphij	    case MODE_CLIENT:		/* client mode */
1958294904Sdelphij#if 0		/* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
1959294904Sdelphij	    case MODE_CONTROL:		/* control mode */
1960294904Sdelphij#endif
1961294904Sdelphij	    case MODE_PRIVATE:		/* private mode */
1962294904Sdelphij	    case MODE_BCLIENT:		/* broadcast client mode */
1963310419Sdelphij		break;
1964298770Sdelphij
1965298770Sdelphij	    case MODE_UNSPEC:		/* unspecified (old version) */
1966294904Sdelphij	    default:
1967298770Sdelphij		msyslog(LOG_INFO,
1968298770Sdelphij			"receive: Unexpected mode (%d) in packet from %s",
1969298770Sdelphij			hismode, ntoa(&peer->srcadr));
1970310419Sdelphij		break;
1971294904Sdelphij	}
1972294904Sdelphij
1973294904Sdelphij
1974290000Sglebius	/*
1975182007Sroberto	 * That was hard and I am sweaty, but the packet is squeaky
1976182007Sroberto	 * clean. Get on with real work.
1977182007Sroberto	 */
1978182007Sroberto	peer->timereceived = current_time;
1979294904Sdelphij	peer->timelastrec = current_time;
1980182007Sroberto	if (is_authentic == AUTH_OK)
1981182007Sroberto		peer->flags |= FLAG_AUTHENTIC;
1982182007Sroberto	else
1983182007Sroberto		peer->flags &= ~FLAG_AUTHENTIC;
1984290000Sglebius
1985290000Sglebius#ifdef AUTOKEY
198654359Sroberto	/*
198782505Sroberto	 * More autokey dance. The rules of the cha-cha are as follows:
198882505Sroberto	 *
198982505Sroberto	 * 1. If there is no key or the key is not auto, do nothing.
199082505Sroberto	 *
1991132454Sroberto	 * 2. If this packet is in response to the one just previously
1992132454Sroberto	 *    sent or from a broadcast server, do the extension fields.
1993132454Sroberto	 *    Otherwise, assume bogosity and bail out.
1994132454Sroberto	 *
1995132454Sroberto	 * 3. If an extension field contains a verified signature, it is
199682505Sroberto	 *    self-authenticated and we sit the dance.
199782505Sroberto	 *
1998132454Sroberto	 * 4. If this is a server reply, check only to see that the
199982505Sroberto	 *    transmitted key ID matches the received key ID.
200082505Sroberto	 *
2001132454Sroberto	 * 5. Check to see that one or more hashes of the current key ID
200282505Sroberto	 *    matches the previous key ID or ultimate original key ID
200382505Sroberto	 *    obtained from the broadcaster or symmetric peer. If no
2004290000Sglebius	 *    match, sit the dance and call for new autokey values.
2005182007Sroberto	 *
2006290000Sglebius	 * In case of crypto error, fire the orchestra, stop dancing and
2007290000Sglebius	 * restart the protocol.
200854359Sroberto	 */
2009290000Sglebius	if (peer->flags & FLAG_SKEY) {
2010290000Sglebius		/*
2011290000Sglebius		 * Decrement remaining autokey hashes. This isn't
2012290000Sglebius		 * perfect if a packet is lost, but results in no harm.
2013290000Sglebius		 */
2014290000Sglebius		ap = (struct autokey *)peer->recval.ptr;
2015290000Sglebius		if (ap != NULL) {
2016290000Sglebius			if (ap->seq > 0)
2017290000Sglebius				ap->seq--;
2018290000Sglebius		}
2019182007Sroberto		peer->flash |= TEST8;
2020132454Sroberto		rval = crypto_recv(peer, rbufp);
2021290000Sglebius		if (rval == XEVNT_OK) {
2022290000Sglebius			peer->unreach = 0;
2023290000Sglebius		} else {
2024290000Sglebius			if (rval == XEVNT_ERR) {
2025290000Sglebius				report_event(PEVNT_RESTART, peer,
2026290000Sglebius				    "crypto error");
2027290000Sglebius				peer_clear(peer, "CRYP");
2028290000Sglebius				peer->flash |= TEST9;	/* bad crypt */
2029294904Sdelphij				if (peer->flags & FLAG_PREEMPT) {
2030294904Sdelphij					if (unpeer_crypto_early) {
2031294904Sdelphij						unpeer(peer);
2032294904Sdelphij					}
2033294904Sdelphij				}
2034290000Sglebius			}
2035182007Sroberto			return;
2036290000Sglebius		}
2037132454Sroberto
2038290000Sglebius		/*
2039290000Sglebius		 * If server mode, verify the receive key ID matches
2040290000Sglebius		 * the transmit key ID.
2041290000Sglebius		 */
2042290000Sglebius		if (hismode == MODE_SERVER) {
204382505Sroberto			if (skeyid == peer->keyid)
2044182007Sroberto				peer->flash &= ~TEST8;
2045290000Sglebius
2046290000Sglebius		/*
2047290000Sglebius		 * If an extension field is present, verify only that it
2048290000Sglebius		 * has been correctly signed. We don't need a sequence
2049290000Sglebius		 * check here, but the sequence continues.
2050290000Sglebius		 */
2051182007Sroberto		} else if (!(peer->flash & TEST8)) {
205282505Sroberto			peer->pkeyid = skeyid;
2053290000Sglebius
2054290000Sglebius		/*
2055290000Sglebius		 * Now the fun part. Here, skeyid is the current ID in
2056290000Sglebius		 * the packet, pkeyid is the ID in the last packet and
2057290000Sglebius		 * tkeyid is the hash of skeyid. If the autokey values
2058290000Sglebius		 * have not been received, this is an automatic error.
2059290000Sglebius		 * If so, check that the tkeyid matches pkeyid. If not,
2060290000Sglebius		 * hash tkeyid and try again. If the number of hashes
2061290000Sglebius		 * exceeds the number remaining in the sequence, declare
2062290000Sglebius		 * a successful failure and refresh the autokey values.
2063290000Sglebius		 */
2064290000Sglebius		} else if (ap != NULL) {
206582505Sroberto			int i;
206682505Sroberto
206782505Sroberto			for (i = 0; ; i++) {
2068290000Sglebius				if (   tkeyid == peer->pkeyid
2069290000Sglebius				    || tkeyid == ap->key) {
2070182007Sroberto					peer->flash &= ~TEST8;
207182505Sroberto					peer->pkeyid = skeyid;
2072290000Sglebius					ap->seq -= i;
207382505Sroberto					break;
207482505Sroberto				}
2075290000Sglebius				if (i > ap->seq) {
2076290000Sglebius					peer->crypto &=
2077290000Sglebius					    ~CRYPTO_FLAG_AUTO;
207882505Sroberto					break;
2079290000Sglebius				}
208054359Sroberto				tkeyid = session_key(
208182505Sroberto				    &rbufp->recv_srcadr, dstadr_sin,
208282505Sroberto				    tkeyid, pkeyid, 0);
208354359Sroberto			}
2084290000Sglebius			if (peer->flash & TEST8)
2085290000Sglebius				report_event(PEVNT_AUTH, peer, "keylist");
208654359Sroberto		}
2087182007Sroberto		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2088290000Sglebius			peer->flash |= TEST8;	/* bad autokey */
208982505Sroberto
209082505Sroberto		/*
2091290000Sglebius		 * The maximum lifetime of the protocol is about one
2092290000Sglebius		 * week before restarting the Autokey protocol to
2093290000Sglebius		 * refresh certificates and leapseconds values.
209482505Sroberto		 */
2095290000Sglebius		if (current_time > peer->refresh) {
2096290000Sglebius			report_event(PEVNT_RESTART, peer,
2097290000Sglebius			    "crypto refresh");
2098290000Sglebius			peer_clear(peer, "TIME");
2099290000Sglebius			return;
2100132454Sroberto		}
210154359Sroberto	}
2102290000Sglebius#endif	/* AUTOKEY */
210354359Sroberto
210454359Sroberto	/*
2105182007Sroberto	 * The dance is complete and the flash bits have been lit. Toss
2106182007Sroberto	 * the packet over the fence for processing, which may light up
2107182007Sroberto	 * more flashers.
210854359Sroberto	 */
2109290000Sglebius	process_packet(peer, pkt, rbufp->recv_length);
2110182007Sroberto
2111182007Sroberto	/*
2112290000Sglebius	 * In interleaved mode update the state variables. Also adjust the
2113290000Sglebius	 * transmit phase to avoid crossover.
2114182007Sroberto	 */
2115290000Sglebius	if (peer->flip != 0) {
2116290000Sglebius		peer->rec = p_rec;
2117290000Sglebius		peer->dst = rbufp->recv_time;
2118290000Sglebius		if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2119290000Sglebius		    peer->hpoll)) / 2)
2120290000Sglebius			peer->nextdate++;
2121290000Sglebius		else
2122290000Sglebius			peer->nextdate--;
2123182007Sroberto	}
212454359Sroberto}
212554359Sroberto
212654359Sroberto
212754359Sroberto/*
2128301301Sdelphij * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2129301301Sdelphij *	Or almost, at least.  If we're in here we have a reasonable
2130301301Sdelphij *	expectation that we will be having a long term
213154359Sroberto *	relationship with this host.
213254359Sroberto */
213382505Srobertovoid
213454359Srobertoprocess_packet(
213554359Sroberto	register struct peer *peer,
2136290000Sglebius	register struct pkt *pkt,
2137290000Sglebius	u_int	len
213854359Sroberto	)
213954359Sroberto{
2140182007Sroberto	double	t34, t21;
2141132454Sroberto	double	p_offset, p_del, p_disp;
2142290000Sglebius	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
2143290000Sglebius	u_char	pmode, pleap, pversion, pstratum;
2144290000Sglebius	char	statstr[NTP_MAXSTRLEN];
2145290000Sglebius#ifdef ASSYM
2146290000Sglebius	int	itemp;
2147290000Sglebius	double	etemp, ftemp, td;
2148290000Sglebius#endif /* ASSYM */
214954359Sroberto
2150301301Sdelphij#if 0
215154359Sroberto	sys_processed++;
215254359Sroberto	peer->processed++;
2153301301Sdelphij#endif
215454359Sroberto	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2155290000Sglebius	p_offset = 0;
2156290000Sglebius	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
215754359Sroberto	NTOHL_FP(&pkt->reftime, &p_reftime);
2158290000Sglebius	NTOHL_FP(&pkt->org, &p_org);
215954359Sroberto	NTOHL_FP(&pkt->rec, &p_rec);
216054359Sroberto	NTOHL_FP(&pkt->xmt, &p_xmt);
2161132454Sroberto	pmode = PKT_MODE(pkt->li_vn_mode);
2162132454Sroberto	pleap = PKT_LEAP(pkt->li_vn_mode);
2163290000Sglebius	pversion = PKT_VERSION(pkt->li_vn_mode);
2164132454Sroberto	pstratum = PKT_TO_STRATUM(pkt->stratum);
216554359Sroberto
2166301301Sdelphij	/**/
2167301301Sdelphij
2168301301Sdelphij	/**/
2169301301Sdelphij
217054359Sroberto	/*
2171301301Sdelphij	 * Verify the server is synchronized; that is, the leap bits,
2172301301Sdelphij	 * stratum and root distance are valid.
2173301301Sdelphij	 */
2174301301Sdelphij	if (   pleap == LEAP_NOTINSYNC		/* test 6 */
2175301301Sdelphij	    || pstratum < sys_floor || pstratum >= sys_ceiling)
2176301301Sdelphij		peer->flash |= TEST6;		/* bad synch or strat */
2177301301Sdelphij	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
2178301301Sdelphij		peer->flash |= TEST7;		/* bad header */
2179301301Sdelphij
2180301301Sdelphij	/*
2181301301Sdelphij	 * If any tests fail at this point, the packet is discarded.
2182301301Sdelphij	 * Note that some flashers may have already been set in the
2183301301Sdelphij	 * receive() routine.
2184301301Sdelphij	 */
2185301301Sdelphij	if (peer->flash & PKT_TEST_MASK) {
2186301301Sdelphij		peer->seldisptoolarge++;
2187301301Sdelphij		DPRINTF(1, ("packet: flash header %04x\n",
2188301301Sdelphij			    peer->flash));
2189301301Sdelphij		return;
2190301301Sdelphij	}
2191301301Sdelphij
2192301301Sdelphij	/**/
2193301301Sdelphij
2194301301Sdelphij#if 1
2195301301Sdelphij	sys_processed++;
2196301301Sdelphij	peer->processed++;
2197301301Sdelphij#endif
2198301301Sdelphij
2199301301Sdelphij	/*
2200290000Sglebius	 * Capture the header values in the client/peer association..
220154359Sroberto	 */
2202290000Sglebius	record_raw_stats(&peer->srcadr, peer->dstadr ?
2203290000Sglebius	    &peer->dstadr->sin : NULL,
2204290000Sglebius	    &p_org, &p_rec, &p_xmt, &peer->dst,
2205290000Sglebius	    pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2206290000Sglebius	    p_del, p_disp, pkt->refid);
2207132454Sroberto	peer->leap = pleap;
2208182007Sroberto	peer->stratum = min(pstratum, STRATUM_UNSPEC);
2209182007Sroberto	peer->pmode = pmode;
2210182007Sroberto	peer->precision = pkt->precision;
2211182007Sroberto	peer->rootdelay = p_del;
2212290000Sglebius	peer->rootdisp = p_disp;
2213182007Sroberto	peer->refid = pkt->refid;		/* network byte order */
2214182007Sroberto	peer->reftime = p_reftime;
221582505Sroberto
221682505Sroberto	/*
2217290000Sglebius	 * First, if either burst mode is armed, enable the burst.
2218290000Sglebius	 * Compute the headway for the next packet and delay if
2219290000Sglebius	 * necessary to avoid exceeding the threshold.
222082505Sroberto	 */
2221290000Sglebius	if (peer->retry > 0) {
2222290000Sglebius		peer->retry = 0;
2223290000Sglebius		if (peer->reach)
2224290000Sglebius			peer->burst = min(1 << (peer->hpoll -
2225290000Sglebius			    peer->minpoll), NTP_SHIFT) - 1;
2226290000Sglebius		else
2227290000Sglebius			peer->burst = NTP_IBURST - 1;
2228290000Sglebius		if (peer->burst > 0)
2229290000Sglebius			peer->nextdate = current_time;
2230290000Sglebius	}
2231290000Sglebius	poll_update(peer, peer->hpoll);
2232290000Sglebius
2233301301Sdelphij	/**/
2234132454Sroberto
2235132454Sroberto	/*
2236290000Sglebius	 * If the peer was previously unreachable, raise a trap. In any
2237290000Sglebius	 * case, mark it reachable.
2238290000Sglebius	 */
2239290000Sglebius	if (!peer->reach) {
2240290000Sglebius		report_event(PEVNT_REACH, peer, NULL);
224154359Sroberto		peer->timereachable = current_time;
224254359Sroberto	}
224354359Sroberto	peer->reach |= 1;
224454359Sroberto
224554359Sroberto	/*
2246182007Sroberto	 * For a client/server association, calculate the clock offset,
2247182007Sroberto	 * roundtrip delay and dispersion. The equations are reordered
2248182007Sroberto	 * from the spec for more efficient use of temporaries. For a
2249182007Sroberto	 * broadcast association, offset the last measurement by the
2250290000Sglebius	 * computed delay during the client/server volley. Note the
2251182007Sroberto	 * computation of dispersion includes the system precision plus
2252182007Sroberto	 * that due to the frequency error since the origin time.
225354359Sroberto	 *
2254182007Sroberto	 * It is very important to respect the hazards of overflow. The
2255182007Sroberto	 * only permitted operation on raw timestamps is subtraction,
2256182007Sroberto	 * where the result is a signed quantity spanning from 68 years
2257182007Sroberto	 * in the past to 68 years in the future. To avoid loss of
2258182007Sroberto	 * precision, these calculations are done using 64-bit integer
2259182007Sroberto	 * arithmetic. However, the offset and delay calculations are
2260182007Sroberto	 * sums and differences of these first-order differences, which
2261182007Sroberto	 * if done using 64-bit integer arithmetic, would be valid over
2262182007Sroberto	 * only half that span. Since the typical first-order
2263182007Sroberto	 * differences are usually very small, they are converted to 64-
2264182007Sroberto	 * bit doubles and all remaining calculations done in floating-
2265290000Sglebius	 * double arithmetic. This preserves the accuracy while
2266290000Sglebius	 * retaining the 68-year span.
2267182007Sroberto	 *
2268290000Sglebius	 * There are three interleaving schemes, basic, interleaved
2269290000Sglebius	 * symmetric and interleaved broadcast. The timestamps are
2270290000Sglebius	 * idioscyncratically different. See the onwire briefing/white
2271290000Sglebius	 * paper at www.eecis.udel.edu/~mills for details.
2272290000Sglebius	 *
2273290000Sglebius	 * Interleaved symmetric mode
2274290000Sglebius	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2275290000Sglebius	 * t4 = peer->dst
227654359Sroberto	 */
2277290000Sglebius	if (peer->flip != 0) {
2278290000Sglebius		ci = p_xmt;				/* t3 - t4 */
2279290000Sglebius		L_SUB(&ci, &peer->dst);
2280290000Sglebius		LFPTOD(&ci, t34);
2281290000Sglebius		ci = p_rec;				/* t2 - t1 */
2282290000Sglebius		if (peer->flip > 0)
2283290000Sglebius			L_SUB(&ci, &peer->borg);
2284290000Sglebius		else
2285290000Sglebius			L_SUB(&ci, &peer->aorg);
2286290000Sglebius		LFPTOD(&ci, t21);
2287290000Sglebius		p_del = t21 - t34;
2288290000Sglebius		p_offset = (t21 + t34) / 2.;
2289290000Sglebius		if (p_del < 0 || p_del > 1.) {
2290290000Sglebius			snprintf(statstr, sizeof(statstr),
2291290000Sglebius			    "t21 %.6f t34 %.6f", t21, t34);
2292290000Sglebius			report_event(PEVNT_XERR, peer, statstr);
2293290000Sglebius			return;
2294290000Sglebius		}
229554359Sroberto
229654359Sroberto	/*
2297290000Sglebius	 * Broadcast modes
229854359Sroberto	 */
2299290000Sglebius	} else if (peer->pmode == MODE_BROADCAST) {
2300290000Sglebius
2301290000Sglebius		/*
2302290000Sglebius		 * Interleaved broadcast mode. Use interleaved timestamps.
2303290000Sglebius		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2304290000Sglebius		 */
2305290000Sglebius		if (peer->flags & FLAG_XB) {
2306290000Sglebius			ci = p_org;			/* delay */
2307290000Sglebius			L_SUB(&ci, &peer->aorg);
2308290000Sglebius			LFPTOD(&ci, t34);
2309290000Sglebius			ci = p_org;			/* t2 - t1 */
2310290000Sglebius			L_SUB(&ci, &peer->borg);
2311290000Sglebius			LFPTOD(&ci, t21);
2312290000Sglebius			peer->aorg = p_xmt;
2313290000Sglebius			peer->borg = peer->dst;
2314290000Sglebius			if (t34 < 0 || t34 > 1.) {
2315298770Sdelphij				/* drop all if in the initial volley */
2316298770Sdelphij				if (FLAG_BC_VOL & peer->flags)
2317298770Sdelphij					goto bcc_init_volley_fail;
2318290000Sglebius				snprintf(statstr, sizeof(statstr),
2319290000Sglebius				    "offset %.6f delay %.6f", t21, t34);
2320290000Sglebius				report_event(PEVNT_XERR, peer, statstr);
232182505Sroberto				return;
2322290000Sglebius			}
2323290000Sglebius			p_offset = t21;
2324290000Sglebius			peer->xleave = t34;
232554359Sroberto
2326290000Sglebius		/*
2327290000Sglebius		 * Basic broadcast - use direct timestamps.
2328290000Sglebius		 * t3 = p_xmt, t4 = peer->dst
2329290000Sglebius		 */
2330290000Sglebius		} else {
2331290000Sglebius			ci = p_xmt;		/* t3 - t4 */
2332290000Sglebius			L_SUB(&ci, &peer->dst);
2333290000Sglebius			LFPTOD(&ci, t34);
2334290000Sglebius			p_offset = t34;
233554359Sroberto		}
2336290000Sglebius
2337290000Sglebius		/*
2338290000Sglebius		 * When calibration is complete and the clock is
2339290000Sglebius		 * synchronized, the bias is calculated as the difference
2340290000Sglebius		 * between the unicast timestamp and the broadcast
2341290000Sglebius		 * timestamp. This works for both basic and interleaved
2342290000Sglebius		 * modes.
2343298770Sdelphij		 * [Bug 3031] Don't keep this peer when the delay
2344298770Sdelphij		 * calculation gives reason to suspect clock steps.
2345298770Sdelphij		 * This is assumed for delays > 50ms.
2346290000Sglebius		 */
2347290000Sglebius		if (FLAG_BC_VOL & peer->flags) {
2348290000Sglebius			peer->flags &= ~FLAG_BC_VOL;
2349290000Sglebius			peer->delay = fabs(peer->offset - p_offset) * 2;
2350298770Sdelphij			DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2351298770Sdelphij				peer->delay));
2352298770Sdelphij			if (peer->delay > fabs(sys_bdelay)) {
2353298770Sdelphij		bcc_init_volley_fail:
2354298770Sdelphij				DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2355298770Sdelphij				unpeer(peer);
2356298770Sdelphij				return;
2357298770Sdelphij			}
2358290000Sglebius		}
2359298770Sdelphij		peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
236054359Sroberto		p_del = peer->delay;
2361290000Sglebius		p_offset += p_del / 2;
2362290000Sglebius
2363290000Sglebius
2364290000Sglebius	/*
2365290000Sglebius	 * Basic mode, otherwise known as the old fashioned way.
2366290000Sglebius	 *
2367290000Sglebius	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2368290000Sglebius	 */
236954359Sroberto	} else {
2370290000Sglebius		ci = p_xmt;				/* t3 - t4 */
2371290000Sglebius		L_SUB(&ci, &peer->dst);
2372290000Sglebius		LFPTOD(&ci, t34);
2373290000Sglebius		ci = p_rec;				/* t2 - t1 */
2374290000Sglebius		L_SUB(&ci, &p_org);
2375290000Sglebius		LFPTOD(&ci, t21);
2376290000Sglebius		p_del = fabs(t21 - t34);
2377182007Sroberto		p_offset = (t21 + t34) / 2.;
237854359Sroberto	}
237982505Sroberto	p_del = max(p_del, LOGTOD(sys_precision));
2380290000Sglebius	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2381290000Sglebius	    clock_phi * p_del;
2382290000Sglebius
2383290000Sglebius#if ASSYM
2384290000Sglebius	/*
2385290000Sglebius	 * This code calculates the outbound and inbound data rates by
2386290000Sglebius	 * measuring the differences between timestamps at different
2387290000Sglebius	 * packet lengths. This is helpful in cases of large asymmetric
2388290000Sglebius	 * delays commonly experienced on deep space communication
2389290000Sglebius	 * links.
2390290000Sglebius	 */
2391290000Sglebius	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2392290000Sglebius		itemp = peer->t21_bytes - peer->t21_last;
2393290000Sglebius		if (itemp > 25) {
2394290000Sglebius			etemp = t21 - peer->t21;
2395290000Sglebius			if (fabs(etemp) > 1e-6) {
2396290000Sglebius				ftemp = itemp / etemp;
2397290000Sglebius				if (ftemp > 1000.)
2398290000Sglebius					peer->r21 = ftemp;
2399290000Sglebius			}
2400290000Sglebius		}
2401290000Sglebius		itemp = len - peer->t34_bytes;
2402290000Sglebius		if (itemp > 25) {
2403290000Sglebius			etemp = -t34 - peer->t34;
2404290000Sglebius			if (fabs(etemp) > 1e-6) {
2405290000Sglebius				ftemp = itemp / etemp;
2406290000Sglebius				if (ftemp > 1000.)
2407290000Sglebius					peer->r34 = ftemp;
2408290000Sglebius			}
2409290000Sglebius		}
2410290000Sglebius	}
2411290000Sglebius
2412290000Sglebius	/*
2413290000Sglebius	 * The following section compensates for different data rates on
2414290000Sglebius	 * the outbound (d21) and inbound (t34) directions. To do this,
2415290000Sglebius	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2416290000Sglebius	 * the roundtrip delay. Then it calculates the correction as a
2417290000Sglebius	 * fraction of d.
2418290000Sglebius	 */
2419293894Sglebius	peer->t21 = t21;
2420290000Sglebius	peer->t21_last = peer->t21_bytes;
2421290000Sglebius	peer->t34 = -t34;
2422290000Sglebius	peer->t34_bytes = len;
2423293894Sglebius	DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2424293894Sglebius		    peer->t21_bytes, peer->t34, peer->t34_bytes));
2425290000Sglebius	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2426290000Sglebius		if (peer->pmode != MODE_BROADCAST)
2427290000Sglebius			td = (peer->r34 / (peer->r21 + peer->r34) -
2428290000Sglebius			    .5) * p_del;
2429290000Sglebius		else
2430290000Sglebius			td = 0;
2431290000Sglebius
2432290000Sglebius		/*
2433293894Sglebius		 * Unfortunately, in many cases the errors are
2434290000Sglebius		 * unacceptable, so for the present the rates are not
2435290000Sglebius		 * used. In future, we might find conditions where the
2436290000Sglebius		 * calculations are useful, so this should be considered
2437290000Sglebius		 * a work in progress.
2438290000Sglebius		 */
2439290000Sglebius		t21 -= td;
2440290000Sglebius		t34 -= td;
2441293894Sglebius		DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2442290000Sglebius			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2443293894Sglebius			    td));
2444290000Sglebius	}
2445290000Sglebius#endif /* ASSYM */
2446290000Sglebius
2447290000Sglebius	/*
2448290000Sglebius	 * That was awesome. Now hand off to the clock filter.
2449290000Sglebius	 */
2450290000Sglebius	clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2451290000Sglebius
2452290000Sglebius	/*
2453290000Sglebius	 * If we are in broadcast calibrate mode, return to broadcast
2454290000Sglebius	 * client mode when the client is fit and the autokey dance is
2455290000Sglebius	 * complete.
2456290000Sglebius	 */
2457290000Sglebius	if (   (FLAG_BC_VOL & peer->flags)
2458290000Sglebius	    && MODE_CLIENT == peer->hmode
2459290000Sglebius	    && !(TEST11 & peer_unfit(peer))) {	/* distance exceeded */
2460290000Sglebius#ifdef AUTOKEY
2461290000Sglebius		if (peer->flags & FLAG_SKEY) {
2462290000Sglebius			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2463290000Sglebius				peer->hmode = MODE_BCLIENT;
2464290000Sglebius		} else {
2465290000Sglebius			peer->hmode = MODE_BCLIENT;
2466290000Sglebius		}
2467290000Sglebius#else	/* !AUTOKEY follows */
2468290000Sglebius		peer->hmode = MODE_BCLIENT;
2469290000Sglebius#endif	/* !AUTOKEY */
2470290000Sglebius	}
247154359Sroberto}
247254359Sroberto
247354359Sroberto
247454359Sroberto/*
247554359Sroberto * clock_update - Called at system process update intervals.
247654359Sroberto */
247754359Srobertostatic void
2478290000Sglebiusclock_update(
2479290000Sglebius	struct peer *peer	/* peer structure pointer */
2480290000Sglebius	)
248154359Sroberto{
2482182007Sroberto	double	dtemp;
2483290000Sglebius	l_fp	now;
2484290000Sglebius#ifdef HAVE_LIBSCF_H
2485290000Sglebius	char	*fmri;
2486290000Sglebius#endif /* HAVE_LIBSCF_H */
248754359Sroberto
248854359Sroberto	/*
2489290000Sglebius	 * Update the system state variables. We do this very carefully,
2490290000Sglebius	 * as the poll interval might need to be clamped differently.
249154359Sroberto	 */
2492290000Sglebius	sys_peer = peer;
2493290000Sglebius	sys_epoch = peer->epoch;
2494290000Sglebius	if (sys_poll < peer->minpoll)
2495290000Sglebius		sys_poll = peer->minpoll;
2496290000Sglebius	if (sys_poll > peer->maxpoll)
2497290000Sglebius		sys_poll = peer->maxpoll;
2498290000Sglebius	poll_update(peer, sys_poll);
2499290000Sglebius	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2500290000Sglebius	if (   peer->stratum == STRATUM_REFCLOCK
2501290000Sglebius	    || peer->stratum == STRATUM_UNSPEC)
2502290000Sglebius		sys_refid = peer->refid;
2503290000Sglebius	else
2504290000Sglebius		sys_refid = addr2refid(&peer->srcadr);
2505290000Sglebius	/*
2506290000Sglebius	 * Root Dispersion (E) is defined (in RFC 5905) as:
2507290000Sglebius	 *
2508290000Sglebius	 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2509290000Sglebius	 *
2510290000Sglebius	 * where:
2511290000Sglebius	 *  p.epsilon_r is the PollProc's root dispersion
2512290000Sglebius	 *  p.epsilon   is the PollProc's dispersion
2513290000Sglebius	 *  p.psi       is the PollProc's jitter
2514290000Sglebius	 *  THETA       is the combined offset
2515290000Sglebius	 *
2516290000Sglebius	 * NB: Think Hard about where these numbers come from and
2517290000Sglebius	 * what they mean.  When did peer->update happen?  Has anything
2518290000Sglebius	 * interesting happened since then?  What values are the most
2519290000Sglebius	 * defensible?  Why?
2520290000Sglebius	 *
2521290000Sglebius	 * DLM thinks this equation is probably the best of all worse choices.
2522290000Sglebius	 */
2523290000Sglebius	dtemp	= peer->rootdisp
2524290000Sglebius		+ peer->disp
2525290000Sglebius		+ sys_jitter
2526290000Sglebius		+ clock_phi * (current_time - peer->update)
2527290000Sglebius		+ fabs(sys_offset);
2528182007Sroberto
2529290000Sglebius	if (dtemp > sys_mindisp)
2530290000Sglebius		sys_rootdisp = dtemp;
2531290000Sglebius	else
2532290000Sglebius		sys_rootdisp = sys_mindisp;
2533290000Sglebius	sys_rootdelay = peer->delay + peer->rootdelay;
2534290000Sglebius	sys_reftime = peer->dst;
2535290000Sglebius
2536293894Sglebius	DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2537293894Sglebius		    current_time, peer->epoch, peer->associd));
253854359Sroberto
253982505Sroberto	/*
2540290000Sglebius	 * Comes now the moment of truth. Crank the clock discipline and
2541290000Sglebius	 * see what comes out.
2542290000Sglebius	 */
2543290000Sglebius	switch (local_clock(peer, sys_offset)) {
2544290000Sglebius
2545290000Sglebius	/*
2546182007Sroberto	 * Clock exceeds panic threshold. Life as we know it ends.
254782505Sroberto	 */
254882505Sroberto	case -1:
2549290000Sglebius#ifdef HAVE_LIBSCF_H
2550290000Sglebius		/*
2551290000Sglebius		 * For Solaris enter the maintenance mode.
2552290000Sglebius		 */
2553290000Sglebius		if ((fmri = getenv("SMF_FMRI")) != NULL) {
2554290000Sglebius			if (smf_maintain_instance(fmri, 0) < 0) {
2555290000Sglebius				printf("smf_maintain_instance: %s\n",
2556290000Sglebius				    scf_strerror(scf_error()));
2557290000Sglebius				exit(1);
2558290000Sglebius			}
2559290000Sglebius			/*
2560290000Sglebius			 * Sleep until SMF kills us.
2561290000Sglebius			 */
2562290000Sglebius			for (;;)
2563290000Sglebius				pause();
2564290000Sglebius		}
2565290000Sglebius#endif /* HAVE_LIBSCF_H */
2566132454Sroberto		exit (-1);
2567182007Sroberto		/* not reached */
256854359Sroberto
256982505Sroberto	/*
257082505Sroberto	 * Clock was stepped. Flush all time values of all peers.
257182505Sroberto	 */
2572182007Sroberto	case 2:
257382505Sroberto		clear_all();
2574290000Sglebius		set_sys_leap(LEAP_NOTINSYNC);
2575182007Sroberto		sys_stratum = STRATUM_UNSPEC;
2576290000Sglebius		memcpy(&sys_refid, "STEP", 4);
2577182007Sroberto		sys_rootdelay = 0;
2578290000Sglebius		sys_rootdisp = 0;
2579290000Sglebius		L_CLR(&sys_reftime);
2580290000Sglebius		sys_jitter = LOGTOD(sys_precision);
2581290000Sglebius		leapsec_reset_frame();
258254359Sroberto		break;
258354359Sroberto
258482505Sroberto	/*
2585290000Sglebius	 * Clock was slewed. Handle the leapsecond stuff.
258682505Sroberto	 */
2587182007Sroberto	case 1:
2588182007Sroberto
2589182007Sroberto		/*
2590290000Sglebius		 * If this is the first time the clock is set, reset the
2591290000Sglebius		 * leap bits. If crypto, the timer will goose the setup
2592290000Sglebius		 * process.
2593182007Sroberto		 */
2594290000Sglebius		if (sys_leap == LEAP_NOTINSYNC) {
2595290000Sglebius			set_sys_leap(LEAP_NOWARNING);
2596290000Sglebius#ifdef AUTOKEY
2597290000Sglebius			if (crypto_flags)
2598290000Sglebius				crypto_update();
2599290000Sglebius#endif	/* AUTOKEY */
2600290000Sglebius			/*
2601290000Sglebius			 * If our parent process is waiting for the
2602290000Sglebius			 * first clock sync, send them home satisfied.
2603290000Sglebius			 */
2604290000Sglebius#ifdef HAVE_WORKING_FORK
2605290000Sglebius			if (waitsync_fd_to_close != -1) {
2606290000Sglebius				close(waitsync_fd_to_close);
2607290000Sglebius				waitsync_fd_to_close = -1;
2608290000Sglebius				DPRINTF(1, ("notified parent --wait-sync is done\n"));
2609290000Sglebius			}
2610290000Sglebius#endif /* HAVE_WORKING_FORK */
2611290000Sglebius
2612182007Sroberto		}
2613290000Sglebius
2614290000Sglebius		/*
2615290000Sglebius		 * If there is no leap second pending and the number of
2616290000Sglebius		 * survivor leap bits is greater than half the number of
2617290000Sglebius		 * survivors, try to schedule a leap for the end of the
2618290000Sglebius		 * current month. (This only works if no leap second for
2619290000Sglebius		 * that range is in the table, so doing this more than
2620290000Sglebius		 * once is mostly harmless.)
2621290000Sglebius		 */
2622290000Sglebius		if (leapsec == LSPROX_NOWARN) {
2623290000Sglebius			if (   leap_vote_ins > leap_vote_del
2624290000Sglebius			    && leap_vote_ins > sys_survivors / 2) {
2625290000Sglebius				get_systime(&now);
2626290000Sglebius				leapsec_add_dyn(TRUE, now.l_ui, NULL);
2627290000Sglebius			}
2628290000Sglebius			if (   leap_vote_del > leap_vote_ins
2629290000Sglebius			    && leap_vote_del > sys_survivors / 2) {
2630290000Sglebius				get_systime(&now);
2631290000Sglebius				leapsec_add_dyn(FALSE, now.l_ui, NULL);
2632290000Sglebius			}
2633132454Sroberto		}
2634182007Sroberto		break;
2635290000Sglebius
2636182007Sroberto	/*
2637182007Sroberto	 * Popcorn spike or step threshold exceeded. Pretend it never
2638182007Sroberto	 * happened.
2639182007Sroberto	 */
2640182007Sroberto	default:
2641182007Sroberto		break;
264254359Sroberto	}
264354359Sroberto}
264454359Sroberto
264554359Sroberto
264654359Sroberto/*
264782505Sroberto * poll_update - update peer poll interval
264854359Sroberto */
264954359Srobertovoid
265054359Srobertopoll_update(
2651290000Sglebius	struct peer *peer,	/* peer structure pointer */
2652290000Sglebius	u_char	mpoll
265354359Sroberto	)
265454359Sroberto{
2655290000Sglebius	u_long	next, utemp;
2656290000Sglebius	u_char	hpoll;
265754359Sroberto
265854359Sroberto	/*
2659182007Sroberto	 * This routine figures out when the next poll should be sent.
2660290000Sglebius	 * That turns out to be wickedly complicated. One problem is
2661290000Sglebius	 * that sometimes the time for the next poll is in the past when
2662290000Sglebius	 * the poll interval is reduced. We watch out for races here
2663290000Sglebius	 * between the receive process and the poll process.
2664182007Sroberto	 *
2665290000Sglebius	 * Clamp the poll interval between minpoll and maxpoll.
266654359Sroberto	 */
2667290000Sglebius	hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2668182007Sroberto
2669290000Sglebius#ifdef AUTOKEY
2670182007Sroberto	/*
2671290000Sglebius	 * If during the crypto protocol the poll interval has changed,
2672290000Sglebius	 * the lifetimes in the key list are probably bogus. Purge the
2673290000Sglebius	 * the key list and regenerate it later.
2674182007Sroberto	 */
2675290000Sglebius	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2676182007Sroberto		key_expire(peer);
2677290000Sglebius#endif	/* AUTOKEY */
2678182007Sroberto	peer->hpoll = hpoll;
267982505Sroberto
268082505Sroberto	/*
2681290000Sglebius	 * There are three variables important for poll scheduling, the
2682290000Sglebius	 * current time (current_time), next scheduled time (nextdate)
2683290000Sglebius	 * and the earliest time (utemp). The earliest time is 2 s
2684290000Sglebius	 * seconds, but could be more due to rate management. When
2685290000Sglebius	 * sending in a burst, use the earliest time. When not in a
2686290000Sglebius	 * burst but with a reply pending, send at the earliest time
2687290000Sglebius	 * unless the next scheduled time has not advanced. This can
2688290000Sglebius	 * only happen if multiple replies are pending in the same
2689290000Sglebius	 * response interval. Otherwise, send at the later of the next
2690290000Sglebius	 * scheduled time and the earliest time.
2691290000Sglebius	 *
2692290000Sglebius	 * Now we figure out if there is an override. If a burst is in
2693290000Sglebius	 * progress and we get called from the receive process, just
2694290000Sglebius	 * slink away. If called from the poll process, delay 1 s for a
2695290000Sglebius	 * reference clock, otherwise 2 s.
269682505Sroberto	 */
2697290000Sglebius	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2698290000Sglebius	    (1 << peer->minpoll), ntp_minpkt);
269954359Sroberto	if (peer->burst > 0) {
2700290000Sglebius		if (peer->nextdate > current_time)
270154359Sroberto			return;
270282505Sroberto#ifdef REFCLOCK
270382505Sroberto		else if (peer->flags & FLAG_REFCLOCK)
2704290000Sglebius			peer->nextdate = current_time + RESP_DELAY;
2705182007Sroberto#endif /* REFCLOCK */
270654359Sroberto		else
2707290000Sglebius			peer->nextdate = utemp;
2708290000Sglebius
2709290000Sglebius#ifdef AUTOKEY
2710182007Sroberto	/*
2711290000Sglebius	 * If a burst is not in progress and a crypto response message
2712290000Sglebius	 * is pending, delay 2 s, but only if this is a new interval.
2713182007Sroberto	 */
2714290000Sglebius	} else if (peer->cmmd != NULL) {
2715290000Sglebius		if (peer->nextdate > current_time) {
2716290000Sglebius			if (peer->nextdate + ntp_minpkt != utemp)
2717290000Sglebius				peer->nextdate = utemp;
2718290000Sglebius		} else {
2719290000Sglebius			peer->nextdate = utemp;
2720290000Sglebius		}
2721290000Sglebius#endif	/* AUTOKEY */
2722182007Sroberto
272382505Sroberto	/*
2724290000Sglebius	 * The ordinary case. If a retry, use minpoll; if unreachable,
2725290000Sglebius	 * use host poll; otherwise, use the minimum of host and peer
2726290000Sglebius	 * polls; In other words, oversampling is okay but
2727290000Sglebius	 * understampling is evil. Use the maximum of this value and the
2728290000Sglebius	 * headway. If the average headway is greater than the headway
2729290000Sglebius	 * threshold, increase the headway by the minimum interval.
273082505Sroberto	 */
2731290000Sglebius	} else {
2732290000Sglebius		if (peer->retry > 0)
2733290000Sglebius			hpoll = peer->minpoll;
2734290000Sglebius		else if (!(peer->reach))
2735290000Sglebius			hpoll = peer->hpoll;
2736290000Sglebius		else
2737290000Sglebius			hpoll = min(peer->ppoll, peer->hpoll);
2738290000Sglebius#ifdef REFCLOCK
2739290000Sglebius		if (peer->flags & FLAG_REFCLOCK)
2740290000Sglebius			next = 1 << hpoll;
2741290000Sglebius		else
2742290000Sglebius#endif /* REFCLOCK */
2743290000Sglebius			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2744290000Sglebius			    hpoll) >> 12;
2745290000Sglebius		next += peer->outdate;
2746290000Sglebius		if (next > utemp)
2747290000Sglebius			peer->nextdate = next;
2748290000Sglebius		else
2749290000Sglebius			peer->nextdate = utemp;
2750290000Sglebius		if (peer->throttle > (1 << peer->minpoll))
2751290000Sglebius			peer->nextdate += ntp_minpkt;
2752290000Sglebius	}
2753290000Sglebius	DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2754290000Sglebius		    current_time, ntoa(&peer->srcadr), peer->hpoll,
2755290000Sglebius		    peer->burst, peer->retry, peer->throttle,
2756290000Sglebius		    utemp - current_time, peer->nextdate -
2757290000Sglebius		    current_time));
275854359Sroberto}
275954359Sroberto
2760290000Sglebius
276154359Sroberto/*
2762290000Sglebius * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
2763290000Sglebius * spec.
276454359Sroberto */
276554359Srobertovoid
2766290000Sglebiuspeer_clear(
2767290000Sglebius	struct peer *peer,		/* peer structure */
2768290000Sglebius	const char *ident		/* tally lights */
2769290000Sglebius	)
277054359Sroberto{
2771290000Sglebius	u_char	u;
2772310419Sdelphij	l_fp	bxmt = peer->bxmt;	/* bcast clients retain this! */
2773290000Sglebius
2774290000Sglebius#ifdef AUTOKEY
277582505Sroberto	/*
277682505Sroberto	 * If cryptographic credentials have been acquired, toss them to
277782505Sroberto	 * Valhalla. Note that autokeys are ephemeral, in that they are
277882505Sroberto	 * tossed immediately upon use. Therefore, the keylist can be
277982505Sroberto	 * purged anytime without needing to preserve random keys. Note
278082505Sroberto	 * that, if the peer is purged, the cryptographic variables are
278182505Sroberto	 * purged, too. This makes it much harder to sneak in some
278282505Sroberto	 * unauthenticated data in the clock filter.
278382505Sroberto	 */
2784290000Sglebius	key_expire(peer);
2785132454Sroberto	if (peer->iffval != NULL)
2786132454Sroberto		BN_free(peer->iffval);
2787132454Sroberto	value_free(&peer->cookval);
2788132454Sroberto	value_free(&peer->recval);
2789290000Sglebius	value_free(&peer->encrypt);
2790290000Sglebius	value_free(&peer->sndval);
2791290000Sglebius	if (peer->cmmd != NULL)
2792182007Sroberto		free(peer->cmmd);
2793290000Sglebius	if (peer->subject != NULL)
2794290000Sglebius		free(peer->subject);
2795290000Sglebius	if (peer->issuer != NULL)
2796290000Sglebius		free(peer->issuer);
2797290000Sglebius#endif /* AUTOKEY */
2798182007Sroberto
279982505Sroberto	/*
2800290000Sglebius	 * Clear all values, including the optional crypto values above.
280182505Sroberto	 */
2802290000Sglebius	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
280382505Sroberto	peer->ppoll = peer->maxpoll;
2804182007Sroberto	peer->hpoll = peer->minpoll;
2805182007Sroberto	peer->disp = MAXDISPERSE;
2806290000Sglebius	peer->flash = peer_unfit(peer);
2807182007Sroberto	peer->jitter = LOGTOD(sys_precision);
2808290000Sglebius
2809310419Sdelphij	/* Don't throw away our broadcast replay protection */
2810310419Sdelphij	if (peer->hmode == MODE_BCLIENT)
2811310419Sdelphij		peer->bxmt = bxmt;
2812310419Sdelphij
2813290000Sglebius	/*
2814290000Sglebius	 * If interleave mode, initialize the alternate origin switch.
2815290000Sglebius	 */
2816290000Sglebius	if (peer->flags & FLAG_XLEAVE)
2817290000Sglebius		peer->flip = 1;
2818290000Sglebius	for (u = 0; u < NTP_SHIFT; u++) {
2819290000Sglebius		peer->filter_order[u] = u;
2820290000Sglebius		peer->filter_disp[u] = MAXDISPERSE;
2821182007Sroberto	}
282282505Sroberto#ifdef REFCLOCK
282382505Sroberto	if (!(peer->flags & FLAG_REFCLOCK)) {
2824290000Sglebius#endif
282582505Sroberto		peer->leap = LEAP_NOTINSYNC;
282682505Sroberto		peer->stratum = STRATUM_UNSPEC;
2827132454Sroberto		memcpy(&peer->refid, ident, 4);
2828290000Sglebius#ifdef REFCLOCK
282982505Sroberto	}
2830290000Sglebius#endif
283154359Sroberto
283254359Sroberto	/*
2833182007Sroberto	 * During initialization use the association count to spread out
2834290000Sglebius	 * the polls at one-second intervals. Passive associations'
2835290000Sglebius	 * first poll is delayed by the "discard minimum" to avoid rate
2836290000Sglebius	 * limiting. Other post-startup new or cleared associations
2837290000Sglebius	 * randomize the first poll over the minimum poll interval to
2838290000Sglebius	 * avoid implosion.
283954359Sroberto	 */
2840132454Sroberto	peer->nextdate = peer->update = peer->outdate = current_time;
2841290000Sglebius	if (initializing) {
2842182007Sroberto		peer->nextdate += peer_associations;
2843290000Sglebius	} else if (MODE_PASSIVE == peer->hmode) {
2844290000Sglebius		peer->nextdate += ntp_minpkt;
2845290000Sglebius	} else {
2846290000Sglebius		peer->nextdate += ntp_random() % peer->minpoll;
2847290000Sglebius	}
2848290000Sglebius#ifdef AUTOKEY
2849290000Sglebius	peer->refresh = current_time + (1 << NTP_REFRESH);
2850290000Sglebius#endif	/* AUTOKEY */
2851293894Sglebius	DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
2852290000Sglebius		    current_time, peer->nextdate, peer->associd,
2853293894Sglebius		    ident));
285454359Sroberto}
285554359Sroberto
285654359Sroberto
285754359Sroberto/*
285854359Sroberto * clock_filter - add incoming clock sample to filter register and run
285954359Sroberto *		  the filter procedure to find the best sample.
286054359Sroberto */
286154359Srobertovoid
286254359Srobertoclock_filter(
2863132454Sroberto	struct peer *peer,		/* peer structure pointer */
2864132454Sroberto	double	sample_offset,		/* clock offset */
2865132454Sroberto	double	sample_delay,		/* roundtrip delay */
2866132454Sroberto	double	sample_disp		/* dispersion */
286754359Sroberto	)
286854359Sroberto{
2869132454Sroberto	double	dst[NTP_SHIFT];		/* distance vector */
2870132454Sroberto	int	ord[NTP_SHIFT];		/* index vector */
2871132454Sroberto	int	i, j, k, m;
2872182007Sroberto	double	dtemp, etemp;
2873290000Sglebius	char	tbuf[80];
287454359Sroberto
287554359Sroberto	/*
2876290000Sglebius	 * A sample consists of the offset, delay, dispersion and epoch
2877290000Sglebius	 * of arrival. The offset and delay are determined by the on-
2878290000Sglebius	 * wire protocol. The dispersion grows from the last outbound
2879290000Sglebius	 * packet to the arrival of this one increased by the sum of the
2880290000Sglebius	 * peer precision and the system precision as required by the
2881290000Sglebius	 * error budget. First, shift the new arrival into the shift
2882290000Sglebius	 * register discarding the oldest one.
288354359Sroberto	 */
288454359Sroberto	j = peer->filter_nextpt;
288582505Sroberto	peer->filter_offset[j] = sample_offset;
2886290000Sglebius	peer->filter_delay[j] = sample_delay;
2887182007Sroberto	peer->filter_disp[j] = sample_disp;
2888182007Sroberto	peer->filter_epoch[j] = current_time;
2889182007Sroberto	j = (j + 1) % NTP_SHIFT;
2890182007Sroberto	peer->filter_nextpt = j;
289154359Sroberto
289254359Sroberto	/*
289382505Sroberto	 * Update dispersions since the last update and at the same
2894290000Sglebius	 * time initialize the distance and index lists. Since samples
2895290000Sglebius	 * become increasingly uncorrelated beyond the Allan intercept,
2896290000Sglebius	 * only under exceptional cases will an older sample be used.
2897290000Sglebius	 * Therefore, the distance list uses a compound metric. If the
2898290000Sglebius	 * dispersion is greater than the maximum dispersion, clamp the
2899290000Sglebius	 * distance at that value. If the time since the last update is
2900290000Sglebius	 * less than the Allan intercept use the delay; otherwise, use
2901290000Sglebius	 * the sum of the delay and dispersion.
290254359Sroberto	 */
290382505Sroberto	dtemp = clock_phi * (current_time - peer->update);
290482505Sroberto	peer->update = current_time;
290582505Sroberto	for (i = NTP_SHIFT - 1; i >= 0; i--) {
2906132454Sroberto		if (i != 0)
290782505Sroberto			peer->filter_disp[j] += dtemp;
2908290000Sglebius		if (peer->filter_disp[j] >= MAXDISPERSE) {
2909132454Sroberto			peer->filter_disp[j] = MAXDISPERSE;
291082505Sroberto			dst[i] = MAXDISPERSE;
2911290000Sglebius		} else if (peer->update - peer->filter_epoch[j] >
2912290000Sglebius		    (u_long)ULOGTOD(allan_xpt)) {
2913290000Sglebius			dst[i] = peer->filter_delay[j] +
2914290000Sglebius			    peer->filter_disp[j];
2915290000Sglebius		} else {
2916132454Sroberto			dst[i] = peer->filter_delay[j];
2917290000Sglebius		}
291882505Sroberto		ord[i] = j;
2919290000Sglebius		j = (j + 1) % NTP_SHIFT;
292082505Sroberto	}
292154359Sroberto
2922290000Sglebius	/*
2923290000Sglebius	 * If the clock has stabilized, sort the samples by distance.
292454359Sroberto	 */
2925290000Sglebius	if (freq_cnt == 0) {
2926182007Sroberto		for (i = 1; i < NTP_SHIFT; i++) {
2927182007Sroberto			for (j = 0; j < i; j++) {
2928290000Sglebius				if (dst[j] > dst[i]) {
2929182007Sroberto					k = ord[j];
2930182007Sroberto					ord[j] = ord[i];
2931182007Sroberto					ord[i] = k;
2932182007Sroberto					etemp = dst[j];
2933182007Sroberto					dst[j] = dst[i];
2934182007Sroberto					dst[i] = etemp;
2935182007Sroberto				}
293654359Sroberto			}
293754359Sroberto		}
293882505Sroberto	}
293982505Sroberto
294082505Sroberto	/*
294182505Sroberto	 * Copy the index list to the association structure so ntpq
2942290000Sglebius	 * can see it later. Prune the distance list to leave only
2943290000Sglebius	 * samples less than the maximum dispersion, which disfavors
2944290000Sglebius	 * uncorrelated samples older than the Allan intercept. To
2945290000Sglebius	 * further improve the jitter estimate, of the remainder leave
2946290000Sglebius	 * only samples less than the maximum distance, but keep at
2947290000Sglebius	 * least two samples for jitter calculation.
294882505Sroberto	 */
294982505Sroberto	m = 0;
295082505Sroberto	for (i = 0; i < NTP_SHIFT; i++) {
2951132454Sroberto		peer->filter_order[i] = (u_char) ord[i];
2952290000Sglebius		if (   dst[i] >= MAXDISPERSE
2953290000Sglebius		    || (m >= 2 && dst[i] >= sys_maxdist))
295482505Sroberto			continue;
295582505Sroberto		m++;
295682505Sroberto	}
2957290000Sglebius
295854359Sroberto	/*
2959182007Sroberto	 * Compute the dispersion and jitter. The dispersion is weighted
2960182007Sroberto	 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2961182007Sroberto	 * to 1.0. The jitter is the RMS differences relative to the
2962290000Sglebius	 * lowest delay sample.
296354359Sroberto	 */
2964182007Sroberto	peer->disp = peer->jitter = 0;
296582505Sroberto	k = ord[0];
296654359Sroberto	for (i = NTP_SHIFT - 1; i >= 0; i--) {
296782505Sroberto		j = ord[i];
296882505Sroberto		peer->disp = NTP_FWEIGHT * (peer->disp +
296982505Sroberto		    peer->filter_disp[j]);
297082505Sroberto		if (i < m)
2971182007Sroberto			peer->jitter += DIFF(peer->filter_offset[j],
297282505Sroberto			    peer->filter_offset[k]);
297354359Sroberto	}
297454359Sroberto
297554359Sroberto	/*
297682505Sroberto	 * If no acceptable samples remain in the shift register,
297782505Sroberto	 * quietly tiptoe home leaving only the dispersion. Otherwise,
2978182007Sroberto	 * save the offset, delay and jitter. Note the jitter must not
2979182007Sroberto	 * be less than the precision.
298082505Sroberto	 */
2981290000Sglebius	if (m == 0) {
2982290000Sglebius		clock_select();
298382505Sroberto		return;
2984290000Sglebius	}
2985132454Sroberto	etemp = fabs(peer->offset - peer->filter_offset[k]);
298682505Sroberto	peer->offset = peer->filter_offset[k];
298782505Sroberto	peer->delay = peer->filter_delay[k];
298882505Sroberto	if (m > 1)
2989182007Sroberto		peer->jitter /= m - 1;
2990182007Sroberto	peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
299182505Sroberto
299282505Sroberto	/*
2993290000Sglebius	 * If the the new sample and the current sample are both valid
2994290000Sglebius	 * and the difference between their offsets exceeds CLOCK_SGATE
2995290000Sglebius	 * (3) times the jitter and the interval between them is less
2996290000Sglebius	 * than twice the host poll interval, consider the new sample
2997290000Sglebius	 * a popcorn spike and ignore it.
299854359Sroberto	 */
2999290000Sglebius	if (   peer->disp < sys_maxdist
3000290000Sglebius	    && peer->filter_disp[k] < sys_maxdist
3001290000Sglebius	    && etemp > CLOCK_SGATE * peer->jitter
3002290000Sglebius	    && peer->filter_epoch[k] - peer->epoch
3003290000Sglebius	       < 2. * ULOGTOD(peer->hpoll)) {
3004290000Sglebius		snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3005290000Sglebius		report_event(PEVNT_POPCORN, peer, tbuf);
300654359Sroberto		return;
300754359Sroberto	}
300854359Sroberto
300954359Sroberto	/*
3010290000Sglebius	 * A new minimum sample is useful only if it is later than the
3011290000Sglebius	 * last one used. In this design the maximum lifetime of any
3012290000Sglebius	 * sample is not greater than eight times the poll interval, so
3013290000Sglebius	 * the maximum interval between minimum samples is eight
3014290000Sglebius	 * packets.
301554359Sroberto	 */
3016290000Sglebius	if (peer->filter_epoch[k] <= peer->epoch) {
3017293894Sglebius	DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3018293894Sglebius		    peer->filter_epoch[k]));
301954359Sroberto		return;
302054359Sroberto	}
3021290000Sglebius	peer->epoch = peer->filter_epoch[k];
302282505Sroberto
302382505Sroberto	/*
302482505Sroberto	 * The mitigated sample statistics are saved for later
3025290000Sglebius	 * processing. If not synchronized or not in a burst, tickle the
3026290000Sglebius	 * clock select algorithm.
302782505Sroberto	 */
3028290000Sglebius	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3029290000Sglebius	    peer->offset, peer->delay, peer->disp, peer->jitter);
3030293894Sglebius	DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
303182505Sroberto		    m, peer->offset, peer->delay, peer->disp,
3032293894Sglebius		    peer->jitter));
3033182007Sroberto	if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
3034182007Sroberto		clock_select();
303554359Sroberto}
303654359Sroberto
303754359Sroberto
303854359Sroberto/*
303954359Sroberto * clock_select - find the pick-of-the-litter clock
3040132454Sroberto *
3041290000Sglebius * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3042290000Sglebius * be enabled, even if declared falseticker, (2) only the prefer peer
3043290000Sglebius * can be selected as the system peer, (3) if the external source is
3044290000Sglebius * down, the system leap bits are set to 11 and the stratum set to
3045290000Sglebius * infinity.
304654359Sroberto */
304754359Srobertovoid
304854359Srobertoclock_select(void)
304954359Sroberto{
3050132454Sroberto	struct peer *peer;
3051132454Sroberto	int	i, j, k, n;
3052290000Sglebius	int	nlist, nl2;
3053290000Sglebius	int	allow;
3054290000Sglebius	int	speer;
3055182007Sroberto	double	d, e, f, g;
3056132454Sroberto	double	high, low;
3057290000Sglebius	double	speermet;
3058290000Sglebius	double	orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3059290000Sglebius	struct endpoint endp;
306054359Sroberto	struct peer *osys_peer;
3061290000Sglebius	struct peer *sys_prefer = NULL;	/* prefer peer */
3062290000Sglebius	struct peer *typesystem = NULL;
3063290000Sglebius	struct peer *typeorphan = NULL;
3064290000Sglebius#ifdef REFCLOCK
306582505Sroberto	struct peer *typeacts = NULL;
306682505Sroberto	struct peer *typelocal = NULL;
3067290000Sglebius	struct peer *typepps = NULL;
3068290000Sglebius#endif /* REFCLOCK */
306954359Sroberto	static struct endpoint *endpoint = NULL;
307082505Sroberto	static int *indx = NULL;
3071290000Sglebius	static peer_select *peers = NULL;
307254359Sroberto	static u_int endpoint_size = 0;
3073290000Sglebius	static u_int peers_size = 0;
307482505Sroberto	static u_int indx_size = 0;
3075290000Sglebius	size_t octets;
307654359Sroberto
307754359Sroberto	/*
307882505Sroberto	 * Initialize and create endpoint, index and peer lists big
307982505Sroberto	 * enough to handle all associations.
308054359Sroberto	 */
308182505Sroberto	osys_peer = sys_peer;
3082132454Sroberto	sys_survivors = 0;
3083132454Sroberto#ifdef LOCKCLOCK
3084290000Sglebius	set_sys_leap(LEAP_NOTINSYNC);
3085132454Sroberto	sys_stratum = STRATUM_UNSPEC;
3086132454Sroberto	memcpy(&sys_refid, "DOWN", 4);
3087132454Sroberto#endif /* LOCKCLOCK */
308854359Sroberto
308954359Sroberto	/*
3090290000Sglebius	 * Allocate dynamic space depending on the number of
3091290000Sglebius	 * associations.
3092290000Sglebius	 */
3093290000Sglebius	nlist = 1;
3094290000Sglebius	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3095290000Sglebius		nlist++;
3096290000Sglebius	endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3097290000Sglebius	peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3098290000Sglebius	indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3099290000Sglebius	octets = endpoint_size + peers_size + indx_size;
3100290000Sglebius	endpoint = erealloc(endpoint, octets);
3101290000Sglebius	peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3102290000Sglebius	indx = INC_ALIGNED_PTR(peers, peers_size);
3103290000Sglebius
3104290000Sglebius	/*
310582505Sroberto	 * Initially, we populate the island with all the rifraff peers
310682505Sroberto	 * that happen to be lying around. Those with seriously
310782505Sroberto	 * defective clocks are immediately booted off the island. Then,
310882505Sroberto	 * the falsetickers are culled and put to sea. The truechimers
310982505Sroberto	 * remaining are subject to repeated rounds where the most
311082505Sroberto	 * unpopular at each round is kicked off. When the population
3111132454Sroberto	 * has dwindled to sys_minclock, the survivors split a million
3112132454Sroberto	 * bucks and collectively crank the chimes.
311354359Sroberto	 */
3114290000Sglebius	nlist = nl2 = 0;	/* none yet */
3115290000Sglebius	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3116290000Sglebius		peer->new_status = CTL_PST_SEL_REJECT;
311754359Sroberto
3118290000Sglebius		/*
3119290000Sglebius		 * Leave the island immediately if the peer is
3120290000Sglebius		 * unfit to synchronize.
3121290000Sglebius		 */
3122310419Sdelphij		if (peer_unfit(peer)) {
3123290000Sglebius			continue;
3124310419Sdelphij		}
312582505Sroberto
3126290000Sglebius		/*
3127290000Sglebius		 * If this peer is an orphan parent, elect the
3128290000Sglebius		 * one with the lowest metric defined as the
3129290000Sglebius		 * IPv4 address or the first 64 bits of the
3130290000Sglebius		 * hashed IPv6 address.  To ensure convergence
3131290000Sglebius		 * on the same selected orphan, consider as
3132290000Sglebius		 * well that this system may have the lowest
3133290000Sglebius		 * metric and be the orphan parent.  If this
3134290000Sglebius		 * system wins, sys_peer will be NULL to trigger
3135290000Sglebius		 * orphan mode in timer().
3136290000Sglebius		 */
3137290000Sglebius		if (peer->stratum == sys_orphan) {
3138290000Sglebius			u_int32	localmet;
3139290000Sglebius			u_int32 peermet;
314054359Sroberto
3141290000Sglebius			if (peer->dstadr != NULL)
3142290000Sglebius				localmet = ntohl(peer->dstadr->addr_refid);
3143290000Sglebius			else
3144290000Sglebius				localmet = U_INT32_MAX;
3145290000Sglebius			peermet = ntohl(addr2refid(&peer->srcadr));
3146290000Sglebius			if (peermet < localmet && peermet < orphmet) {
3147290000Sglebius				typeorphan = peer;
3148290000Sglebius				orphmet = peermet;
314954359Sroberto			}
3150290000Sglebius			continue;
3151290000Sglebius		}
315254359Sroberto
3153290000Sglebius		/*
3154290000Sglebius		 * If this peer could have the orphan parent
3155290000Sglebius		 * as a synchronization ancestor, exclude it
3156290000Sglebius		 * from selection to avoid forming a
3157290000Sglebius		 * synchronization loop within the orphan mesh,
3158290000Sglebius		 * triggering stratum climb to infinity
3159290000Sglebius		 * instability.  Peers at stratum higher than
3160290000Sglebius		 * the orphan stratum could have the orphan
3161290000Sglebius		 * parent in ancestry so are excluded.
3162290000Sglebius		 * See http://bugs.ntp.org/2050
3163290000Sglebius		 */
3164310419Sdelphij		if (peer->stratum > sys_orphan) {
3165290000Sglebius			continue;
3166310419Sdelphij		}
3167290000Sglebius#ifdef REFCLOCK
3168290000Sglebius		/*
3169290000Sglebius		 * The following are special cases. We deal
3170290000Sglebius		 * with them later.
3171290000Sglebius		 */
3172290000Sglebius		if (!(peer->flags & FLAG_PREFER)) {
3173290000Sglebius			switch (peer->refclktype) {
3174290000Sglebius			case REFCLK_LOCALCLOCK:
3175290000Sglebius				if (   current_time > orphwait
3176290000Sglebius				    && typelocal == NULL)
3177290000Sglebius					typelocal = peer;
3178290000Sglebius				continue;
3179182007Sroberto
3180290000Sglebius			case REFCLK_ACTS:
3181290000Sglebius				if (   current_time > orphwait
3182290000Sglebius				    && typeacts == NULL)
3183290000Sglebius					typeacts = peer;
3184290000Sglebius				continue;
318554359Sroberto			}
3186290000Sglebius		}
3187290000Sglebius#endif /* REFCLOCK */
318854359Sroberto
3189290000Sglebius		/*
3190290000Sglebius		 * If we get this far, the peer can stay on the
3191290000Sglebius		 * island, but does not yet have the immunity
3192290000Sglebius		 * idol.
3193290000Sglebius		 */
3194290000Sglebius		peer->new_status = CTL_PST_SEL_SANE;
3195290000Sglebius		f = root_distance(peer);
3196290000Sglebius		peers[nlist].peer = peer;
3197290000Sglebius		peers[nlist].error = peer->jitter;
3198290000Sglebius		peers[nlist].synch = f;
3199290000Sglebius		nlist++;
3200182007Sroberto
3201290000Sglebius		/*
3202290000Sglebius		 * Insert each interval endpoint on the unsorted
3203290000Sglebius		 * endpoint[] list.
3204290000Sglebius		 */
3205290000Sglebius		e = peer->offset;
3206290000Sglebius		endpoint[nl2].type = -1;	/* lower end */
3207290000Sglebius		endpoint[nl2].val = e - f;
3208290000Sglebius		nl2++;
3209290000Sglebius		endpoint[nl2].type = 1;		/* upper end */
3210290000Sglebius		endpoint[nl2].val = e + f;
3211290000Sglebius		nl2++;
3212290000Sglebius	}
3213290000Sglebius	/*
3214290000Sglebius	 * Construct sorted indx[] of endpoint[] indexes ordered by
3215290000Sglebius	 * offset.
3216290000Sglebius	 */
3217290000Sglebius	for (i = 0; i < nl2; i++)
3218290000Sglebius		indx[i] = i;
3219290000Sglebius	for (i = 0; i < nl2; i++) {
3220290000Sglebius		endp = endpoint[indx[i]];
3221290000Sglebius		e = endp.val;
3222290000Sglebius		k = i;
3223290000Sglebius		for (j = i + 1; j < nl2; j++) {
3224290000Sglebius			endp = endpoint[indx[j]];
3225290000Sglebius			if (endp.val < e) {
3226290000Sglebius				e = endp.val;
3227290000Sglebius				k = j;
322854359Sroberto			}
322954359Sroberto		}
3230290000Sglebius		if (k != i) {
3231290000Sglebius			j = indx[k];
3232290000Sglebius			indx[k] = indx[i];
3233290000Sglebius			indx[i] = j;
3234290000Sglebius		}
323554359Sroberto	}
3236290000Sglebius	for (i = 0; i < nl2; i++)
3237290000Sglebius		DPRINTF(3, ("select: endpoint %2d %.6f\n",
3238290000Sglebius			endpoint[indx[i]].type, endpoint[indx[i]].val));
3239290000Sglebius
3240132454Sroberto	/*
3241132454Sroberto	 * This is the actual algorithm that cleaves the truechimers
3242132454Sroberto	 * from the falsetickers. The original algorithm was described
3243132454Sroberto	 * in Keith Marzullo's dissertation, but has been modified for
3244132454Sroberto	 * better accuracy.
3245132454Sroberto	 *
3246132454Sroberto	 * Briefly put, we first assume there are no falsetickers, then
3247132454Sroberto	 * scan the candidate list first from the low end upwards and
3248132454Sroberto	 * then from the high end downwards. The scans stop when the
3249132454Sroberto	 * number of intersections equals the number of candidates less
3250132454Sroberto	 * the number of falsetickers. If this doesn't happen for a
3251132454Sroberto	 * given number of falsetickers, we bump the number of
3252132454Sroberto	 * falsetickers and try again. If the number of falsetickers
3253132454Sroberto	 * becomes equal to or greater than half the number of
3254132454Sroberto	 * candidates, the Albanians have won the Byzantine wars and
3255132454Sroberto	 * correct synchronization is not possible.
3256132454Sroberto	 *
3257132454Sroberto	 * Here, nlist is the number of candidates and allow is the
3258182007Sroberto	 * number of falsetickers. Upon exit, the truechimers are the
3259290000Sglebius	 * survivors with offsets not less than low and not greater than
3260182007Sroberto	 * high. There may be none of them.
3261132454Sroberto	 */
3262132454Sroberto	low = 1e9;
3263132454Sroberto	high = -1e9;
3264132454Sroberto	for (allow = 0; 2 * allow < nlist; allow++) {
3265132454Sroberto
3266132454Sroberto		/*
3267290000Sglebius		 * Bound the interval (low, high) as the smallest
3268290000Sglebius		 * interval containing points from the most sources.
3269132454Sroberto		 */
3270132454Sroberto		n = 0;
3271290000Sglebius		for (i = 0; i < nl2; i++) {
3272132454Sroberto			low = endpoint[indx[i]].val;
3273132454Sroberto			n -= endpoint[indx[i]].type;
3274132454Sroberto			if (n >= nlist - allow)
327554359Sroberto				break;
327654359Sroberto		}
3277132454Sroberto		n = 0;
3278290000Sglebius		for (j = nl2 - 1; j >= 0; j--) {
3279132454Sroberto			high = endpoint[indx[j]].val;
328082505Sroberto			n += endpoint[indx[j]].type;
3281132454Sroberto			if (n >= nlist - allow)
328254359Sroberto				break;
328354359Sroberto		}
3284132454Sroberto
3285132454Sroberto		/*
3286132454Sroberto		 * If an interval containing truechimers is found, stop.
3287132454Sroberto		 * If not, increase the number of falsetickers and go
3288132454Sroberto		 * around again.
3289132454Sroberto		 */
3290132454Sroberto		if (high > low)
329154359Sroberto			break;
329254359Sroberto	}
329354359Sroberto
329454359Sroberto	/*
3295290000Sglebius	 * Clustering algorithm. Whittle candidate list of falsetickers,
3296290000Sglebius	 * who leave the island immediately. The TRUE peer is always a
3297182007Sroberto	 * truechimer. We must leave at least one peer to collect the
3298290000Sglebius	 * million bucks.
3299290000Sglebius	 *
3300290000Sglebius	 * We assert the correct time is contained in the interval, but
3301290000Sglebius	 * the best offset estimate for the interval might not be
3302290000Sglebius	 * contained in the interval. For this purpose, a truechimer is
3303290000Sglebius	 * defined as the midpoint of an interval that overlaps the
3304290000Sglebius	 * intersection interval.
3305182007Sroberto	 */
3306182007Sroberto	j = 0;
3307182007Sroberto	for (i = 0; i < nlist; i++) {
3308290000Sglebius		double	h;
3309290000Sglebius
3310290000Sglebius		peer = peers[i].peer;
3311290000Sglebius		h = peers[i].synch;
3312290000Sglebius		if ((   high <= low
3313290000Sglebius		     || peer->offset + h < low
3314290000Sglebius		     || peer->offset - h > high
3315290000Sglebius		    ) && !(peer->flags & FLAG_TRUE))
3316182007Sroberto			continue;
3317182007Sroberto
3318290000Sglebius#ifdef REFCLOCK
3319182007Sroberto		/*
3320290000Sglebius		 * Eligible PPS peers must survive the intersection
3321290000Sglebius		 * algorithm. Use the first one found, but don't
3322290000Sglebius		 * include any of them in the cluster population.
3323182007Sroberto		 */
3324290000Sglebius		if (peer->flags & FLAG_PPS) {
3325290000Sglebius			if (typepps == NULL)
3326290000Sglebius				typepps = peer;
3327290000Sglebius			if (!(peer->flags & FLAG_TSTAMP_PPS))
3328182007Sroberto				continue;
3329182007Sroberto		}
3330290000Sglebius#endif /* REFCLOCK */
3331182007Sroberto
3332290000Sglebius		if (j != i)
3333290000Sglebius			peers[j] = peers[i];
3334182007Sroberto		j++;
3335182007Sroberto	}
3336182007Sroberto	nlist = j;
3337182007Sroberto
3338182007Sroberto	/*
3339290000Sglebius	 * If no survivors remain at this point, check if the modem
3340290000Sglebius	 * driver, local driver or orphan parent in that order. If so,
3341290000Sglebius	 * nominate the first one found as the only survivor.
3342290000Sglebius	 * Otherwise, give up and leave the island to the rats.
334354359Sroberto	 */
3344182007Sroberto	if (nlist == 0) {
3345290000Sglebius		peers[0].error = 0;
3346290000Sglebius		peers[0].synch = sys_mindisp;
3347290000Sglebius#ifdef REFCLOCK
3348290000Sglebius		if (typeacts != NULL) {
3349290000Sglebius			peers[0].peer = typeacts;
335054359Sroberto			nlist = 1;
3351290000Sglebius		} else if (typelocal != NULL) {
3352290000Sglebius			peers[0].peer = typelocal;
335354359Sroberto			nlist = 1;
3354290000Sglebius		} else
3355290000Sglebius#endif /* REFCLOCK */
3356290000Sglebius		if (typeorphan != NULL) {
3357290000Sglebius			peers[0].peer = typeorphan;
3358290000Sglebius			nlist = 1;
335954359Sroberto		}
336054359Sroberto	}
336154359Sroberto
336254359Sroberto	/*
3363290000Sglebius	 * Mark the candidates at this point as truechimers.
3364132454Sroberto	 */
3365290000Sglebius	for (i = 0; i < nlist; i++) {
3366290000Sglebius		peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3367290000Sglebius		DPRINTF(2, ("select: survivor %s %f\n",
3368290000Sglebius			stoa(&peers[i].peer->srcadr), peers[i].synch));
3369290000Sglebius	}
3370132454Sroberto
337154359Sroberto	/*
3372290000Sglebius	 * Now, vote outliers off the island by select jitter weighted
3373182007Sroberto	 * by root distance. Continue voting as long as there are more
3374290000Sglebius	 * than sys_minclock survivors and the select jitter of the peer
3375290000Sglebius	 * with the worst metric is greater than the minimum peer
3376290000Sglebius	 * jitter. Stop if we are about to discard a TRUE or PREFER
3377290000Sglebius	 * peer, who of course have the immunity idol.
337854359Sroberto	 */
337954359Sroberto	while (1) {
338082505Sroberto		d = 1e9;
338182505Sroberto		e = -1e9;
3382290000Sglebius		g = 0;
338382505Sroberto		k = 0;
338482505Sroberto		for (i = 0; i < nlist; i++) {
3385290000Sglebius			if (peers[i].error < d)
3386290000Sglebius				d = peers[i].error;
3387290000Sglebius			peers[i].seljit = 0;
338882505Sroberto			if (nlist > 1) {
3389290000Sglebius				f = 0;
339082505Sroberto				for (j = 0; j < nlist; j++)
3391290000Sglebius					f += DIFF(peers[j].peer->offset,
3392290000Sglebius					    peers[i].peer->offset);
3393290000Sglebius				peers[i].seljit = SQRT(f / (nlist - 1));
339454359Sroberto			}
3395290000Sglebius			if (peers[i].seljit * peers[i].synch > e) {
3396290000Sglebius				g = peers[i].seljit;
3397290000Sglebius				e = peers[i].seljit * peers[i].synch;
339854359Sroberto				k = i;
339954359Sroberto			}
340054359Sroberto		}
3401290000Sglebius		g = max(g, LOGTOD(sys_precision));
3402290000Sglebius		if (   nlist <= max(1, sys_minclock)
3403290000Sglebius		    || g <= d
3404290000Sglebius		    || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3405132454Sroberto			break;
3406290000Sglebius
3407290000Sglebius		DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3408290000Sglebius			ntoa(&peers[k].peer->srcadr), g, d));
3409290000Sglebius		if (nlist > sys_maxclock)
3410290000Sglebius			peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3411290000Sglebius		for (j = k + 1; j < nlist; j++)
3412290000Sglebius			peers[j - 1] = peers[j];
341354359Sroberto		nlist--;
341454359Sroberto	}
341582505Sroberto
341682505Sroberto	/*
3417132454Sroberto	 * What remains is a list usually not greater than sys_minclock
3418290000Sglebius	 * peers. Note that unsynchronized peers cannot survive this
3419290000Sglebius	 * far.  Count and mark these survivors.
3420290000Sglebius	 *
3421290000Sglebius	 * While at it, count the number of leap warning bits found.
3422290000Sglebius	 * This will be used later to vote the system leap warning bit.
3423290000Sglebius	 * If a leap warning bit is found on a reference clock, the vote
3424290000Sglebius	 * is always won.
3425290000Sglebius	 *
3426290000Sglebius	 * Choose the system peer using a hybrid metric composed of the
3427290000Sglebius	 * selection jitter scaled by the root distance augmented by
3428290000Sglebius	 * stratum scaled by sys_mindisp (.001 by default). The goal of
3429290000Sglebius	 * the small stratum factor is to avoid clockhop between a
3430290000Sglebius	 * reference clock and a network peer which has a refclock and
3431290000Sglebius	 * is using an older ntpd, which does not floor sys_rootdisp at
3432290000Sglebius	 * sys_mindisp.
3433290000Sglebius	 *
3434290000Sglebius	 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3435290000Sglebius	 * in selecting the system peer, using a weight of 1 second of
3436290000Sglebius	 * additional root distance per stratum.  This heavy bias is no
3437290000Sglebius	 * longer appropriate, as the scaled root distance provides a
3438290000Sglebius	 * more rational metric carrying the cumulative error budget.
343954359Sroberto	 */
3440290000Sglebius	e = 1e9;
3441290000Sglebius	speer = 0;
3442290000Sglebius	leap_vote_ins = 0;
3443290000Sglebius	leap_vote_del = 0;
3444182007Sroberto	for (i = 0; i < nlist; i++) {
3445290000Sglebius		peer = peers[i].peer;
3446290000Sglebius		peer->unreach = 0;
3447290000Sglebius		peer->new_status = CTL_PST_SEL_SYNCCAND;
3448182007Sroberto		sys_survivors++;
3449290000Sglebius		if (peer->leap == LEAP_ADDSECOND) {
3450290000Sglebius			if (peer->flags & FLAG_REFCLOCK)
3451290000Sglebius				leap_vote_ins = nlist;
3452290000Sglebius			else if (leap_vote_ins < nlist)
3453290000Sglebius				leap_vote_ins++;
3454290000Sglebius		}
3455290000Sglebius		if (peer->leap == LEAP_DELSECOND) {
3456290000Sglebius			if (peer->flags & FLAG_REFCLOCK)
3457290000Sglebius				leap_vote_del = nlist;
3458290000Sglebius			else if (leap_vote_del < nlist)
3459290000Sglebius				leap_vote_del++;
3460290000Sglebius		}
3461132454Sroberto		if (peer->flags & FLAG_PREFER)
3462132454Sroberto			sys_prefer = peer;
3463290000Sglebius		speermet = peers[i].seljit * peers[i].synch +
3464290000Sglebius		    peer->stratum * sys_mindisp;
3465290000Sglebius		if (speermet < e) {
3466290000Sglebius			e = speermet;
3467290000Sglebius			speer = i;
3468290000Sglebius		}
346954359Sroberto	}
347054359Sroberto
347154359Sroberto	/*
3472290000Sglebius	 * Unless there are at least sys_misane survivors, leave the
3473290000Sglebius	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3474290000Sglebius	 * use the selected survivor speer. However, if the current
3475290000Sglebius	 * system peer is not speer, stay with the current system peer
3476290000Sglebius	 * as long as it doesn't get too old or too ugly.
3477132454Sroberto	 */
3478290000Sglebius	if (nlist > 0 && nlist >= sys_minsane) {
3479290000Sglebius		double	x;
3480290000Sglebius
3481290000Sglebius		typesystem = peers[speer].peer;
3482290000Sglebius		if (osys_peer == NULL || osys_peer == typesystem) {
3483290000Sglebius			sys_clockhop = 0;
3484290000Sglebius		} else if ((x = fabs(typesystem->offset -
3485290000Sglebius		    osys_peer->offset)) < sys_mindisp) {
3486290000Sglebius			if (sys_clockhop == 0)
3487290000Sglebius				sys_clockhop = sys_mindisp;
3488290000Sglebius			else
3489290000Sglebius				sys_clockhop *= .5;
3490290000Sglebius			DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3491290000Sglebius				j, x, sys_clockhop));
3492290000Sglebius			if (fabs(x) < sys_clockhop)
3493290000Sglebius				typesystem = osys_peer;
3494290000Sglebius			else
3495290000Sglebius				sys_clockhop = 0;
3496290000Sglebius		} else {
3497290000Sglebius			sys_clockhop = 0;
3498290000Sglebius		}
3499182007Sroberto	}
3500132454Sroberto
3501132454Sroberto	/*
3502290000Sglebius	 * Mitigation rules of the game. We have the pick of the
3503290000Sglebius	 * litter in typesystem if any survivors are left. If
3504290000Sglebius	 * there is a prefer peer, use its offset and jitter.
3505290000Sglebius	 * Otherwise, use the combined offset and jitter of all kitters.
350654359Sroberto	 */
3507290000Sglebius	if (typesystem != NULL) {
3508290000Sglebius		if (sys_prefer == NULL) {
3509290000Sglebius			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3510290000Sglebius			clock_combine(peers, sys_survivors, speer);
3511182007Sroberto		} else {
3512290000Sglebius			typesystem = sys_prefer;
3513290000Sglebius			sys_clockhop = 0;
3514290000Sglebius			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3515290000Sglebius			sys_offset = typesystem->offset;
3516290000Sglebius			sys_jitter = typesystem->jitter;
3517182007Sroberto		}
3518290000Sglebius		DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3519290000Sglebius			sys_offset, sys_jitter));
3520290000Sglebius	}
3521290000Sglebius#ifdef REFCLOCK
3522290000Sglebius	/*
3523290000Sglebius	 * If a PPS driver is lit and the combined offset is less than
3524290000Sglebius	 * 0.4 s, select the driver as the PPS peer and use its offset
3525290000Sglebius	 * and jitter. However, if this is the atom driver, use it only
3526290000Sglebius	 * if there is a prefer peer or there are no survivors and none
3527290000Sglebius	 * are required.
3528290000Sglebius	 */
3529290000Sglebius	if (   typepps != NULL
3530290000Sglebius	    && fabs(sys_offset) < 0.4
3531290000Sglebius	    && (   typepps->refclktype != REFCLK_ATOM_PPS
3532290000Sglebius		|| (   typepps->refclktype == REFCLK_ATOM_PPS
3533290000Sglebius		    && (   sys_prefer != NULL
3534290000Sglebius			|| (typesystem == NULL && sys_minsane == 0))))) {
3535290000Sglebius		typesystem = typepps;
3536290000Sglebius		sys_clockhop = 0;
3537290000Sglebius		typesystem->new_status = CTL_PST_SEL_PPS;
3538293894Sglebius		sys_offset = typesystem->offset;
3539290000Sglebius		sys_jitter = typesystem->jitter;
3540290000Sglebius		DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3541290000Sglebius			sys_offset, sys_jitter));
3542290000Sglebius	}
3543290000Sglebius#endif /* REFCLOCK */
3544182007Sroberto
3545290000Sglebius	/*
3546290000Sglebius	 * If there are no survivors at this point, there is no
3547290000Sglebius	 * system peer. If so and this is an old update, keep the
3548290000Sglebius	 * current statistics, but do not update the clock.
3549290000Sglebius	 */
3550290000Sglebius	if (typesystem == NULL) {
3551290000Sglebius		if (osys_peer != NULL) {
3552290000Sglebius			if (sys_orphwait > 0)
3553290000Sglebius				orphwait = current_time + sys_orphwait;
3554290000Sglebius			report_event(EVNT_NOPEER, NULL, NULL);
3555182007Sroberto		}
3556290000Sglebius		sys_peer = NULL;
3557290000Sglebius		for (peer = peer_list; peer != NULL; peer = peer->p_link)
3558290000Sglebius			peer->status = peer->new_status;
3559290000Sglebius		return;
356054359Sroberto	}
3561182007Sroberto
3562182007Sroberto	/*
3563290000Sglebius	 * Do not use old data, as this may mess up the clock discipline
3564290000Sglebius	 * stability.
3565182007Sroberto	 */
3566290000Sglebius	if (typesystem->epoch <= sys_epoch)
3567290000Sglebius		return;
3568132454Sroberto
3569290000Sglebius	/*
3570290000Sglebius	 * We have found the alpha male. Wind the clock.
3571290000Sglebius	 */
3572290000Sglebius	if (osys_peer != typesystem)
3573290000Sglebius		report_event(PEVNT_NEWPEER, typesystem, NULL);
3574290000Sglebius	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3575290000Sglebius		peer->status = peer->new_status;
3576290000Sglebius	clock_update(typesystem);
357754359Sroberto}
357854359Sroberto
3579182007Sroberto
3580182007Srobertostatic void
358154359Srobertoclock_combine(
3582290000Sglebius	peer_select *	peers,	/* survivor list */
3583290000Sglebius	int		npeers,	/* number of survivors */
3584290000Sglebius	int		syspeer	/* index of sys.peer */
358554359Sroberto	)
358654359Sroberto{
3587132454Sroberto	int	i;
3588182007Sroberto	double	x, y, z, w;
3589132454Sroberto
3590182007Sroberto	y = z = w = 0;
359154359Sroberto	for (i = 0; i < npeers; i++) {
3592290000Sglebius		x = 1. / peers[i].synch;
3593290000Sglebius		y += x;
3594290000Sglebius		z += x * peers[i].peer->offset;
3595290000Sglebius		w += x * DIFF(peers[i].peer->offset,
3596290000Sglebius		    peers[syspeer].peer->offset);
359754359Sroberto	}
3598182007Sroberto	sys_offset = z / y;
3599290000Sglebius	sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
360054359Sroberto}
360154359Sroberto
3602290000Sglebius
360354359Sroberto/*
360454359Sroberto * root_distance - compute synchronization distance from peer to root
360554359Sroberto */
360654359Srobertostatic double
360754359Srobertoroot_distance(
3608290000Sglebius	struct peer *peer	/* peer structure pointer */
360954359Sroberto	)
361054359Sroberto{
3611290000Sglebius	double	dtemp;
3612182007Sroberto
361382505Sroberto	/*
3614290000Sglebius	 * Root Distance (LAMBDA) is defined as:
3615310419Sdelphij	 * (delta + DELTA)/2 + epsilon + EPSILON + D
3616290000Sglebius	 *
3617290000Sglebius	 * where:
3618290000Sglebius	 *  delta   is the round-trip delay
3619290000Sglebius	 *  DELTA   is the root delay
3620310419Sdelphij	 *  epsilon is the peer dispersion
3621290000Sglebius	 *	    + (15 usec each second)
3622290000Sglebius	 *  EPSILON is the root dispersion
3623310419Sdelphij	 *  D       is sys_jitter
3624290000Sglebius	 *
3625290000Sglebius	 * NB: Think hard about why we are using these values, and what
3626290000Sglebius	 * the alternatives are, and the various pros/cons.
3627290000Sglebius	 *
3628290000Sglebius	 * DLM thinks these are probably the best choices from any of the
3629290000Sglebius	 * other worse choices.
3630290000Sglebius	 */
3631290000Sglebius	dtemp = (peer->delay + peer->rootdelay) / 2
3632310419Sdelphij		+ peer->disp
3633290000Sglebius		  + clock_phi * (current_time - peer->update)
3634290000Sglebius		+ peer->rootdisp
3635290000Sglebius		+ peer->jitter;
3636290000Sglebius	/*
363782505Sroberto	 * Careful squeak here. The value returned must be greater than
3638182007Sroberto	 * the minimum root dispersion in order to avoid clockhop with
3639290000Sglebius	 * highly precise reference clocks. Note that the root distance
3640290000Sglebius	 * cannot exceed the sys_maxdist, as this is the cutoff by the
3641290000Sglebius	 * selection algorithm.
364282505Sroberto	 */
3643290000Sglebius	if (dtemp < sys_mindisp)
3644290000Sglebius		dtemp = sys_mindisp;
3645290000Sglebius	return (dtemp);
364654359Sroberto}
364754359Sroberto
3648290000Sglebius
364954359Sroberto/*
365054359Sroberto * peer_xmit - send packet for persistent association.
365154359Sroberto */
365254359Srobertostatic void
365354359Srobertopeer_xmit(
365454359Sroberto	struct peer *peer	/* peer structure pointer */
365554359Sroberto	)
365654359Sroberto{
365782505Sroberto	struct pkt xpkt;	/* transmit packet */
3658290000Sglebius	size_t	sendlen, authlen;
3659182007Sroberto	keyid_t	xkeyid = 0;	/* transmit key ID */
3660290000Sglebius	l_fp	xmt_tx, xmt_ty;
366154359Sroberto
3662290000Sglebius	if (!peer->dstadr)	/* drop peers without interface */
3663182007Sroberto		return;
3664182007Sroberto
3665290000Sglebius	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3666290000Sglebius	    peer->hmode);
3667290000Sglebius	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
366854359Sroberto	xpkt.ppoll = peer->hpoll;
366954359Sroberto	xpkt.precision = sys_precision;
3670290000Sglebius	xpkt.refid = sys_refid;
3671290000Sglebius	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3672290000Sglebius	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
367354359Sroberto	HTONL_FP(&sys_reftime, &xpkt.reftime);
3674290000Sglebius	HTONL_FP(&peer->rec, &xpkt.org);
3675290000Sglebius	HTONL_FP(&peer->dst, &xpkt.rec);
367654359Sroberto
367754359Sroberto	/*
367882505Sroberto	 * If the received packet contains a MAC, the transmitted packet
367982505Sroberto	 * is authenticated and contains a MAC. If not, the transmitted
368082505Sroberto	 * packet is not authenticated.
368182505Sroberto	 *
3682182007Sroberto	 * It is most important when autokey is in use that the local
3683182007Sroberto	 * interface IP address be known before the first packet is
3684182007Sroberto	 * sent. Otherwise, it is not possible to compute a correct MAC
3685182007Sroberto	 * the recipient will accept. Thus, the I/O semantics have to do
3686182007Sroberto	 * a little more work. In particular, the wildcard interface
3687182007Sroberto	 * might not be usable.
368854359Sroberto	 */
368954359Sroberto	sendlen = LEN_PKT_NOMAC;
3690293894Sglebius	if (
3691290000Sglebius#ifdef AUTOKEY
3692293894Sglebius	    !(peer->flags & FLAG_SKEY) &&
3693290000Sglebius#endif	/* !AUTOKEY */
3694293894Sglebius	    peer->keyid == 0) {
3695290000Sglebius
3696290000Sglebius		/*
3697290000Sglebius		 * Transmit a-priori timestamps
3698290000Sglebius		 */
3699290000Sglebius		get_systime(&xmt_tx);
3700290000Sglebius		if (peer->flip == 0) {	/* basic mode */
3701290000Sglebius			peer->aorg = xmt_tx;
3702290000Sglebius			HTONL_FP(&xmt_tx, &xpkt.xmt);
3703290000Sglebius		} else {		/* interleaved modes */
3704290000Sglebius			if (peer->hmode == MODE_BROADCAST) { /* bcst */
3705290000Sglebius				HTONL_FP(&xmt_tx, &xpkt.xmt);
3706290000Sglebius				if (peer->flip > 0)
3707290000Sglebius					HTONL_FP(&peer->borg,
3708290000Sglebius					    &xpkt.org);
3709290000Sglebius				else
3710290000Sglebius					HTONL_FP(&peer->aorg,
3711290000Sglebius					    &xpkt.org);
3712290000Sglebius			} else {	/* symmetric */
3713290000Sglebius				if (peer->flip > 0)
3714290000Sglebius					HTONL_FP(&peer->borg,
3715290000Sglebius					    &xpkt.xmt);
3716290000Sglebius				else
3717290000Sglebius					HTONL_FP(&peer->aorg,
3718290000Sglebius					    &xpkt.xmt);
3719290000Sglebius			}
3720290000Sglebius		}
3721290000Sglebius		peer->t21_bytes = sendlen;
3722132454Sroberto		sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3723290000Sglebius		    &xpkt, sendlen);
372482505Sroberto		peer->sent++;
3725290000Sglebius		peer->throttle += (1 << peer->minpoll) - 2;
3726290000Sglebius
3727290000Sglebius		/*
3728290000Sglebius		 * Capture a-posteriori timestamps
3729290000Sglebius		 */
3730290000Sglebius		get_systime(&xmt_ty);
3731290000Sglebius		if (peer->flip != 0) {		/* interleaved modes */
3732290000Sglebius			if (peer->flip > 0)
3733290000Sglebius				peer->aorg = xmt_ty;
3734290000Sglebius			else
3735290000Sglebius				peer->borg = xmt_ty;
3736290000Sglebius			peer->flip = -peer->flip;
3737290000Sglebius		}
3738290000Sglebius		L_SUB(&xmt_ty, &xmt_tx);
3739290000Sglebius		LFPTOD(&xmt_ty, peer->xleave);
3740293894Sglebius		DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3741293894Sglebius			    current_time,
3742293894Sglebius			    peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3743293894Sglebius		            stoa(&peer->srcadr), peer->hmode, sendlen,
3744293894Sglebius			    xmt_tx.l_ui, xmt_tx.l_uf));
374582505Sroberto		return;
374682505Sroberto	}
374754359Sroberto
374882505Sroberto	/*
3749290000Sglebius	 * Authentication is enabled, so the transmitted packet must be
3750290000Sglebius	 * authenticated. If autokey is enabled, fuss with the various
3751290000Sglebius	 * modes; otherwise, symmetric key cryptography is used.
375282505Sroberto	 */
3753290000Sglebius#ifdef AUTOKEY
3754290000Sglebius	if (peer->flags & FLAG_SKEY) {
3755132454Sroberto		struct exten *exten;	/* extension field */
375682505Sroberto
375754359Sroberto		/*
375882505Sroberto		 * The Public Key Dance (PKD): Cryptographic credentials
375982505Sroberto		 * are contained in extension fields, each including a
376082505Sroberto		 * 4-octet length/code word followed by a 4-octet
376182505Sroberto		 * association ID and optional additional data. Optional
376282505Sroberto		 * data includes a 4-octet data length field followed by
376382505Sroberto		 * the data itself. Request messages are sent from a
376482505Sroberto		 * configured association; response messages can be sent
376582505Sroberto		 * from a configured association or can take the fast
376682505Sroberto		 * path without ever matching an association. Response
376782505Sroberto		 * messages have the same code as the request, but have
376882505Sroberto		 * a response bit and possibly an error bit set. In this
376982505Sroberto		 * implementation, a message may contain no more than
3770290000Sglebius		 * one command and one or more responses.
377182505Sroberto		 *
377282505Sroberto		 * Cryptographic session keys include both a public and
377382505Sroberto		 * a private componet. Request and response messages
377482505Sroberto		 * using extension fields are always sent with the
377582505Sroberto		 * private component set to zero. Packets without
377682505Sroberto		 * extension fields indlude the private component when
377782505Sroberto		 * the session key is generated.
377854359Sroberto		 */
377982505Sroberto		while (1) {
3780290000Sglebius
378154359Sroberto			/*
378282505Sroberto			 * Allocate and initialize a keylist if not
378382505Sroberto			 * already done. Then, use the list in inverse
378482505Sroberto			 * order, discarding keys once used. Keep the
378582505Sroberto			 * latest key around until the next one, so
378682505Sroberto			 * clients can use client/server packets to
378782505Sroberto			 * compute propagation delay.
378882505Sroberto			 *
378982505Sroberto			 * Note that once a key is used from the list,
379082505Sroberto			 * it is retained in the key cache until the
379182505Sroberto			 * next key is used. This is to allow a client
379282505Sroberto			 * to retrieve the encrypted session key
379382505Sroberto			 * identifier to verify authenticity.
379482505Sroberto			 *
379582505Sroberto			 * If for some reason a key is no longer in the
3796290000Sglebius			 * key cache, a birthday has happened or the key
3797290000Sglebius			 * has expired, so the pseudo-random sequence is
3798290000Sglebius			 * broken. In that case, purge the keylist and
3799290000Sglebius			 * regenerate it.
380054359Sroberto			 */
380182505Sroberto			if (peer->keynumber == 0)
380282505Sroberto				make_keylist(peer, peer->dstadr);
380382505Sroberto			else
380482505Sroberto				peer->keynumber--;
380582505Sroberto			xkeyid = peer->keylist[peer->keynumber];
380682505Sroberto			if (authistrusted(xkeyid))
380782505Sroberto				break;
380882505Sroberto			else
380982505Sroberto				key_expire(peer);
381054359Sroberto		}
381182505Sroberto		peer->keyid = xkeyid;
3812182007Sroberto		exten = NULL;
381382505Sroberto		switch (peer->hmode) {
381454359Sroberto
3815290000Sglebius		/*
3816290000Sglebius		 * In broadcast server mode the autokey values are
3817290000Sglebius		 * required by the broadcast clients. Push them when a
3818290000Sglebius		 * new keylist is generated; otherwise, push the
3819290000Sglebius		 * association message so the client can request them at
3820290000Sglebius		 * other times.
3821290000Sglebius		 */
382282505Sroberto		case MODE_BROADCAST:
382382505Sroberto			if (peer->flags & FLAG_ASSOC)
3824132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO |
3825290000Sglebius				    CRYPTO_RESP, peer->associd, NULL);
382682505Sroberto			else
3827132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC |
3828290000Sglebius				    CRYPTO_RESP, peer->associd, NULL);
382982505Sroberto			break;
383082505Sroberto
383154359Sroberto		/*
3832290000Sglebius		 * In symmetric modes the parameter, certificate,
3833290000Sglebius		 * identity, cookie and autokey exchanges are
3834290000Sglebius		 * required. The leapsecond exchange is optional. But, a
3835290000Sglebius		 * peer will not believe the other peer until the other
3836290000Sglebius		 * peer has synchronized, so the certificate exchange
3837290000Sglebius		 * might loop until then. If a peer finds a broken
3838290000Sglebius		 * autokey sequence, it uses the autokey exchange to
3839290000Sglebius		 * retrieve the autokey values. In any case, if a new
3840290000Sglebius		 * keylist is generated, the autokey values are pushed.
384154359Sroberto		 */
384282505Sroberto		case MODE_ACTIVE:
384382505Sroberto		case MODE_PASSIVE:
3844290000Sglebius
3845182007Sroberto			/*
3846290000Sglebius			 * Parameter, certificate and identity.
3847182007Sroberto			 */
384882505Sroberto			if (!peer->crypto)
3849132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC,
3850290000Sglebius				    peer->associd, hostval.ptr);
3851290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3852132454Sroberto				exten = crypto_args(peer, CRYPTO_CERT,
3853290000Sglebius				    peer->associd, peer->issuer);
3854182007Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3855182007Sroberto				exten = crypto_args(peer,
3856290000Sglebius				    crypto_ident(peer), peer->associd,
3857290000Sglebius				    NULL);
3858132454Sroberto
3859132454Sroberto			/*
3860290000Sglebius			 * Cookie and autokey. We request the cookie
3861290000Sglebius			 * only when the this peer and the other peer
3862290000Sglebius			 * are synchronized. But, this peer needs the
3863290000Sglebius			 * autokey values when the cookie is zero. Any
3864290000Sglebius			 * time we regenerate the key list, we offer the
3865290000Sglebius			 * autokey values without being asked. If for
3866290000Sglebius			 * some reason either peer finds a broken
3867290000Sglebius			 * autokey sequence, the autokey exchange is
3868290000Sglebius			 * used to retrieve the autokey values.
3869132454Sroberto			 */
3870290000Sglebius			else if (   sys_leap != LEAP_NOTINSYNC
3871290000Sglebius				 && peer->leap != LEAP_NOTINSYNC
3872290000Sglebius				 && !(peer->crypto & CRYPTO_FLAG_COOK))
3873132454Sroberto				exten = crypto_args(peer, CRYPTO_COOK,
3874290000Sglebius				    peer->associd, NULL);
3875132454Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3876132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO,
3877290000Sglebius				    peer->associd, NULL);
3878290000Sglebius			else if (   peer->flags & FLAG_ASSOC
3879290000Sglebius				 && peer->crypto & CRYPTO_FLAG_SIGN)
3880290000Sglebius				exten = crypto_args(peer, CRYPTO_AUTO |
3881290000Sglebius				    CRYPTO_RESP, peer->assoc, NULL);
3882132454Sroberto
3883132454Sroberto			/*
3884290000Sglebius			 * Wait for clock sync, then sign the
3885290000Sglebius			 * certificate and retrieve the leapsecond
3886290000Sglebius			 * values.
3887132454Sroberto			 */
3888290000Sglebius			else if (sys_leap == LEAP_NOTINSYNC)
3889290000Sglebius				break;
3890290000Sglebius
3891290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3892290000Sglebius				exten = crypto_args(peer, CRYPTO_SIGN,
3893290000Sglebius				    peer->associd, hostval.ptr);
3894290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3895290000Sglebius				exten = crypto_args(peer, CRYPTO_LEAP,
3896290000Sglebius				    peer->associd, NULL);
389782505Sroberto			break;
389882505Sroberto
389982505Sroberto		/*
3900290000Sglebius		 * In client mode the parameter, certificate, identity,
3901290000Sglebius		 * cookie and sign exchanges are required. The
3902290000Sglebius		 * leapsecond exchange is optional. If broadcast client
3903290000Sglebius		 * mode the same exchanges are required, except that the
3904290000Sglebius		 * autokey exchange is substitutes for the cookie
3905290000Sglebius		 * exchange, since the cookie is always zero. If the
3906290000Sglebius		 * broadcast client finds a broken autokey sequence, it
3907290000Sglebius		 * uses the autokey exchange to retrieve the autokey
3908290000Sglebius		 * values.
390982505Sroberto		 */
391082505Sroberto		case MODE_CLIENT:
3911290000Sglebius
3912182007Sroberto			/*
3913290000Sglebius			 * Parameter, certificate and identity.
3914182007Sroberto			 */
391582505Sroberto			if (!peer->crypto)
3916132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC,
3917290000Sglebius				    peer->associd, hostval.ptr);
3918290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3919132454Sroberto				exten = crypto_args(peer, CRYPTO_CERT,
3920290000Sglebius				    peer->associd, peer->issuer);
3921182007Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3922182007Sroberto				exten = crypto_args(peer,
3923290000Sglebius				    crypto_ident(peer), peer->associd,
3924290000Sglebius				    NULL);
3925132454Sroberto
3926132454Sroberto			/*
3927290000Sglebius			 * Cookie and autokey. These are requests, but
3928290000Sglebius			 * we use the peer association ID with autokey
3929290000Sglebius			 * rather than our own.
3930132454Sroberto			 */
3931290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3932132454Sroberto				exten = crypto_args(peer, CRYPTO_COOK,
3933290000Sglebius				    peer->associd, NULL);
3934290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3935132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO,
3936290000Sglebius				    peer->assoc, NULL);
3937132454Sroberto
3938132454Sroberto			/*
3939290000Sglebius			 * Wait for clock sync, then sign the
3940290000Sglebius			 * certificate and retrieve the leapsecond
3941290000Sglebius			 * values.
3942132454Sroberto			 */
3943290000Sglebius			else if (sys_leap == LEAP_NOTINSYNC)
3944290000Sglebius				break;
3945290000Sglebius
3946290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3947132454Sroberto				exten = crypto_args(peer, CRYPTO_SIGN,
3948290000Sglebius				    peer->associd, hostval.ptr);
3949290000Sglebius			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3950290000Sglebius				exten = crypto_args(peer, CRYPTO_LEAP,
3951290000Sglebius				    peer->associd, NULL);
395282505Sroberto			break;
395382505Sroberto		}
395482505Sroberto
395582505Sroberto		/*
3956290000Sglebius		 * Add a queued extension field if present. This is
3957290000Sglebius		 * always a request message, so the reply ID is already
3958290000Sglebius		 * in the message. If an error occurs, the error bit is
3959290000Sglebius		 * lit in the response.
3960182007Sroberto		 */
3961182007Sroberto		if (peer->cmmd != NULL) {
3962290000Sglebius			u_int32 temp32;
3963290000Sglebius
3964290000Sglebius			temp32 = CRYPTO_RESP;
3965290000Sglebius			peer->cmmd->opcode |= htonl(temp32);
3966290000Sglebius			sendlen += crypto_xmit(peer, &xpkt, NULL,
3967290000Sglebius			    sendlen, peer->cmmd, 0);
3968182007Sroberto			free(peer->cmmd);
3969182007Sroberto			peer->cmmd = NULL;
3970182007Sroberto		}
3971290000Sglebius
3972290000Sglebius		/*
3973290000Sglebius		 * Add an extension field created above. All but the
3974290000Sglebius		 * autokey response message are request messages.
3975290000Sglebius		 */
3976182007Sroberto		if (exten != NULL) {
3977290000Sglebius			if (exten->opcode != 0)
3978290000Sglebius				sendlen += crypto_xmit(peer, &xpkt,
3979290000Sglebius				    NULL, sendlen, exten, 0);
3980182007Sroberto			free(exten);
3981182007Sroberto		}
3982182007Sroberto
3983182007Sroberto		/*
3984290000Sglebius		 * Calculate the next session key. Since extension
3985290000Sglebius		 * fields are present, the cookie value is zero.
398682505Sroberto		 */
3987290000Sglebius		if (sendlen > (int)LEN_PKT_NOMAC) {
398882505Sroberto			session_key(&peer->dstadr->sin, &peer->srcadr,
398982505Sroberto			    xkeyid, 0, 2);
3990182007Sroberto		}
3991290000Sglebius	}
3992290000Sglebius#endif	/* AUTOKEY */
3993182007Sroberto
3994182007Sroberto	/*
3995290000Sglebius	 * Transmit a-priori timestamps
3996182007Sroberto	 */
3997290000Sglebius	get_systime(&xmt_tx);
3998290000Sglebius	if (peer->flip == 0) {		/* basic mode */
3999290000Sglebius		peer->aorg = xmt_tx;
4000290000Sglebius		HTONL_FP(&xmt_tx, &xpkt.xmt);
4001290000Sglebius	} else {			/* interleaved modes */
4002290000Sglebius		if (peer->hmode == MODE_BROADCAST) { /* bcst */
4003290000Sglebius			HTONL_FP(&xmt_tx, &xpkt.xmt);
4004290000Sglebius			if (peer->flip > 0)
4005290000Sglebius				HTONL_FP(&peer->borg, &xpkt.org);
4006290000Sglebius			else
4007290000Sglebius				HTONL_FP(&peer->aorg, &xpkt.org);
4008290000Sglebius		} else {		/* symmetric */
4009290000Sglebius			if (peer->flip > 0)
4010290000Sglebius				HTONL_FP(&peer->borg, &xpkt.xmt);
4011290000Sglebius			else
4012290000Sglebius				HTONL_FP(&peer->aorg, &xpkt.xmt);
4013290000Sglebius		}
4014290000Sglebius	}
401582505Sroberto	xkeyid = peer->keyid;
401682505Sroberto	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
401782505Sroberto	if (authlen == 0) {
4018290000Sglebius		report_event(PEVNT_AUTH, peer, "no key");
4019290000Sglebius		peer->flash |= TEST5;		/* auth error */
4020290000Sglebius		peer->badauth++;
402182505Sroberto		return;
402282505Sroberto	}
402382505Sroberto	sendlen += authlen;
4024290000Sglebius#ifdef AUTOKEY
402582505Sroberto	if (xkeyid > NTP_MAXKEY)
402682505Sroberto		authtrust(xkeyid, 0);
4027290000Sglebius#endif	/* AUTOKEY */
402882505Sroberto	if (sendlen > sizeof(xpkt)) {
4029293894Sglebius		msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4030132454Sroberto		exit (-1);
403182505Sroberto	}
4032290000Sglebius	peer->t21_bytes = sendlen;
4033132454Sroberto	sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
4034290000Sglebius	    sendlen);
4035290000Sglebius	peer->sent++;
4036290000Sglebius	peer->throttle += (1 << peer->minpoll) - 2;
403782505Sroberto
403882505Sroberto	/*
4039290000Sglebius	 * Capture a-posteriori timestamps
404082505Sroberto	 */
4041290000Sglebius	get_systime(&xmt_ty);
4042290000Sglebius	if (peer->flip != 0) {			/* interleaved modes */
4043290000Sglebius		if (peer->flip > 0)
4044290000Sglebius			peer->aorg = xmt_ty;
4045290000Sglebius		else
4046290000Sglebius			peer->borg = xmt_ty;
4047290000Sglebius		peer->flip = -peer->flip;
4048290000Sglebius	}
4049290000Sglebius	L_SUB(&xmt_ty, &xmt_tx);
4050290000Sglebius	LFPTOD(&xmt_ty, peer->xleave);
4051290000Sglebius#ifdef AUTOKEY
4052293894Sglebius	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4053290000Sglebius		    current_time, latoa(peer->dstadr),
4054290000Sglebius		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4055293894Sglebius		    peer->keynumber));
4056290000Sglebius#else	/* !AUTOKEY follows */
4057293894Sglebius	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %d\n",
4058290000Sglebius		    current_time, peer->dstadr ?
4059290000Sglebius		    ntoa(&peer->dstadr->sin) : "-",
4060293894Sglebius		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4061290000Sglebius#endif	/* !AUTOKEY */
4062293894Sglebius
4063293894Sglebius	return;
406454359Sroberto}
406554359Sroberto
406682505Sroberto
4067290000Sglebius#ifdef LEAP_SMEAR
4068290000Sglebius
4069290000Sglebiusstatic void
4070293894Sglebiusleap_smear_add_offs(
4071293894Sglebius	l_fp *t,
4072293894Sglebius	l_fp *t_recv
4073293894Sglebius	)
4074293894Sglebius{
4075293894Sglebius
4076290000Sglebius	L_ADD(t, &leap_smear.offset);
4077293894Sglebius
4078310419Sdelphij	/*
4079310419Sdelphij	** XXX: Should the smear be added to the root dispersion?
4080310419Sdelphij	*/
4081310419Sdelphij
4082293894Sglebius	return;
4083290000Sglebius}
4084290000Sglebius
4085290000Sglebius#endif  /* LEAP_SMEAR */
4086290000Sglebius
4087290000Sglebius
408854359Sroberto/*
408982505Sroberto * fast_xmit - Send packet for nonpersistent association. Note that
409082505Sroberto * neither the source or destination can be a broadcast address.
409154359Sroberto */
409254359Srobertostatic void
409354359Srobertofast_xmit(
409454359Sroberto	struct recvbuf *rbufp,	/* receive packet pointer */
4095290000Sglebius	int	xmode,		/* receive mode */
4096132454Sroberto	keyid_t	xkeyid,		/* transmit key ID */
4097290000Sglebius	int	flags		/* restrict mask */
409854359Sroberto	)
409954359Sroberto{
4100290000Sglebius	struct pkt xpkt;	/* transmit packet structure */
4101290000Sglebius	struct pkt *rpkt;	/* receive packet structure */
4102290000Sglebius	l_fp	xmt_tx, xmt_ty;
4103293894Sglebius	size_t	sendlen;
4104290000Sglebius#ifdef AUTOKEY
4105132454Sroberto	u_int32	temp32;
4106132454Sroberto#endif
410754359Sroberto
410854359Sroberto	/*
410982505Sroberto	 * Initialize transmit packet header fields from the receive
4110290000Sglebius	 * buffer provided. We leave the fields intact as received, but
4111290000Sglebius	 * set the peer poll at the maximum of the receive peer poll and
4112290000Sglebius	 * the system minimum poll (ntp_minpoll). This is for KoD rate
4113290000Sglebius	 * control and not strictly specification compliant, but doesn't
4114290000Sglebius	 * break anything.
4115182007Sroberto	 *
4116290000Sglebius	 * If the gazinta was from a multicast address, the gazoutta
4117290000Sglebius	 * must go out another way.
411854359Sroberto	 */
411954359Sroberto	rpkt = &rbufp->recv_pkt;
4120182007Sroberto	if (rbufp->dstadr->flags & INT_MCASTOPEN)
412182505Sroberto		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
412282505Sroberto
412382505Sroberto	/*
4124290000Sglebius	 * If this is a kiss-o'-death (KoD) packet, show leap
4125182007Sroberto	 * unsynchronized, stratum zero, reference ID the four-character
4126290000Sglebius	 * kiss code and system root delay. Note we don't reveal the
4127290000Sglebius	 * local time, so these packets can't be used for
4128290000Sglebius	 * synchronization.
4129182007Sroberto	 */
4130290000Sglebius	if (flags & RES_KOD) {
4131290000Sglebius		sys_kodsent++;
4132132454Sroberto		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4133132454Sroberto		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4134290000Sglebius		xpkt.stratum = STRATUM_PKT_UNSPEC;
4135290000Sglebius		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4136290000Sglebius		xpkt.precision = rpkt->precision;
4137182007Sroberto		memcpy(&xpkt.refid, "RATE", 4);
4138290000Sglebius		xpkt.rootdelay = rpkt->rootdelay;
4139290000Sglebius		xpkt.rootdisp = rpkt->rootdisp;
4140290000Sglebius		xpkt.reftime = rpkt->reftime;
4141290000Sglebius		xpkt.org = rpkt->xmt;
4142290000Sglebius		xpkt.rec = rpkt->xmt;
4143290000Sglebius		xpkt.xmt = rpkt->xmt;
4144182007Sroberto
4145182007Sroberto	/*
4146182007Sroberto	 * This is a normal packet. Use the system variables.
4147182007Sroberto	 */
4148290000Sglebius	} else {
4149290000Sglebius#ifdef LEAP_SMEAR
4150290000Sglebius		/*
4151290000Sglebius		 * Make copies of the variables which can be affected by smearing.
4152290000Sglebius		 */
4153290000Sglebius		l_fp this_ref_time;
4154290000Sglebius		l_fp this_recv_time;
4155290000Sglebius#endif
4156290000Sglebius
4157290000Sglebius		/*
4158290000Sglebius		 * If we are inside the leap smear interval we add the current smear offset to
4159290000Sglebius		 * the packet receive time, to the packet transmit time, and eventually to the
4160290000Sglebius		 * reftime to make sure the reftime isn't later than the transmit/receive times.
4161290000Sglebius		 */
4162290000Sglebius		xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
416382505Sroberto		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4164290000Sglebius
416582505Sroberto		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4166290000Sglebius		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4167290000Sglebius		xpkt.precision = sys_precision;
416882505Sroberto		xpkt.refid = sys_refid;
4169182007Sroberto		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4170290000Sglebius		xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4171182007Sroberto
4172290000Sglebius#ifdef LEAP_SMEAR
4173290000Sglebius		this_ref_time = sys_reftime;
4174290000Sglebius		if (leap_smear.in_progress) {
4175290000Sglebius			leap_smear_add_offs(&this_ref_time, NULL);
4176290000Sglebius			xpkt.refid = convertLFPToRefID(leap_smear.offset);
4177290000Sglebius			DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4178290000Sglebius				ntohl(xpkt.refid),
4179290000Sglebius				lfptoa(&leap_smear.offset, 8)
4180290000Sglebius				));
4181290000Sglebius		}
4182290000Sglebius		HTONL_FP(&this_ref_time, &xpkt.reftime);
4183290000Sglebius#else
4184290000Sglebius		HTONL_FP(&sys_reftime, &xpkt.reftime);
4185290000Sglebius#endif
4186182007Sroberto
4187290000Sglebius		xpkt.org = rpkt->xmt;
4188290000Sglebius
4189290000Sglebius#ifdef LEAP_SMEAR
4190290000Sglebius		this_recv_time = rbufp->recv_time;
4191290000Sglebius		if (leap_smear.in_progress)
4192290000Sglebius			leap_smear_add_offs(&this_recv_time, NULL);
4193290000Sglebius		HTONL_FP(&this_recv_time, &xpkt.rec);
4194290000Sglebius#else
4195290000Sglebius		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4196290000Sglebius#endif
4197290000Sglebius
4198290000Sglebius		get_systime(&xmt_tx);
4199290000Sglebius#ifdef LEAP_SMEAR
4200290000Sglebius		if (leap_smear.in_progress)
4201290000Sglebius			leap_smear_add_offs(&xmt_tx, &this_recv_time);
4202290000Sglebius#endif
4203290000Sglebius		HTONL_FP(&xmt_tx, &xpkt.xmt);
420482505Sroberto	}
420582505Sroberto
4206290000Sglebius#ifdef HAVE_NTP_SIGND
4207290000Sglebius	if (flags & RES_MSSNTP) {
4208290000Sglebius		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4209290000Sglebius		return;
4210290000Sglebius	}
4211290000Sglebius#endif /* HAVE_NTP_SIGND */
4212290000Sglebius
421382505Sroberto	/*
421482505Sroberto	 * If the received packet contains a MAC, the transmitted packet
421582505Sroberto	 * is authenticated and contains a MAC. If not, the transmitted
421682505Sroberto	 * packet is not authenticated.
421782505Sroberto	 */
421854359Sroberto	sendlen = LEN_PKT_NOMAC;
421982505Sroberto	if (rbufp->recv_length == sendlen) {
422082505Sroberto		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
422156749Sroberto		    sendlen);
4222293894Sglebius		DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4223132454Sroberto			    current_time, stoa(&rbufp->dstadr->sin),
4224293894Sglebius			    stoa(&rbufp->recv_srcadr), xmode,
4225293894Sglebius			    (u_long)sendlen));
422682505Sroberto		return;
422782505Sroberto	}
422854359Sroberto
422982505Sroberto	/*
423082505Sroberto	 * The received packet contains a MAC, so the transmitted packet
4231182007Sroberto	 * must be authenticated. For symmetric key cryptography, use
4232182007Sroberto	 * the predefined and trusted symmetric keys to generate the
4233182007Sroberto	 * cryptosum. For autokey cryptography, use the server private
4234182007Sroberto	 * value to generate the cookie, which is unique for every
4235182007Sroberto	 * source-destination-key ID combination.
423682505Sroberto	 */
4237290000Sglebius#ifdef AUTOKEY
423882505Sroberto	if (xkeyid > NTP_MAXKEY) {
423982505Sroberto		keyid_t cookie;
424082505Sroberto
424154359Sroberto		/*
424282505Sroberto		 * The only way to get here is a reply to a legitimate
424382505Sroberto		 * client request message, so the mode must be
424482505Sroberto		 * MODE_SERVER. If an extension field is present, there
424582505Sroberto		 * can be only one and that must be a command. Do what
424682505Sroberto		 * needs, but with private value of zero so the poor
424782505Sroberto		 * jerk can decode it. If no extension field is present,
424882505Sroberto		 * use the cookie to generate the session key.
424954359Sroberto		 */
425082505Sroberto		cookie = session_key(&rbufp->recv_srcadr,
425182505Sroberto		    &rbufp->dstadr->sin, 0, sys_private, 0);
4252293894Sglebius		if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
425382505Sroberto			session_key(&rbufp->dstadr->sin,
425482505Sroberto			    &rbufp->recv_srcadr, xkeyid, 0, 2);
4255132454Sroberto			temp32 = CRYPTO_RESP;
4256132454Sroberto			rpkt->exten[0] |= htonl(temp32);
4257290000Sglebius			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4258290000Sglebius			    sendlen, (struct exten *)rpkt->exten,
4259290000Sglebius			    cookie);
426082505Sroberto		} else {
426182505Sroberto			session_key(&rbufp->dstadr->sin,
426282505Sroberto			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
426382505Sroberto		}
426482505Sroberto	}
4265290000Sglebius#endif	/* AUTOKEY */
4266290000Sglebius	get_systime(&xmt_tx);
4267290000Sglebius	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4268290000Sglebius#ifdef AUTOKEY
426982505Sroberto	if (xkeyid > NTP_MAXKEY)
427082505Sroberto		authtrust(xkeyid, 0);
4271290000Sglebius#endif	/* AUTOKEY */
427282505Sroberto	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4273290000Sglebius	get_systime(&xmt_ty);
4274290000Sglebius	L_SUB(&xmt_ty, &xmt_tx);
4275290000Sglebius	sys_authdelay = xmt_ty;
4276293894Sglebius	DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
427782505Sroberto		    current_time, ntoa(&rbufp->dstadr->sin),
4278293894Sglebius		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4279293894Sglebius		    (u_long)sendlen));
428054359Sroberto}
428154359Sroberto
428282505Sroberto
428354359Sroberto/*
4284290000Sglebius * pool_xmit - resolve hostname or send unicast solicitation for pool.
4285290000Sglebius */
4286290000Sglebiusstatic void
4287290000Sglebiuspool_xmit(
4288290000Sglebius	struct peer *pool	/* pool solicitor association */
4289290000Sglebius	)
4290290000Sglebius{
4291290000Sglebius#ifdef WORKER
4292290000Sglebius	struct pkt		xpkt;	/* transmit packet structure */
4293290000Sglebius	struct addrinfo		hints;
4294290000Sglebius	int			rc;
4295290000Sglebius	struct interface *	lcladr;
4296290000Sglebius	sockaddr_u *		rmtadr;
4297290000Sglebius	int			restrict_mask;
4298290000Sglebius	struct peer *		p;
4299290000Sglebius	l_fp			xmt_tx;
4300290000Sglebius
4301290000Sglebius	if (NULL == pool->ai) {
4302290000Sglebius		if (pool->addrs != NULL) {
4303290000Sglebius			/* free() is used with copy_addrinfo_list() */
4304290000Sglebius			free(pool->addrs);
4305290000Sglebius			pool->addrs = NULL;
4306290000Sglebius		}
4307290000Sglebius		ZERO(hints);
4308290000Sglebius		hints.ai_family = AF(&pool->srcadr);
4309290000Sglebius		hints.ai_socktype = SOCK_DGRAM;
4310290000Sglebius		hints.ai_protocol = IPPROTO_UDP;
4311290000Sglebius		/* ignore getaddrinfo_sometime() errors, we will retry */
4312290000Sglebius		rc = getaddrinfo_sometime(
4313290000Sglebius			pool->hostname,
4314290000Sglebius			"ntp",
4315290000Sglebius			&hints,
4316290000Sglebius			0,			/* no retry */
4317290000Sglebius			&pool_name_resolved,
4318290000Sglebius			(void *)(intptr_t)pool->associd);
4319290000Sglebius		if (!rc)
4320290000Sglebius			DPRINTF(1, ("pool DNS lookup %s started\n",
4321290000Sglebius				pool->hostname));
4322290000Sglebius		else
4323290000Sglebius			msyslog(LOG_ERR,
4324290000Sglebius				"unable to start pool DNS %s: %m",
4325290000Sglebius				pool->hostname);
4326290000Sglebius		return;
4327290000Sglebius	}
4328290000Sglebius
4329290000Sglebius	do {
4330290000Sglebius		/* copy_addrinfo_list ai_addr points to a sockaddr_u */
4331290000Sglebius		rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4332290000Sglebius		pool->ai = pool->ai->ai_next;
4333290000Sglebius		p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
4334290000Sglebius	} while (p != NULL && pool->ai != NULL);
4335290000Sglebius	if (p != NULL)
4336290000Sglebius		return;	/* out of addresses, re-query DNS next poll */
4337290000Sglebius	restrict_mask = restrictions(rmtadr);
4338290000Sglebius	if (RES_FLAGS & restrict_mask)
4339290000Sglebius		restrict_source(rmtadr, 0,
4340290000Sglebius				current_time + POOL_SOLICIT_WINDOW + 1);
4341290000Sglebius	lcladr = findinterface(rmtadr);
4342290000Sglebius	memset(&xpkt, 0, sizeof(xpkt));
4343290000Sglebius	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4344290000Sglebius					 MODE_CLIENT);
4345290000Sglebius	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4346290000Sglebius	xpkt.ppoll = pool->hpoll;
4347290000Sglebius	xpkt.precision = sys_precision;
4348290000Sglebius	xpkt.refid = sys_refid;
4349290000Sglebius	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4350290000Sglebius	xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4351290000Sglebius	HTONL_FP(&sys_reftime, &xpkt.reftime);
4352290000Sglebius	get_systime(&xmt_tx);
4353290000Sglebius	pool->aorg = xmt_tx;
4354290000Sglebius	HTONL_FP(&xmt_tx, &xpkt.xmt);
4355290000Sglebius	sendpkt(rmtadr, lcladr,	sys_ttl[pool->ttl], &xpkt,
4356290000Sglebius		LEN_PKT_NOMAC);
4357290000Sglebius	pool->sent++;
4358290000Sglebius	pool->throttle += (1 << pool->minpoll) - 2;
4359293894Sglebius	DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4360293894Sglebius		    current_time, latoa(lcladr), stoa(rmtadr)));
4361290000Sglebius	msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4362290000Sglebius#endif	/* WORKER */
4363290000Sglebius}
4364290000Sglebius
4365290000Sglebius
4366290000Sglebius#ifdef AUTOKEY
4367290000Sglebius	/*
4368290000Sglebius	 * group_test - test if this is the same group
4369290000Sglebius	 *
4370290000Sglebius	 * host		assoc		return		action
4371290000Sglebius	 * none		none		0		mobilize *
4372290000Sglebius	 * none		group		0		mobilize *
4373290000Sglebius	 * group	none		0		mobilize *
4374290000Sglebius	 * group	group		1		mobilize
4375290000Sglebius	 * group	different	1		ignore
4376290000Sglebius	 * * ignore if notrust
4377290000Sglebius	 */
4378293894Sglebiusint
4379293894Sglebiusgroup_test(
4380290000Sglebius	char	*grp,
4381290000Sglebius	char	*ident
4382290000Sglebius	)
4383290000Sglebius{
4384290000Sglebius	if (grp == NULL)
4385290000Sglebius		return (0);
4386290000Sglebius
4387290000Sglebius	if (strcmp(grp, sys_groupname) == 0)
4388290000Sglebius		return (0);
4389290000Sglebius
4390290000Sglebius	if (ident == NULL)
4391290000Sglebius		return (1);
4392290000Sglebius
4393290000Sglebius	if (strcmp(grp, ident) == 0)
4394290000Sglebius		return (0);
4395290000Sglebius
4396290000Sglebius	return (1);
4397290000Sglebius}
4398290000Sglebius#endif /* AUTOKEY */
4399290000Sglebius
4400298770Sdelphij
4401290000Sglebius#ifdef WORKER
4402290000Sglebiusvoid
4403290000Sglebiuspool_name_resolved(
4404290000Sglebius	int			rescode,
4405290000Sglebius	int			gai_errno,
4406290000Sglebius	void *			context,
4407290000Sglebius	const char *		name,
4408290000Sglebius	const char *		service,
4409290000Sglebius	const struct addrinfo *	hints,
4410290000Sglebius	const struct addrinfo *	res
4411290000Sglebius	)
4412290000Sglebius{
4413290000Sglebius	struct peer *	pool;	/* pool solicitor association */
4414290000Sglebius	associd_t	assoc;
4415290000Sglebius
4416290000Sglebius	if (rescode) {
4417290000Sglebius		msyslog(LOG_ERR,
4418290000Sglebius			"error resolving pool %s: %s (%d)",
4419290000Sglebius			name, gai_strerror(rescode), rescode);
4420290000Sglebius		return;
4421290000Sglebius	}
4422290000Sglebius
4423290000Sglebius	assoc = (associd_t)(intptr_t)context;
4424290000Sglebius	pool = findpeerbyassoc(assoc);
4425290000Sglebius	if (NULL == pool) {
4426290000Sglebius		msyslog(LOG_ERR,
4427290000Sglebius			"Could not find assoc %u for pool DNS %s",
4428290000Sglebius			assoc, name);
4429290000Sglebius		return;
4430290000Sglebius	}
4431290000Sglebius	DPRINTF(1, ("pool DNS %s completed\n", name));
4432290000Sglebius	pool->addrs = copy_addrinfo_list(res);
4433290000Sglebius	pool->ai = pool->addrs;
4434290000Sglebius	pool_xmit(pool);
4435290000Sglebius
4436290000Sglebius}
4437290000Sglebius#endif	/* WORKER */
4438290000Sglebius
4439290000Sglebius
4440290000Sglebius#ifdef AUTOKEY
4441290000Sglebius/*
444282505Sroberto * key_expire - purge the key list
444354359Sroberto */
444482505Srobertovoid
444582505Srobertokey_expire(
444682505Sroberto	struct peer *peer	/* peer structure pointer */
444754359Sroberto	)
444854359Sroberto{
444954359Sroberto	int i;
445054359Sroberto
4451132454Sroberto	if (peer->keylist != NULL) {
445282505Sroberto		for (i = 0; i <= peer->keynumber; i++)
445382505Sroberto			authtrust(peer->keylist[i], 0);
445482505Sroberto		free(peer->keylist);
445582505Sroberto		peer->keylist = NULL;
445654359Sroberto	}
4457132454Sroberto	value_free(&peer->sndval);
4458132454Sroberto	peer->keynumber = 0;
4459290000Sglebius	peer->flags &= ~FLAG_ASSOC;
4460293894Sglebius	DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4461293894Sglebius		    peer->associd));
446254359Sroberto}
4463290000Sglebius#endif	/* AUTOKEY */
446454359Sroberto
4465132454Sroberto
446654359Sroberto/*
4467290000Sglebius * local_refid(peer) - check peer refid to avoid selecting peers
4468290000Sglebius *		       currently synced to this ntpd.
4469290000Sglebius */
4470290000Sglebiusstatic int
4471290000Sglebiuslocal_refid(
4472290000Sglebius	struct peer *	p
4473290000Sglebius	)
4474290000Sglebius{
4475290000Sglebius	endpt *	unicast_ep;
4476290000Sglebius
4477290000Sglebius	if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4478290000Sglebius		unicast_ep = p->dstadr;
4479290000Sglebius	else
4480290000Sglebius		unicast_ep = findinterface(&p->srcadr);
4481290000Sglebius
4482290000Sglebius	if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4483290000Sglebius		return TRUE;
4484290000Sglebius	else
4485290000Sglebius		return FALSE;
4486290000Sglebius}
4487290000Sglebius
4488290000Sglebius
4489290000Sglebius/*
4490132454Sroberto * Determine if the peer is unfit for synchronization
4491132454Sroberto *
4492132454Sroberto * A peer is unfit for synchronization if
4493182007Sroberto * > TEST10 bad leap or stratum below floor or at or above ceiling
4494290000Sglebius * > TEST11 root distance exceeded for remote peer
4495182007Sroberto * > TEST12 a direct or indirect synchronization loop would form
4496182007Sroberto * > TEST13 unreachable or noselect
4497132454Sroberto */
4498182007Srobertoint				/* FALSE if fit, TRUE if unfit */
4499132454Srobertopeer_unfit(
4500132454Sroberto	struct peer *peer	/* peer structure pointer */
4501132454Sroberto	)
4502132454Sroberto{
4503182007Sroberto	int	rval = 0;
4504182007Sroberto
4505182007Sroberto	/*
4506182007Sroberto	 * A stratum error occurs if (1) the server has never been
4507182007Sroberto	 * synchronized, (2) the server stratum is below the floor or
4508290000Sglebius	 * greater than or equal to the ceiling.
4509182007Sroberto	 */
4510290000Sglebius	if (   peer->leap == LEAP_NOTINSYNC
4511290000Sglebius	    || peer->stratum < sys_floor
4512310419Sdelphij	    || peer->stratum >= sys_ceiling) {
4513290000Sglebius		rval |= TEST10;		/* bad synch or stratum */
4514310419Sdelphij	}
4515182007Sroberto
4516182007Sroberto	/*
4517290000Sglebius	 * A distance error for a remote peer occurs if the root
4518290000Sglebius	 * distance is greater than or equal to the distance threshold
4519290000Sglebius	 * plus the increment due to one host poll interval.
4520182007Sroberto	 */
4521290000Sglebius	if (   !(peer->flags & FLAG_REFCLOCK)
4522290000Sglebius	    && root_distance(peer) >= sys_maxdist
4523310419Sdelphij				      + clock_phi * ULOGTOD(peer->hpoll)) {
4524182007Sroberto		rval |= TEST11;		/* distance exceeded */
4525310419Sdelphij	}
4526182007Sroberto
4527182007Sroberto	/*
4528182007Sroberto	 * A loop error occurs if the remote peer is synchronized to the
4529290000Sglebius	 * local peer or if the remote peer is synchronized to the same
4530290000Sglebius	 * server as the local peer but only if the remote peer is
4531290000Sglebius	 * neither a reference clock nor an orphan.
4532182007Sroberto	 */
4533310419Sdelphij	if (peer->stratum > 1 && local_refid(peer)) {
4534290000Sglebius		rval |= TEST12;		/* synchronization loop */
4535310419Sdelphij	}
4536182007Sroberto
4537182007Sroberto	/*
4538182007Sroberto	 * An unreachable error occurs if the server is unreachable or
4539182007Sroberto	 * the noselect bit is set.
4540182007Sroberto	 */
4541310419Sdelphij	if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
4542182007Sroberto		rval |= TEST13;		/* unreachable */
4543310419Sdelphij	}
4544182007Sroberto
4545182007Sroberto	peer->flash &= ~PEER_TEST_MASK;
4546182007Sroberto	peer->flash |= rval;
4547182007Sroberto	return (rval);
4548132454Sroberto}
4549132454Sroberto
4550132454Sroberto
4551132454Sroberto/*
455254359Sroberto * Find the precision of this particular machine
455354359Sroberto */
4554290000Sglebius#define MINSTEP		20e-9	/* minimum clock increment (s) */
4555290000Sglebius#define MAXSTEP		1	/* maximum clock increment (s) */
4556290000Sglebius#define MINCHANGES	12	/* minimum number of step samples */
4557290000Sglebius#define MAXLOOPS	((int)(1. / MINSTEP))	/* avoid infinite loop */
455854359Sroberto
455954359Sroberto/*
4560290000Sglebius * This routine measures the system precision defined as the minimum of
4561290000Sglebius * a sequence of differences between successive readings of the system
4562290000Sglebius * clock. However, if a difference is less than MINSTEP, the clock has
4563290000Sglebius * been read more than once during a clock tick and the difference is
4564290000Sglebius * ignored. We set MINSTEP greater than zero in case something happens
4565290000Sglebius * like a cache miss, and to tolerate underlying system clocks which
4566290000Sglebius * ensure each reading is strictly greater than prior readings while
4567290000Sglebius * using an underlying stepping (not interpolated) clock.
4568132454Sroberto *
4569290000Sglebius * sys_tick and sys_precision represent the time to read the clock for
4570290000Sglebius * systems with high-precision clocks, and the tick interval or step
4571290000Sglebius * size for lower-precision stepping clocks.
4572290000Sglebius *
4573290000Sglebius * This routine also measures the time to read the clock on stepping
4574290000Sglebius * system clocks by counting the number of readings between changes of
4575290000Sglebius * the underlying clock.  With either type of clock, the minimum time
4576290000Sglebius * to read the clock is saved as sys_fuzz, and used to ensure the
4577290000Sglebius * get_systime() readings always increase and are fuzzed below sys_fuzz.
457854359Sroberto */
4579290000Sglebiusvoid
4580290000Sglebiusmeasure_precision(void)
458154359Sroberto{
4582290000Sglebius	/*
4583290000Sglebius	 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4584290000Sglebius	 * is effectively disabled.  trunc_os_clock is FALSE to disable
4585290000Sglebius	 * get_ostime() simulation of a low-precision system clock.
4586290000Sglebius	 */
4587290000Sglebius	set_sys_fuzz(0.);
4588290000Sglebius	trunc_os_clock = FALSE;
4589290000Sglebius	measured_tick = measure_tick_fuzz();
4590290000Sglebius	set_sys_tick_precision(measured_tick);
4591290000Sglebius	msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4592290000Sglebius		sys_tick * 1e6, sys_precision);
4593290000Sglebius	if (sys_fuzz < sys_tick) {
4594290000Sglebius		msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4595290000Sglebius			sys_fuzz * 1e6);
4596290000Sglebius	}
4597290000Sglebius}
4598290000Sglebius
4599290000Sglebius
4600290000Sglebius/*
4601290000Sglebius * measure_tick_fuzz()
4602290000Sglebius *
4603290000Sglebius * measures the minimum time to read the clock (stored in sys_fuzz)
4604290000Sglebius * and returns the tick, the larger of the minimum increment observed
4605290000Sglebius * between successive clock readings and the time to read the clock.
4606290000Sglebius */
4607290000Sglebiusdouble
4608290000Sglebiusmeasure_tick_fuzz(void)
4609290000Sglebius{
4610290000Sglebius	l_fp	minstep;	/* MINSTEP as l_fp */
4611132454Sroberto	l_fp	val;		/* current seconds fraction */
4612132454Sroberto	l_fp	last;		/* last seconds fraction */
4613290000Sglebius	l_fp	ldiff;		/* val - last */
4614132454Sroberto	double	tick;		/* computed tick value */
4615290000Sglebius	double	diff;
4616290000Sglebius	long	repeats;
4617290000Sglebius	long	max_repeats;
4618290000Sglebius	int	changes;
4619132454Sroberto	int	i;		/* log2 precision */
462054359Sroberto
4621290000Sglebius	tick = MAXSTEP;
4622290000Sglebius	max_repeats = 0;
4623290000Sglebius	repeats = 0;
4624290000Sglebius	changes = 0;
4625290000Sglebius	DTOLFP(MINSTEP, &minstep);
4626132454Sroberto	get_systime(&last);
4627290000Sglebius	for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4628132454Sroberto		get_systime(&val);
4629290000Sglebius		ldiff = val;
4630290000Sglebius		L_SUB(&ldiff, &last);
4631132454Sroberto		last = val;
4632290000Sglebius		if (L_ISGT(&ldiff, &minstep)) {
4633290000Sglebius			max_repeats = max(repeats, max_repeats);
4634290000Sglebius			repeats = 0;
4635290000Sglebius			changes++;
4636290000Sglebius			LFPTOD(&ldiff, diff);
4637290000Sglebius			tick = min(diff, tick);
4638290000Sglebius		} else {
4639290000Sglebius			repeats++;
4640290000Sglebius		}
464154359Sroberto	}
4642290000Sglebius	if (changes < MINCHANGES) {
4643290000Sglebius		msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4644290000Sglebius		exit(1);
4645290000Sglebius	}
4646132454Sroberto
4647290000Sglebius	if (0 == max_repeats) {
4648290000Sglebius		set_sys_fuzz(tick);
4649290000Sglebius	} else {
4650290000Sglebius		set_sys_fuzz(tick / max_repeats);
4651290000Sglebius	}
4652290000Sglebius
4653290000Sglebius	return tick;
4654290000Sglebius}
4655290000Sglebius
4656290000Sglebius
4657290000Sglebiusvoid
4658290000Sglebiusset_sys_tick_precision(
4659290000Sglebius	double tick
4660290000Sglebius	)
4661290000Sglebius{
4662290000Sglebius	int i;
4663290000Sglebius
4664290000Sglebius	if (tick > 1.) {
4665290000Sglebius		msyslog(LOG_ERR,
4666290000Sglebius			"unsupported tick %.3f > 1s ignored", tick);
4667290000Sglebius		return;
4668290000Sglebius	}
4669290000Sglebius	if (tick < measured_tick) {
4670290000Sglebius		msyslog(LOG_ERR,
4671290000Sglebius			"proto: tick %.3f less than measured tick %.3f, ignored",
4672290000Sglebius			tick, measured_tick);
4673290000Sglebius		return;
4674290000Sglebius	} else if (tick > measured_tick) {
4675290000Sglebius		trunc_os_clock = TRUE;
4676290000Sglebius		msyslog(LOG_NOTICE,
4677290000Sglebius			"proto: truncating system clock to multiples of %.9f",
4678290000Sglebius			tick);
4679290000Sglebius	}
4680290000Sglebius	sys_tick = tick;
4681290000Sglebius
4682132454Sroberto	/*
4683132454Sroberto	 * Find the nearest power of two.
4684132454Sroberto	 */
4685290000Sglebius	for (i = 0; tick <= 1; i--)
4686132454Sroberto		tick *= 2;
4687290000Sglebius	if (tick - 1 > 1 - tick / 2)
4688290000Sglebius		i++;
468954359Sroberto
4690290000Sglebius	sys_precision = (s_char)i;
4691132454Sroberto}
4692132454Sroberto
4693132454Sroberto
4694132454Sroberto/*
469554359Sroberto * init_proto - initialize the protocol module's data
469654359Sroberto */
469754359Srobertovoid
469854359Srobertoinit_proto(void)
469954359Sroberto{
4700132454Sroberto	l_fp	dummy;
4701132454Sroberto	int	i;
470254359Sroberto
470354359Sroberto	/*
470454359Sroberto	 * Fill in the sys_* stuff.  Default is don't listen to
4705290000Sglebius	 * broadcasting, require authentication.
470654359Sroberto	 */
4707290000Sglebius	set_sys_leap(LEAP_NOTINSYNC);
470854359Sroberto	sys_stratum = STRATUM_UNSPEC;
4709132454Sroberto	memcpy(&sys_refid, "INIT", 4);
4710290000Sglebius	sys_peer = NULL;
471154359Sroberto	sys_rootdelay = 0;
4712290000Sglebius	sys_rootdisp = 0;
471354359Sroberto	L_CLR(&sys_reftime);
4714290000Sglebius	sys_jitter = 0;
4715290000Sglebius	measure_precision();
4716290000Sglebius	get_systime(&dummy);
471782505Sroberto	sys_survivors = 0;
4718132454Sroberto	sys_manycastserver = 0;
471954359Sroberto	sys_bclient = 0;
4720298770Sdelphij	sys_bdelay = BDELAY_DEFAULT;	/*[Bug 3031] delay cutoff */
472154359Sroberto	sys_authenticate = 1;
4722290000Sglebius	sys_stattime = current_time;
4723290000Sglebius	orphwait = current_time + sys_orphwait;
4724132454Sroberto	proto_clr_stats();
4725132454Sroberto	for (i = 0; i < MAX_TTL; i++) {
4726132454Sroberto		sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4727132454Sroberto		sys_ttlmax = i;
4728132454Sroberto	}
4729290000Sglebius	hardpps_enable = 0;
473054359Sroberto	stats_control = 1;
473154359Sroberto}
473254359Sroberto
473354359Sroberto
473454359Sroberto/*
473554359Sroberto * proto_config - configure the protocol module
473654359Sroberto */
473754359Srobertovoid
473854359Srobertoproto_config(
4739132454Sroberto	int	item,
4740132454Sroberto	u_long	value,
4741132454Sroberto	double	dvalue,
4742290000Sglebius	sockaddr_u *svalue
474354359Sroberto	)
474454359Sroberto{
474554359Sroberto	/*
474654359Sroberto	 * Figure out what he wants to change, then do it
474754359Sroberto	 */
4748290000Sglebius	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4749290000Sglebius		    item, value, dvalue));
4750290000Sglebius
475154359Sroberto	switch (item) {
4752132454Sroberto
4753132454Sroberto	/*
4754290000Sglebius	 * enable and disable commands - arguments are Boolean.
4755132454Sroberto	 */
4756290000Sglebius	case PROTO_AUTHENTICATE: /* authentication (auth) */
4757290000Sglebius		sys_authenticate = value;
475854359Sroberto		break;
475954359Sroberto
4760290000Sglebius	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4761290000Sglebius		sys_bclient = (int)value;
4762290000Sglebius		if (sys_bclient == 0)
4763290000Sglebius			io_unsetbclient();
4764290000Sglebius		else
4765290000Sglebius			io_setbclient();
476654359Sroberto		break;
476754359Sroberto
4768290000Sglebius#ifdef REFCLOCK
4769290000Sglebius	case PROTO_CAL:		/* refclock calibrate (calibrate) */
4770290000Sglebius		cal_enable = value;
4771290000Sglebius		break;
4772290000Sglebius#endif /* REFCLOCK */
4773290000Sglebius
4774290000Sglebius	case PROTO_KERNEL:	/* kernel discipline (kernel) */
4775290000Sglebius		select_loop(value);
4776290000Sglebius		break;
4777290000Sglebius
4778290000Sglebius	case PROTO_MONITOR:	/* monitoring (monitor) */
477954359Sroberto		if (value)
478054359Sroberto			mon_start(MON_ON);
4781290000Sglebius		else {
478254359Sroberto			mon_stop(MON_ON);
4783290000Sglebius			if (mon_enabled)
4784290000Sglebius				msyslog(LOG_WARNING,
4785290000Sglebius					"restrict: 'monitor' cannot be disabled while 'limited' is enabled");
4786290000Sglebius		}
478754359Sroberto		break;
478854359Sroberto
4789290000Sglebius	case PROTO_NTP:		/* NTP discipline (ntp) */
4790290000Sglebius		ntp_enable = value;
479154359Sroberto		break;
479254359Sroberto
4793290000Sglebius	case PROTO_MODE7:	/* mode7 management (ntpdc) */
4794290000Sglebius		ntp_mode7 = value;
479554359Sroberto		break;
479654359Sroberto
4797290000Sglebius	case PROTO_PPS:		/* PPS discipline (pps) */
4798290000Sglebius		hardpps_enable = value;
4799182007Sroberto		break;
4800182007Sroberto
4801290000Sglebius	case PROTO_FILEGEN:	/* statistics (stats) */
4802290000Sglebius		stats_control = value;
480354359Sroberto		break;
480454359Sroberto
4805132454Sroberto	/*
4806290000Sglebius	 * tos command - arguments are double, sometimes cast to int
4807132454Sroberto	 */
4808310419Sdelphij
4809310419Sdelphij	case PROTO_BCPOLLBSTEP:	/* Broadcast Poll Backstep gate (bcpollbstep) */
4810310419Sdelphij		sys_bcpollbstep = (u_char)dvalue;
4811310419Sdelphij		break;
4812310419Sdelphij
4813290000Sglebius	case PROTO_BEACON:	/* manycast beacon (beacon) */
4814290000Sglebius		sys_beacon = (int)dvalue;
481554359Sroberto		break;
481654359Sroberto
4817290000Sglebius	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
4818298770Sdelphij		sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
481954359Sroberto		break;
482054359Sroberto
4821290000Sglebius	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
4822290000Sglebius		sys_ceiling = (int)dvalue;
4823132454Sroberto		break;
4824132454Sroberto
4825290000Sglebius	case PROTO_COHORT:	/* cohort switch (cohort) */
4826290000Sglebius		sys_cohort = (int)dvalue;
482754359Sroberto		break;
482854359Sroberto
4829290000Sglebius	case PROTO_FLOOR:	/* stratum floor (floor) */
4830290000Sglebius		sys_floor = (int)dvalue;
483182505Sroberto		break;
483282505Sroberto
4833290000Sglebius	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
4834182007Sroberto		sys_maxclock = (int)dvalue;
4835132454Sroberto		break;
4836132454Sroberto
4837290000Sglebius	case PROTO_MAXDIST:	/* select threshold (maxdist) */
4838290000Sglebius		sys_maxdist = dvalue;
4839132454Sroberto		break;
4840132454Sroberto
4841290000Sglebius	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
4842290000Sglebius		break;		/* NOT USED */
4843132454Sroberto
4844290000Sglebius	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
4845290000Sglebius		sys_minclock = (int)dvalue;
4846132454Sroberto		break;
4847132454Sroberto
4848290000Sglebius	case PROTO_MINDISP:	/* minimum distance (mindist) */
4849290000Sglebius		sys_mindisp = dvalue;
4850182007Sroberto		break;
4851182007Sroberto
4852290000Sglebius	case PROTO_MINSANE:	/* minimum survivors (minsane) */
4853290000Sglebius		sys_minsane = (int)dvalue;
4854132454Sroberto		break;
4855182007Sroberto
4856290000Sglebius	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
4857290000Sglebius		sys_orphan = (int)dvalue;
4858182007Sroberto		break;
4859182007Sroberto
4860290000Sglebius	case PROTO_ORPHWAIT:	/* orphan wait (orphwait) */
4861290000Sglebius		orphwait -= sys_orphwait;
4862290000Sglebius		sys_orphwait = (int)dvalue;
4863290000Sglebius		orphwait += sys_orphwait;
4864182007Sroberto		break;
4865182007Sroberto
4866182007Sroberto	/*
4867290000Sglebius	 * Miscellaneous commands
4868182007Sroberto	 */
4869290000Sglebius	case PROTO_MULTICAST_ADD: /* add group address */
4870290000Sglebius		if (svalue != NULL)
4871290000Sglebius			io_multicast_add(svalue);
4872290000Sglebius		sys_bclient = 1;
4873182007Sroberto		break;
4874182007Sroberto
4875290000Sglebius	case PROTO_MULTICAST_DEL: /* delete group address */
4876290000Sglebius		if (svalue != NULL)
4877290000Sglebius			io_multicast_del(svalue);
4878132454Sroberto		break;
4879132454Sroberto
4880294904Sdelphij	/*
4881301301Sdelphij	 * Peer_clear Early policy choices
4882301301Sdelphij	 */
4883301301Sdelphij
4884301301Sdelphij	case PROTO_PCEDIGEST:	/* Digest */
4885301301Sdelphij		peer_clear_digest_early = value;
4886301301Sdelphij		break;
4887301301Sdelphij
4888301301Sdelphij	/*
4889294904Sdelphij	 * Unpeer Early policy choices
4890294904Sdelphij	 */
4891294904Sdelphij
4892294904Sdelphij	case PROTO_UECRYPTO:	/* Crypto */
4893294904Sdelphij		unpeer_crypto_early = value;
4894294904Sdelphij		break;
4895294904Sdelphij
4896294904Sdelphij	case PROTO_UECRYPTONAK:	/* Crypto_NAK */
4897294904Sdelphij		unpeer_crypto_nak_early = value;
4898294904Sdelphij		break;
4899294904Sdelphij
4900294904Sdelphij	case PROTO_UEDIGEST:	/* Digest */
4901294904Sdelphij		unpeer_digest_early = value;
4902294904Sdelphij		break;
4903294904Sdelphij
490456749Sroberto	default:
4905290000Sglebius		msyslog(LOG_NOTICE,
4906290000Sglebius		    "proto: unsupported option %d", item);
490754359Sroberto	}
490854359Sroberto}
490954359Sroberto
491054359Sroberto
491154359Sroberto/*
491254359Sroberto * proto_clr_stats - clear protocol stat counters
491354359Sroberto */
491454359Srobertovoid
491554359Srobertoproto_clr_stats(void)
491654359Sroberto{
4917132454Sroberto	sys_stattime = current_time;
4918132454Sroberto	sys_received = 0;
4919132454Sroberto	sys_processed = 0;
4920290000Sglebius	sys_newversion = 0;
4921290000Sglebius	sys_oldversion = 0;
4922290000Sglebius	sys_declined = 0;
4923132454Sroberto	sys_restricted = 0;
492454359Sroberto	sys_badlength = 0;
492554359Sroberto	sys_badauth = 0;
492654359Sroberto	sys_limitrejected = 0;
4927290000Sglebius	sys_kodsent = 0;
492854359Sroberto}
4929