ntp_proto.c revision 309007
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"
16280849Scy#include "ntp_leapsec.h"
17285169Scy#include "refidsmear.h"
18293423Sdelphij#include "lib_strbuf.h"
1954359Sroberto
2082505Sroberto#include <stdio.h>
21280849Scy#ifdef HAVE_LIBSCF_H
22280849Scy#include <libscf.h>
2354359Sroberto#endif
24280849Scy#ifdef HAVE_UNISTD_H
25280849Scy#include <unistd.h>
2654359Sroberto#endif
2754359Sroberto
28298695Sdelphij/* [Bug 3031] define automatic broadcastdelay cutoff preset */
29298695Sdelphij#ifndef BDELAY_DEFAULT
30298695Sdelphij# define BDELAY_DEFAULT (-0.050)
31298695Sdelphij#endif
32298695Sdelphij
3354359Sroberto/*
34182007Sroberto * This macro defines the authentication state. If x is 1 authentication
35182007Sroberto * is required; othewise it is optional.
36182007Sroberto */
37289764Sglebius#define	AUTH(x, y)	((x) ? (y) == AUTH_OK \
38289764Sglebius			     : (y) == AUTH_OK || (y) == AUTH_NONE)
39182007Sroberto
40280849Scy#define	AUTH_NONE	0	/* authentication not required */
41280849Scy#define	AUTH_OK		1	/* authentication OK */
42280849Scy#define	AUTH_ERROR	2	/* authentication error */
43280849Scy#define	AUTH_CRYPTO	3	/* crypto_NAK */
44280849Scy
45182007Sroberto/*
46289764Sglebius * Set up Kiss Code values
47289764Sglebius */
48289764Sglebius
49289764Sglebiusenum kiss_codes {
50289764Sglebius	NOKISS,				/* No Kiss Code */
51289764Sglebius	RATEKISS,			/* Rate limit Kiss Code */
52289764Sglebius	DENYKISS,			/* Deny Kiss */
53289764Sglebius	RSTRKISS,			/* Restricted Kiss */
54289764Sglebius	XKISS,				/* Experimental Kiss */
55289764Sglebius	UNKNOWNKISS			/* Unknown Kiss Code */
56289764Sglebius};
57289764Sglebius
58298695Sdelphijenum nak_error_codes {
59298695Sdelphij	NONAK,				/* No NAK seen */
60298695Sdelphij	INVALIDNAK,			/* NAK cannot be used */
61298695Sdelphij	VALIDNAK			/* NAK is valid */
62298695Sdelphij};
63298695Sdelphij
64289764Sglebius/*
65280849Scy * traffic shaping parameters
6654359Sroberto */
67280849Scy#define	NTP_IBURST	6	/* packets in iburst */
68280849Scy#define	RESP_DELAY	1	/* refclock burst delay (s) */
69280849Scy
70280849Scy/*
71280849Scy * pool soliciting restriction duration (s)
72280849Scy */
73280849Scy#define	POOL_SOLICIT_WINDOW	8
74280849Scy
75280849Scy/*
76280849Scy * peer_select groups statistics for a peer used by clock_select() and
77280849Scy * clock_cluster().
78280849Scy */
79280849Scytypedef struct peer_select_tag {
80280849Scy	struct peer *	peer;
81280849Scy	double		synch;	/* sync distance */
82280849Scy	double		error;	/* jitter */
83280849Scy	double		seljit;	/* selection jitter */
84280849Scy} peer_select;
85280849Scy
86280849Scy/*
87280849Scy * System variables are declared here. Unless specified otherwise, all
88280849Scy * times are in seconds.
89280849Scy */
90285169Scyu_char	sys_leap;		/* system leap indicator, use set_sys_leap() to change this */
91285169Scyu_char	xmt_leap;		/* leap indicator sent in client requests, set up by set_sys_leap() */
92280849Scyu_char	sys_stratum;		/* system stratum */
93182007Srobertos_char	sys_precision;		/* local clock precision (log2 s) */
9482505Srobertodouble	sys_rootdelay;		/* roundtrip delay to primary source */
95280849Scydouble	sys_rootdisp;		/* dispersion to primary source */
96280849Scyu_int32 sys_refid;		/* reference id (network byte order) */
97280849Scyl_fp	sys_reftime;		/* last update time */
98280849Scystruct	peer *sys_peer;		/* current peer */
9954359Sroberto
100285169Scy#ifdef LEAP_SMEAR
101285169Scystruct leap_smear_info leap_smear;
102285169Scy#endif
103285169Scyint leap_sec_in_progress;
104285169Scy
10554359Sroberto/*
106280849Scy * Rate controls. Leaky buckets are used to throttle the packet
107280849Scy * transmission rates in order to protect busy servers such as at NIST
108280849Scy * and USNO. There is a counter for each association and another for KoD
109280849Scy * packets. The association counter decrements each second, but not
110280849Scy * below zero. Each time a packet is sent the counter is incremented by
111280849Scy * a configurable value representing the average interval between
112280849Scy * packets. A packet is delayed as long as the counter is greater than
113280849Scy * zero. Note this does not affect the time value computations.
11454359Sroberto */
115280849Scy/*
116280849Scy * Nonspecified system state variables
117280849Scy */
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 */
122280849Scydouble	sys_offset;	/* current local clock offset */
123280849Scydouble	sys_mindisp = MINDISPERSE; /* minimum distance (s) */
124280849Scydouble	sys_maxdist = MAXDISTANCE; /* selection threshold */
125280849Scydouble	sys_jitter;		/* system jitter */
126280849Scyu_long	sys_epoch;		/* last clock update time */
127280849Scystatic	double sys_clockhop;	/* clockhop threshold */
128280849Scystatic int leap_vote_ins;	/* leap consensus for insert */
129280849Scystatic 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 */
132280849Scyint	ntp_mode7;		/* respond to ntpdc (mode7) */
13382505Srobertoint	peer_ntpdate;		/* active peers in ntpdate mode */
134132454Srobertoint	sys_survivors;		/* truest of the truechimers */
135280849Scychar	*sys_ident = NULL;	/* identity scheme */
13654359Sroberto
13754359Sroberto/*
138132454Sroberto * TOS and multicast mapping stuff
139132454Sroberto */
140182007Srobertoint	sys_floor = 0;		/* cluster stratum floor */
141309007Sdelphiju_char	sys_bcpollbstep = 0;	/* Broadcast Poll backstep gate */
142280849Scyint	sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
143132454Srobertoint	sys_minsane = 1;	/* minimum candidates */
144280849Scyint	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 */
148280849Scyint	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/*
154280849Scy * Statistics counters - first the good, then the bad
15554359Sroberto */
156280849Scyu_long	sys_stattime;		/* elapsed time */
157132454Srobertou_long	sys_received;		/* packets received */
158280849Scyu_long	sys_processed;		/* packets for this host */
159280849Scyu_long	sys_newversion;		/* current version */
160280849Scyu_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 */
164280849Scyu_long	sys_declined;		/* declined */
165132454Srobertou_long	sys_limitrejected;	/* rate exceeded */
166280849Scyu_long	sys_kodsent;		/* KoD sent */
16754359Sroberto
168294554Sdelphij/*
169301247Sdelphij * Mechanism knobs: how soon do we peer_clear() or unpeer()?
170294554Sdelphij *
171294554Sdelphij * The default way is "on-receipt".  If this was a packet from a
172294554Sdelphij * well-behaved source, on-receipt will offer the fastest recovery.
173294554Sdelphij * If this was from a DoS attack, the default way makes it easier
174294554Sdelphij * for a bad-guy to DoS us.  So look and see what bites you harder
175294554Sdelphij * and choose according to your environment.
176294554Sdelphij */
177301247Sdelphijint peer_clear_digest_early	= 1;	/* bad digest (TEST5) and Autokey */
178294554Sdelphijint unpeer_crypto_early		= 1;	/* bad crypto (TEST9) */
179294554Sdelphijint unpeer_crypto_nak_early	= 1;	/* crypto_NAK (TEST5) */
180294554Sdelphijint unpeer_digest_early		= 1;	/* bad digest (TEST5) */
181294554Sdelphij
182298695Sdelphijint dynamic_interleave = DYNAMIC_INTERLEAVE;	/* Bug 2978 mitigation */
183298695Sdelphij
184298695Sdelphijint kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
185298695Sdelphijenum nak_error_codes valid_NAK(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
186280849Scystatic	double	root_distance	(struct peer *);
187280849Scystatic	void	clock_combine	(peer_select *, int, int);
188280849Scystatic	void	peer_xmit	(struct peer *);
189280849Scystatic	void	fast_xmit	(struct recvbuf *, int, keyid_t, int);
190280849Scystatic	void	pool_xmit	(struct peer *);
191280849Scystatic	void	clock_update	(struct peer *);
192280849Scystatic	void	measure_precision(void);
193280849Scystatic	double	measure_tick_fuzz(void);
194280849Scystatic	int	local_refid	(struct peer *);
195280849Scystatic	int	peer_unfit	(struct peer *);
196280849Scy#ifdef AUTOKEY
197280849Scystatic	int	group_test	(char *, char *);
198280849Scy#endif /* AUTOKEY */
199280849Scy#ifdef WORKER
200280849Scyvoid	pool_name_resolved	(int, int, void *, const char *,
201280849Scy				 const char *, const struct addrinfo *,
202280849Scy				 const struct addrinfo *);
203280849Scy#endif /* WORKER */
20454359Sroberto
205293423Sdelphijconst char *	amtoa		(int am);
206293423Sdelphij
207293423Sdelphij
208285169Scyvoid
209293423Sdelphijset_sys_leap(
210293423Sdelphij	u_char new_sys_leap
211293423Sdelphij	)
212293423Sdelphij{
213285169Scy	sys_leap = new_sys_leap;
214285169Scy	xmt_leap = sys_leap;
215182007Sroberto
216285169Scy	/*
217285169Scy	 * Under certain conditions we send faked leap bits to clients, so
218285169Scy	 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
219285169Scy	 */
220285169Scy	if (xmt_leap != LEAP_NOTINSYNC) {
221285169Scy		if (leap_sec_in_progress) {
222285169Scy			/* always send "not sync" */
223285169Scy			xmt_leap = LEAP_NOTINSYNC;
224285169Scy		}
225285169Scy#ifdef LEAP_SMEAR
226285169Scy		else {
227285169Scy			/*
228293423Sdelphij			 * If leap smear is enabled in general we must
229293423Sdelphij			 * never send a leap second warning to clients,
230293423Sdelphij			 * so make sure we only send "in sync".
231285169Scy			 */
232285169Scy			if (leap_smear.enabled)
233285169Scy				xmt_leap = LEAP_NOWARNING;
234285169Scy		}
235285169Scy#endif	/* LEAP_SMEAR */
236285169Scy	}
237285169Scy}
238285169Scy
239293423Sdelphij
240289764Sglebius/*
241289764Sglebius * Kiss Code check
242289764Sglebius */
243293423Sdelphijint
244293423Sdelphijkiss_code_check(
245293423Sdelphij	u_char hisleap,
246293423Sdelphij	u_char hisstratum,
247293423Sdelphij	u_char hismode,
248293423Sdelphij	u_int32 refid
249293423Sdelphij	)
250293423Sdelphij{
251285169Scy
252293423Sdelphij	if (   hismode == MODE_SERVER
253293423Sdelphij	    && hisleap == LEAP_NOTINSYNC
254293423Sdelphij	    && hisstratum == STRATUM_UNSPEC) {
255293423Sdelphij		if(memcmp(&refid,"RATE", 4) == 0) {
256293423Sdelphij			return (RATEKISS);
257293423Sdelphij		} else if(memcmp(&refid,"DENY", 4) == 0) {
258293423Sdelphij			return (DENYKISS);
259293423Sdelphij		} else if(memcmp(&refid,"RSTR", 4) == 0) {
260293423Sdelphij			return (RSTRKISS);
261293423Sdelphij		} else if(memcmp(&refid,"X", 1) == 0) {
262293423Sdelphij			return (XKISS);
263293423Sdelphij		} else {
264293423Sdelphij			return (UNKNOWNKISS);
265289764Sglebius		}
266293423Sdelphij	} else {
267293423Sdelphij		return (NOKISS);
268293423Sdelphij	}
269289764Sglebius}
270293423Sdelphij
271293423Sdelphij
272298695Sdelphij/*
273298695Sdelphij * Check that NAK is valid
274298695Sdelphij */
275298695Sdelphijenum nak_error_codes
276298695Sdelphijvalid_NAK(
277298695Sdelphij	  struct peer *peer,
278298695Sdelphij	  struct recvbuf *rbufp,
279298695Sdelphij	  u_char hismode
280298695Sdelphij	  )
281298695Sdelphij{
282309007Sdelphij	int		base_packet_length = MIN_V4_PKT_LEN;
283301247Sdelphij	int		remainder_size;
284301247Sdelphij	struct pkt *	rpkt;
285301247Sdelphij	int		keyid;
286301247Sdelphij	l_fp		p_org;	/* origin timestamp */
287301247Sdelphij	const l_fp *	myorg;	/* selected peer origin */
288298695Sdelphij
289298695Sdelphij	/*
290298695Sdelphij	 * Check to see if there is something beyond the basic packet
291298695Sdelphij	 */
292298695Sdelphij	if (rbufp->recv_length == base_packet_length) {
293298695Sdelphij		return NONAK;
294298695Sdelphij	}
295298695Sdelphij
296298695Sdelphij	remainder_size = rbufp->recv_length - base_packet_length;
297298695Sdelphij	/*
298298695Sdelphij	 * Is this a potential NAK?
299298695Sdelphij	 */
300298695Sdelphij	if (remainder_size != 4) {
301298695Sdelphij		return NONAK;
302298695Sdelphij	}
303298695Sdelphij
304298695Sdelphij	/*
305298695Sdelphij	 * Only server responses can contain NAK's
306298695Sdelphij	 */
307298695Sdelphij
308298695Sdelphij	if (hismode != MODE_SERVER &&
309298695Sdelphij	    hismode != MODE_ACTIVE &&
310298695Sdelphij	    hismode != MODE_PASSIVE
311298695Sdelphij	    ) {
312301247Sdelphij		return INVALIDNAK;
313298695Sdelphij	}
314298695Sdelphij
315298695Sdelphij	/*
316298695Sdelphij	 * Make sure that the extra field in the packet is all zeros
317298695Sdelphij	 */
318298695Sdelphij	rpkt = &rbufp->recv_pkt;
319298695Sdelphij	keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
320298695Sdelphij	if (keyid != 0) {
321301247Sdelphij		return INVALIDNAK;
322298695Sdelphij	}
323298695Sdelphij
324298695Sdelphij	/*
325298695Sdelphij	 * Only valid if peer uses a key
326298695Sdelphij	 */
327301247Sdelphij	if (!peer || !peer->keyid || !(peer->flags & FLAG_SKEY)) {
328301247Sdelphij		return INVALIDNAK;
329298695Sdelphij	}
330301247Sdelphij
331301247Sdelphij	/*
332301247Sdelphij	 * The ORIGIN must match, or this cannot be a valid NAK, either.
333301247Sdelphij	 */
334301247Sdelphij	NTOHL_FP(&rpkt->org, &p_org);
335301247Sdelphij	if (peer->flip > 0)
336301247Sdelphij		myorg = &peer->borg;
337301247Sdelphij	else
338301247Sdelphij		myorg = &peer->aorg;
339309007Sdelphij
340301247Sdelphij	if (L_ISZERO(&p_org) ||
341301247Sdelphij	    L_ISZERO( myorg) ||
342301247Sdelphij	    !L_ISEQU(&p_org, myorg)) {
343301247Sdelphij		return INVALIDNAK;
344298695Sdelphij	}
345301247Sdelphij
346301247Sdelphij	/* If we ever passed all that checks, we should be safe. Well,
347301247Sdelphij	 * as safe as we can ever be with an unauthenticated crypto-nak.
348301247Sdelphij	 */
349301247Sdelphij	return VALIDNAK;
350298695Sdelphij}
351298695Sdelphij
352298695Sdelphij
35354359Sroberto/*
354280849Scy * transmit - transmit procedure called by poll timeout
35554359Sroberto */
35654359Srobertovoid
35754359Srobertotransmit(
35854359Sroberto	struct peer *peer	/* peer structure pointer */
35954359Sroberto	)
36054359Sroberto{
361280849Scy	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;
377280849Scy		if (sys_leap != LEAP_NOTINSYNC)
378280849Scy			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
388280849Scy	 * more servers have timed out or until less than sys_minclock
389182007Sroberto	 * associations turn up. In this case additional better servers
390280849Scy	 * are dragged in and preempt the existing ones.  Once every
391280849Scy	 * sys_beacon seconds we are to transmit unconditionally, but
392280849Scy	 * this code is not quite right -- peer->unreach counts polls
393280849Scy	 * and is being compared with sys_beacon, so the beacons happen
394280849Scy	 * 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);
402289764Sglebius		} else if (   sys_survivors < sys_minclock
403289764Sglebius			   || peer_associations < sys_maxclock) {
404280849Scy			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	/*
414280849Scy	 * Pool associations transmit unicast solicitations when there
415280849Scy	 * are less than a hard limit of 2 * sys_maxclock associations,
416280849Scy	 * and either less than sys_minclock survivors or less than
417280849Scy	 * sys_maxclock associations.  The hard limit prevents unbounded
418280849Scy	 * growth in associations if the system clock or network quality
419280849Scy	 * result in survivor count dipping below sys_minclock often.
420280849Scy	 * This was observed testing with pool, where sys_maxclock == 12
421280849Scy	 * resulted in 60 associations without the hard limit.  A
422280849Scy	 * similar hard limit on manycastclient ephemeral associations
423280849Scy	 * may be appropriate.
424280849Scy	 */
425280849Scy	if (peer->cast_flags & MDF_POOL) {
426280849Scy		peer->outdate = current_time;
427289764Sglebius		if (   (peer_associations <= 2 * sys_maxclock)
428289764Sglebius		    && (   peer_associations < sys_maxclock
429293423Sdelphij			|| sys_survivors < sys_minclock))
430280849Scy			pool_xmit(peer);
431280849Scy		poll_update(peer, hpoll);
432280849Scy		return;
433280849Scy	}
434280849Scy
435280849Scy	/*
436182007Sroberto	 * In unicast modes the dance is much more intricate. It is
437280849Scy	 * 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
446282408Scy		 * filter.
447132454Sroberto		 */
448182007Sroberto		oreach = peer->reach;
449182007Sroberto		peer->outdate = current_time;
450280849Scy		peer->unreach++;
451182007Sroberto		peer->reach <<= 1;
452182007Sroberto		if (!peer->reach) {
45382505Sroberto
454182007Sroberto			/*
455182007Sroberto			 * Here the peer is unreachable. If it was
456280849Scy			 * previously reachable raise a trap. Send a
457280849Scy			 * burst if enabled.
458182007Sroberto			 */
459280849Scy			clock_filter(peer, 0., 0., MAXDISPERSE);
460182007Sroberto			if (oreach) {
461280849Scy				peer_unfit(peer);
462280849Scy				report_event(PEVNT_UNREACH, peer, NULL);
463182007Sroberto			}
464289764Sglebius			if (   (peer->flags & FLAG_IBURST)
465289764Sglebius			    && peer->retry == 0)
466280849Scy				peer->retry = NTP_RETRY;
467182007Sroberto		} else {
468182007Sroberto
469182007Sroberto			/*
470280849Scy			 * Here the peer is reachable. Send a burst if
471280849Scy			 * enabled and the peer is fit.  Reset unreach
472280849Scy			 * for persistent and ephemeral associations.
473280849Scy			 * Unreach is also reset for survivors in
474280849Scy			 * clock_select().
475182007Sroberto			 */
476280849Scy			hpoll = sys_poll;
477280849Scy			if (!(peer->flags & FLAG_PREEMPT))
478182007Sroberto				peer->unreach = 0;
479289764Sglebius			if (   (peer->flags & FLAG_BURST)
480289764Sglebius			    && peer->retry == 0
481289764Sglebius			    && !peer_unfit(peer))
482280849Scy				peer->retry = NTP_RETRY;
483182007Sroberto		}
484182007Sroberto
485132454Sroberto		/*
486280849Scy		 * Watch for timeout.  If ephemeral, toss the rascal;
487280849Scy		 * otherwise, bump the poll interval. Note the
488280849Scy		 * poll_update() routine will clamp it to maxpoll.
489280849Scy		 * If preemptible and we have more peers than maxclock,
490280849Scy		 * and this peer has the minimum score of preemptibles,
491280849Scy		 * demobilize.
492282408Scy		 */
493132454Sroberto		if (peer->unreach >= NTP_UNREACH) {
494280849Scy			hpoll++;
495280849Scy			/* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
496280849Scy			if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
497280849Scy				report_event(PEVNT_RESTART, peer, "timeout");
498182007Sroberto				peer_clear(peer, "TIME");
49982505Sroberto				unpeer(peer);
50082505Sroberto				return;
50182505Sroberto			}
502289764Sglebius			if (   (peer->flags & FLAG_PREEMPT)
503289764Sglebius			    && (peer_associations > sys_maxclock)
504289764Sglebius			    && score_all(peer)) {
505280849Scy				report_event(PEVNT_RESTART, peer, "timeout");
506280849Scy				peer_clear(peer, "TIME");
507280849Scy				unpeer(peer);
508280849Scy				return;
509280849Scy			}
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,
524280849Scy					    "ntpd: no servers found");
525280849Scy					if (!msyslog_term)
526280849Scy						printf(
527280849Scy						    "ntpd: no servers found\n");
528132454Sroberto					exit (0);
529132454Sroberto				}
53054359Sroberto			}
53154359Sroberto		}
53254359Sroberto	}
533280849Scy	if (peer->retry > 0)
534280849Scy		peer->retry--;
53554359Sroberto
53654359Sroberto	/*
537282408Scy	 * Do not transmit if in broadcast client mode.
53854359Sroberto	 */
539182007Sroberto	if (peer->hmode != MODE_BCLIENT)
540182007Sroberto		peer_xmit(peer);
541132454Sroberto	poll_update(peer, hpoll);
542293423Sdelphij
543293423Sdelphij	return;
54454359Sroberto}
54554359Sroberto
546182007Sroberto
547293423Sdelphijconst char *
548293423Sdelphijamtoa(
549293423Sdelphij	int am
550293423Sdelphij	)
551293423Sdelphij{
552293423Sdelphij	char *bp;
553293423Sdelphij
554293423Sdelphij	switch(am) {
555293423Sdelphij	    case AM_ERR:	return "AM_ERR";
556293423Sdelphij	    case AM_NOMATCH:	return "AM_NOMATCH";
557293423Sdelphij	    case AM_PROCPKT:	return "AM_PROCPKT";
558293423Sdelphij	    case AM_BCST:	return "AM_BCST";
559293423Sdelphij	    case AM_FXMIT:	return "AM_FXMIT";
560293423Sdelphij	    case AM_MANYCAST:	return "AM_MANYCAST";
561293423Sdelphij	    case AM_NEWPASS:	return "AM_NEWPASS";
562293423Sdelphij	    case AM_NEWBCL:	return "AM_NEWBCL";
563293423Sdelphij	    case AM_POSSBCL:	return "AM_POSSBCL";
564293423Sdelphij	    default:
565293423Sdelphij		LIB_GETBUF(bp);
566293423Sdelphij		snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
567293423Sdelphij		return bp;
568293423Sdelphij	}
569293423Sdelphij}
570293423Sdelphij
571293423Sdelphij
57254359Sroberto/*
573280849Scy * 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 */
582280849Scy	u_char	hisversion;		/* packet version */
583280849Scy	u_char	hisleap;		/* packet leap indicator */
584280849Scy	u_char	hismode;		/* packet mode */
585280849Scy	u_char	hisstratum;		/* packet stratum */
586280849Scy	u_short	restrict_mask;		/* restrict bits */
587293423Sdelphij	const char *hm_str;		/* hismode string */
588293423Sdelphij	const char *am_str;		/* association match string */
589293423Sdelphij	int	kissCode = NOKISS;	/* Kiss Code */
590132454Sroberto	int	has_mac;		/* length of MAC field */
591132454Sroberto	int	authlen;		/* offset of MAC field */
592301247Sdelphij	int	is_authentic = AUTH_NONE;	/* cryptosum ok */
593298695Sdelphij	int	crypto_nak_test;	/* result of crypto-NAK check */
594280849Scy	int	retcode = AM_NOMATCH;	/* match code */
595280849Scy	keyid_t	skeyid = 0;		/* key IDs */
596280849Scy	u_int32	opcode = 0;		/* extension field opcode */
597293423Sdelphij	sockaddr_u *dstadr_sin;		/* active runway */
598132454Sroberto	struct peer *peer2;		/* aux peer structure pointer */
599293423Sdelphij	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 */
603280849Scy#ifdef AUTOKEY
604280849Scy	char	hostname[NTP_MAXSTRLEN + 1];
605280849Scy	char	*groupname = NULL;
606132454Sroberto	struct autokey *ap;		/* autokey structure pointer */
607132454Sroberto	int	rval;			/* cookie snatcher */
608280849Scy	keyid_t	pkeyid = 0, tkeyid = 0;	/* key IDs */
609280849Scy#endif	/* AUTOKEY */
610280849Scy#ifdef HAVE_NTP_SIGND
611280849Scy	static unsigned char zero_key[16];
612280849Scy#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
617280849Scy	 * by the service routines. Some restrictions have to be handled
618280849Scy	 * 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++;
625280849Scy	if (0 == SRCPORT(&rbufp->recv_srcadr)) {
626132454Sroberto		sys_badlength++;
627132454Sroberto		return;				/* bogus port */
628132454Sroberto	}
629280849Scy	restrict_mask = restrictions(&rbufp->recv_srcadr);
630293423Sdelphij	pkt = &rbufp->recv_pkt;
631293423Sdelphij	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),
633293423Sdelphij		    stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,
634293423Sdelphij		    restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
635293423Sdelphij		    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);
640301247Sdelphij	INSIST(0 != hisstratum);
641301247Sdelphij
642280849Scy	if (restrict_mask & RES_IGNORE) {
643280849Scy		sys_restricted++;
644280849Scy		return;				/* ignore everything */
645280849Scy	}
646132454Sroberto	if (hismode == MODE_PRIVATE) {
647280849Scy		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++;
665280849Scy		return;				/* no time serve */
666132454Sroberto	}
667280849Scy
668280849Scy	/*
669280849Scy	 * This is for testing. If restricted drop ten percent of
670280849Scy	 * surviving packets.
671280849Scy	 */
672280849Scy	if (restrict_mask & RES_FLAKE) {
673280849Scy		if ((double)ntp_random() / 0x7fffffff < .1) {
674280849Scy			sys_restricted++;
675280849Scy			return;			/* no flakeway */
676280849Scy		}
67782505Sroberto	}
678282408Scy
679132454Sroberto	/*
680132454Sroberto	 * Version check must be after the query packets, since they
681280849Scy	 * intentionally use an early version.
682132454Sroberto	 */
683182007Sroberto	if (hisversion == NTP_VERSION) {
684280849Scy		sys_newversion++;		/* new version */
685289764Sglebius	} else if (   !(restrict_mask & RES_VERSION)
686289764Sglebius		   && hisversion >= NTP_OLDVERSION) {
687280849Scy		sys_oldversion++;		/* previous version */
688132454Sroberto	} else {
689280849Scy		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
714280849Scy	 * with DES; if 5, the packet is authenticated with MD5; if 6,
715280849Scy	 * the packet is authenticated with SHA. If 2 or * 4, the packet
716280849Scy	 * is a runt and discarded forthwith. If greater than 6, an
717280849Scy	 * extension field is present, so we subtract the length of the
718280849Scy	 * field and go around again.
71954359Sroberto	 */
720298695Sdelphij
72154359Sroberto	authlen = LEN_PKT_NOMAC;
722132454Sroberto	has_mac = rbufp->recv_length - authlen;
723132454Sroberto	while (has_mac > 0) {
724280849Scy		u_int32	len;
725280849Scy#ifdef AUTOKEY
726280849Scy		u_int32	hostlen;
727280849Scy		struct exten *ep;
728280849Scy#endif /*AUTOKEY */
72982505Sroberto
730280849Scy		if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
73154359Sroberto			sys_badlength++;
732280849Scy			return;			/* bad length */
73354359Sroberto		}
734280849Scy		if (has_mac <= (int)MAX_MAC_LEN) {
73582505Sroberto			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
73682505Sroberto			break;
73754359Sroberto
738280849Scy		} else {
739280849Scy			opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
740280849Scy			len = opcode & 0xffff;
741289764Sglebius			if (   len % 4 != 0
742289764Sglebius			    || len < 4
743289764Sglebius			    || (int)len + authlen > rbufp->recv_length) {
74482505Sroberto				sys_badlength++;
745280849Scy				return;		/* bad length */
74682505Sroberto			}
747280849Scy#ifdef AUTOKEY
748280849Scy			/*
749280849Scy			 * Extract calling group name for later.  If
750280849Scy			 * sys_groupname is non-NULL, there must be
751280849Scy			 * a group name provided to elicit a response.
752280849Scy			 */
753289764Sglebius			if (   (opcode & 0x3fff0000) == CRYPTO_ASSOC
754289764Sglebius			    && sys_groupname != NULL) {
755280849Scy				ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
756280849Scy				hostlen = ntohl(ep->vallen);
757289764Sglebius				if (   hostlen >= sizeof(hostname)
758289764Sglebius				    || hostlen > len -
759289764Sglebius						offsetof(struct exten, pkt)) {
760280849Scy					sys_badlength++;
761280849Scy					return;		/* bad length */
762280849Scy				}
763280849Scy				memcpy(hostname, &ep->pkt, hostlen);
764280849Scy				hostname[hostlen] = '\0';
765280849Scy				groupname = strchr(hostname, '@');
766280849Scy				if (groupname == NULL) {
767280849Scy					sys_declined++;
768280849Scy					return;
769280849Scy				}
770280849Scy				groupname++;
771280849Scy			}
772280849Scy#endif /* AUTOKEY */
773280849Scy			authlen += len;
774280849Scy			has_mac -= len;
77582505Sroberto		}
77654359Sroberto	}
77754359Sroberto
77854359Sroberto	/*
779280849Scy	 * If has_mac is < 0 we had a malformed packet.
780280849Scy	 */
781280849Scy	if (has_mac < 0) {
782280849Scy		sys_badlength++;
783280849Scy		return;		/* bad length */
784280849Scy	}
785280849Scy
786280849Scy	/*
787280849Scy	 * If authentication required, a MAC must be present.
788280849Scy	 */
789280849Scy	if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
790280849Scy		sys_restricted++;
791280849Scy		return;				/* access denied */
792280849Scy	}
793280849Scy
794280849Scy	/*
795280849Scy	 * Update the MRU list and finger the cloggers. It can be a
796280849Scy	 * little expensive, so turn it off for production use.
797280849Scy	 * RES_LIMITED and RES_KOD will be cleared in the returned
798280849Scy	 * restrict_mask unless one or both actions are warranted.
799280849Scy	 */
800280849Scy	restrict_mask = ntp_monitor(rbufp, restrict_mask);
801280849Scy	if (restrict_mask & RES_LIMITED) {
802280849Scy		sys_limitrejected++;
803289764Sglebius		if (   !(restrict_mask & RES_KOD)
804289764Sglebius		    || MODE_BROADCAST == hismode
805289764Sglebius		    || MODE_SERVER == hismode) {
806280849Scy			if (MODE_SERVER == hismode)
807280849Scy				DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
808280849Scy					stoa(&rbufp->recv_srcadr)));
809280849Scy			return;			/* rate exceeded */
810280849Scy		}
811280849Scy		if (hismode == MODE_CLIENT)
812280849Scy			fast_xmit(rbufp, MODE_SERVER, skeyid,
813280849Scy			    restrict_mask);
814280849Scy		else
815280849Scy			fast_xmit(rbufp, MODE_ACTIVE, skeyid,
816280849Scy			    restrict_mask);
817280849Scy		return;				/* rate exceeded */
818280849Scy	}
819280849Scy	restrict_mask &= ~RES_KOD;
820280849Scy
821280849Scy	/*
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
826280849Scy	 * 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.
836280849Scy	 * 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	 */
840280849Scy	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);
845293423Sdelphij	hm_str = modetoa(hismode);
846293423Sdelphij	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	 */
871298695Sdelphij	crypto_nak_test = valid_NAK(peer, rbufp, hismode);
872280849Scy
873298695Sdelphij	/*
874298695Sdelphij	 * Drop any invalid crypto-NAKs
875298695Sdelphij	 */
876298695Sdelphij	if (crypto_nak_test == INVALIDNAK) {
877298695Sdelphij		report_event(PEVNT_AUTH, peer, "Invalid_NAK");
878298695Sdelphij		if (0 != peer) {
879298695Sdelphij			peer->badNAK++;
880298695Sdelphij		}
881298695Sdelphij		msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
882298695Sdelphij			current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
883298695Sdelphij		return;
884298695Sdelphij	}
885298695Sdelphij
88654359Sroberto	if (has_mac == 0) {
887280849Scy		restrict_mask &= ~RES_MSSNTP;
888182007Sroberto		is_authentic = AUTH_NONE; /* not required */
889293423Sdelphij		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),
891293423Sdelphij			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
892293423Sdelphij			    authlen,
893293423Sdelphij			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
894293423Sdelphij			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
895298695Sdelphij	} else if (crypto_nak_test == VALIDNAK) {
896280849Scy		restrict_mask &= ~RES_MSSNTP;
897280849Scy		is_authentic = AUTH_CRYPTO; /* crypto-NAK */
898293423Sdelphij		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),
900293423Sdelphij			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
901293423Sdelphij			    skeyid, authlen + has_mac, is_authentic,
902293423Sdelphij			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
903293423Sdelphij			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
904280849Scy
905280849Scy#ifdef HAVE_NTP_SIGND
906280849Scy		/*
907280849Scy		 * If the signature is 20 bytes long, the last 16 of
908280849Scy		 * which are zero, then this is a Microsoft client
909280849Scy		 * wanting AD-style authentication of the server's
910282408Scy		 * reply.
911280849Scy		 *
912280849Scy		 * This is described in Microsoft's WSPP docs, in MS-SNTP:
913280849Scy		 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
914280849Scy		 */
915289764Sglebius	} else if (   has_mac == MAX_MD5_LEN
916289764Sglebius		   && (restrict_mask & RES_MSSNTP)
917289764Sglebius		   && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
918289764Sglebius		   && (memcmp(zero_key, (char *)pkt + authlen + 4,
919293423Sdelphij			      MAX_MD5_LEN - 4) == 0)) {
920280849Scy		is_authentic = AUTH_NONE;
921280849Scy#endif /* HAVE_NTP_SIGND */
922280849Scy
92354359Sroberto	} else {
924280849Scy		restrict_mask &= ~RES_MSSNTP;
925280849Scy#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		 */
931280849Scy		if (crypto_flags && skeyid > NTP_MAXKEY) {
932282408Scy
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			 */
958280849Scy			if (has_mac < (int)MAX_MD5_LEN) {
959280849Scy				sys_badauth++;
960280849Scy				return;
961280849Scy			}
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				 */
972289764Sglebius				if (   crypto_flags
973289764Sglebius				    && rbufp->dstadr ==
974289764Sglebius				       ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
975182007Sroberto					sys_restricted++;
976182007Sroberto					return;	     /* no wildcard */
977182007Sroberto				}
97882505Sroberto				pkeyid = 0;
979280849Scy				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			 */
997280849Scy			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		}
1010280849Scy#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,
1020280849Scy		    has_mac))
1021182007Sroberto			is_authentic = AUTH_ERROR;
1022280849Scy		else
1023182007Sroberto			is_authentic = AUTH_OK;
1024280849Scy#ifdef AUTOKEY
1025280849Scy		if (crypto_flags && skeyid > NTP_MAXKEY)
102682505Sroberto			authtrust(skeyid, 0);
1027280849Scy#endif	/* AUTOKEY */
1028293423Sdelphij		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),
1030293423Sdelphij			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1031293423Sdelphij			    skeyid, authlen + has_mac, is_authentic,
1032293423Sdelphij			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1033293423Sdelphij			    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		/*
1057280849Scy		 * If authentication OK, send a server reply; otherwise,
1058280849Scy		 * send a crypto-NAK.
105956749Sroberto		 */
1060182007Sroberto		if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1061182007Sroberto			if (AUTH(restrict_mask & RES_DONTTRUST,
1062280849Scy			   is_authentic)) {
1063182007Sroberto				fast_xmit(rbufp, MODE_SERVER, skeyid,
1064182007Sroberto				    restrict_mask);
1065280849Scy			} else if (is_authentic == AUTH_ERROR) {
1066182007Sroberto				fast_xmit(rbufp, MODE_SERVER, 0,
1067182007Sroberto				    restrict_mask);
1068280849Scy				sys_badauth++;
1069280849Scy			} else {
1070280849Scy				sys_restricted++;
1071280849Scy			}
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
1084280849Scy#ifdef AUTOKEY
1085182007Sroberto		/*
1086280849Scy		 * Do not respond if not the same group.
1087182007Sroberto		 */
1088280849Scy		if (group_test(groupname, NULL)) {
1089280849Scy			sys_declined++;
1090280849Scy			return;
1091280849Scy		}
1092280849Scy#endif /* AUTOKEY */
1093182007Sroberto
1094182007Sroberto		/*
1095280849Scy		 * Do not respond if we are not synchronized or our
1096280849Scy		 * stratum is greater than the manycaster or the
1097280849Scy		 * manycaster has already synchronized to us.
1098182007Sroberto		 */
1099289764Sglebius		if (   sys_leap == LEAP_NOTINSYNC
1100289764Sglebius		    || sys_stratum >= hisstratum
1101289764Sglebius		    || (!sys_cohort && sys_stratum == hisstratum + 1)
1102289764Sglebius		    || rbufp->dstadr->addr_refid == pkt->refid) {
1103280849Scy			sys_declined++;
1104182007Sroberto			return;			/* no help */
1105280849Scy		}
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
1118280849Scy	 * mode packet sent to a multicast group address (for
1119280849Scy	 * manycastclient) or to a unicast address (for pool). The
1120280849Scy	 * origin timestamp is a good nonce to reliably associate the
1121280849Scy	 * reply with what was sent. If there is no match, that's
1122280849Scy	 * curious and could be an intruder attempting to clog, so we
1123280849Scy	 * just ignore it.
1124182007Sroberto	 *
1125282408Scy	 * If the packet is authentic and the manycastclient or pool
1126280849Scy	 * association is found, we mobilize a client association and
1127280849Scy	 * copy pertinent variables from the manycastclient or pool
1128280849Scy	 * association to the new client association. If not, just
1129280849Scy	 * 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
1137280849Scy#ifdef AUTOKEY
1138280849Scy		/*
1139280849Scy		 * Do not respond if not the same group.
1140280849Scy		 */
1141280849Scy		if (group_test(groupname, NULL)) {
1142280849Scy			sys_declined++;
1143280849Scy			return;
1144280849Scy		}
1145280849Scy#endif /* AUTOKEY */
1146182007Sroberto		if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1147132454Sroberto			sys_restricted++;
1148182007Sroberto			return;			/* not enabled */
1149132454Sroberto		}
1150289764Sglebius		if (!AUTH(  (!(peer2->cast_flags & MDF_POOL)
1151289764Sglebius			     && sys_authenticate)
1152289764Sglebius			  || (restrict_mask & (RES_NOPEER |
1153289764Sglebius			      RES_DONTTRUST)), is_authentic)) {
1154280849Scy			sys_restricted++;
1155280849Scy			return;			/* access denied */
1156280849Scy		}
1157132454Sroberto
1158132454Sroberto		/*
1159280849Scy		 * Do not respond if unsynchronized or stratum is below
1160280849Scy		 * the floor or at or above the ceiling.
1161132454Sroberto		 */
1162289764Sglebius		if (   hisleap == LEAP_NOTINSYNC
1163289764Sglebius		    || hisstratum < sys_floor
1164289764Sglebius		    || hisstratum >= sys_ceiling) {
1165280849Scy			sys_declined++;
1166280849Scy			return;			/* no help */
1167280849Scy		}
1168280849Scy		peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1169280849Scy			       MODE_CLIENT, hisversion, peer2->minpoll,
1170280849Scy			       peer2->maxpoll, FLAG_PREEMPT |
1171280849Scy			       (FLAG_IBURST & peer2->flags), MDF_UCAST |
1172280849Scy			       MDF_UCLNT, 0, skeyid, sys_ident);
1173280849Scy		if (NULL == peer) {
1174280849Scy			sys_declined++;
1175280849Scy			return;			/* ignore duplicate  */
1176280849Scy		}
117756749Sroberto
1178280849Scy		/*
1179280849Scy		 * After each ephemeral pool association is spun,
1180280849Scy		 * accelerate the next poll for the pool solicitor so
1181280849Scy		 * the pool will fill promptly.
1182280849Scy		 */
1183280849Scy		if (peer2->cast_flags & MDF_POOL)
1184280849Scy			peer2->nextdate = current_time + 1;
1185280849Scy
1186280849Scy		/*
1187280849Scy		 * Further processing of the solicitation response would
1188280849Scy		 * simply detect its origin timestamp as bogus for the
1189280849Scy		 * brand-new association (it matches the prototype
1190280849Scy		 * association) and tinker with peer->nextdate delaying
1191280849Scy		 * first sync.
1192280849Scy		 */
1193280849Scy		return;		/* solicitation response handled */
1194280849Scy
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:
1202280849Scy
1203280849Scy#ifdef AUTOKEY
1204280849Scy		/*
1205280849Scy		 * Do not respond if not the same group.
1206280849Scy		 */
1207280849Scy		if (group_test(groupname, sys_ident)) {
1208280849Scy			sys_declined++;
1209280849Scy			return;
1210280849Scy		}
1211280849Scy#endif /* AUTOKEY */
1212280849Scy		if (sys_bclient == 0) {
1213280849Scy			sys_restricted++;
1214280849Scy			return;			/* not enabled */
1215280849Scy		}
1216182007Sroberto		if (!AUTH(sys_authenticate | (restrict_mask &
1217280849Scy		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1218280849Scy			sys_restricted++;
1219280849Scy			return;			/* access denied */
1220280849Scy		}
122154359Sroberto
122256749Sroberto		/*
1223182007Sroberto		 * Do not respond if unsynchronized or stratum is below
1224182007Sroberto		 * the floor or at or above the ceiling.
122556749Sroberto		 */
1226289764Sglebius		if (   hisleap == LEAP_NOTINSYNC
1227289764Sglebius		    || hisstratum < sys_floor
1228289764Sglebius		    || hisstratum >= sys_ceiling) {
1229280849Scy			sys_declined++;
1230280849Scy			return;			/* no help */
1231280849Scy		}
1232132454Sroberto
1233280849Scy#ifdef AUTOKEY
123456749Sroberto		/*
1235280849Scy		 * Do not respond if Autokey and the opcode is not a
1236280849Scy		 * CRYPTO_ASSOC response with association ID.
123756749Sroberto		 */
1238289764Sglebius		if (   crypto_flags && skeyid > NTP_MAXKEY
1239289764Sglebius		    && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1240280849Scy			sys_declined++;
1241280849Scy			return;			/* protocol error */
1242280849Scy		}
1243280849Scy#endif	/* AUTOKEY */
124482505Sroberto
1245132454Sroberto		/*
1246280849Scy		 * Broadcasts received via a multicast address may
1247280849Scy		 * arrive after a unicast volley has begun
1248280849Scy		 * with the same remote address.  newpeer() will not
1249280849Scy		 * find duplicate associations on other local endpoints
1250280849Scy		 * if a non-NULL endpoint is supplied.  multicastclient
1251280849Scy		 * ephemeral associations are unique across all local
1252280849Scy		 * endpoints.
1253132454Sroberto		 */
1254280849Scy		if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1255280849Scy			match_ep = rbufp->dstadr;
1256280849Scy		else
1257280849Scy			match_ep = NULL;
125856749Sroberto
1259132454Sroberto		/*
1260280849Scy		 * Determine whether to execute the initial volley.
126156749Sroberto		 */
1262298695Sdelphij		if (sys_bdelay > 0.0) {
1263280849Scy#ifdef AUTOKEY
1264182007Sroberto			/*
1265182007Sroberto			 * If a two-way exchange is not possible,
1266182007Sroberto			 * neither is Autokey.
1267182007Sroberto			 */
1268280849Scy			if (crypto_flags && skeyid > NTP_MAXKEY) {
1269280849Scy				sys_restricted++;
1270182007Sroberto				return;		/* no autokey */
1271182007Sroberto			}
1272280849Scy#endif	/* AUTOKEY */
1273280849Scy
1274280849Scy			/*
1275280849Scy			 * Do not execute the volley. Start out in
1276280849Scy			 * broadcast client mode.
1277280849Scy			 */
1278280849Scy			peer = newpeer(&rbufp->recv_srcadr, NULL,
1279280849Scy			    match_ep, MODE_BCLIENT, hisversion,
1280280849Scy			    pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1281280849Scy			    MDF_BCLNT, 0, skeyid, sys_ident);
1282280849Scy			if (NULL == peer) {
1283280849Scy				sys_restricted++;
1284280849Scy				return;		/* ignore duplicate */
1285280849Scy
1286280849Scy			} else {
1287280849Scy				peer->delay = sys_bdelay;
1288294554Sdelphij				peer->bxmt = p_xmt;
1289280849Scy			}
1290280849Scy			break;
1291132454Sroberto		}
129256749Sroberto
1293280849Scy		/*
1294280849Scy		 * Execute the initial volley in order to calibrate the
1295280849Scy		 * propagation delay and run the Autokey protocol.
1296280849Scy		 *
1297280849Scy		 * Note that the minpoll is taken from the broadcast
1298280849Scy		 * packet, normally 6 (64 s) and that the poll interval
1299280849Scy		 * is fixed at this value.
1300280849Scy		 */
1301280849Scy		peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1302280849Scy		    MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1303280849Scy		    FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1304280849Scy		    0, skeyid, sys_ident);
1305280849Scy		if (NULL == peer) {
1306280849Scy			sys_restricted++;
1307280849Scy			return;			/* ignore duplicate */
1308280849Scy		}
1309294554Sdelphij		peer->bxmt = p_xmt;
1310280849Scy#ifdef AUTOKEY
1311280849Scy		if (skeyid > NTP_MAXKEY)
1312280849Scy			crypto_recv(peer, rbufp);
1313280849Scy#endif	/* AUTOKEY */
1314280849Scy
1315280849Scy		return;				/* hooray */
1316280849Scy
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
1324280849Scy#ifdef AUTOKEY
132556749Sroberto		/*
1326280849Scy		 * Do not respond if not the same group.
132756749Sroberto		 */
1328280849Scy		if (group_test(groupname, sys_ident)) {
1329280849Scy			sys_declined++;
1330280849Scy			return;
1331280849Scy		}
1332280849Scy#endif /* AUTOKEY */
1333280849Scy		if (!AUTH(sys_authenticate | (restrict_mask &
1334280849Scy		    (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1335280849Scy
1336280849Scy			/*
1337280849Scy			 * If authenticated but cannot mobilize an
1338280849Scy			 * association, send a symmetric passive
1339280849Scy			 * response without mobilizing an association.
1340280849Scy			 * This is for drat broken Windows clients. See
1341280849Scy			 * Microsoft KB 875424 for preferred workaround.
1342280849Scy			 */
1343280849Scy			if (AUTH(restrict_mask & RES_DONTTRUST,
1344280849Scy			    is_authentic)) {
1345280849Scy				fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1346280849Scy				    restrict_mask);
1347280849Scy				return;			/* hooray */
1348280849Scy			}
1349280849Scy			if (is_authentic == AUTH_ERROR) {
1350182007Sroberto				fast_xmit(rbufp, MODE_ACTIVE, 0,
1351182007Sroberto				    restrict_mask);
1352280849Scy				sys_restricted++;
1353280849Scy				return;
1354280849Scy			}
1355289764Sglebius			/* [Bug 2941]
1356289764Sglebius			 * If we got here, the packet isn't part of an
1357289764Sglebius			 * existing association, it isn't correctly
1358289764Sglebius			 * authenticated, and it didn't meet either of
1359289764Sglebius			 * the previous two special cases so we should
1360289764Sglebius			 * just drop it on the floor.  For example,
1361289764Sglebius			 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1362289764Sglebius			 * will make it this far.  This is just
1363289764Sglebius			 * debug-printed and not logged to avoid log
1364289764Sglebius			 * flooding.
1365289764Sglebius			 */
1366293423Sdelphij			DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1367293423Sdelphij				    " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1368289764Sglebius				    current_time, stoa(&rbufp->recv_srcadr),
1369293423Sdelphij				    hismode, hm_str, am_str, skeyid,
1370293423Sdelphij				    (authlen + has_mac), is_authentic));
1371289764Sglebius			sys_declined++;
1372289764Sglebius			return;
1373182007Sroberto		}
1374280849Scy
1375280849Scy		/*
1376280849Scy		 * Do not respond if synchronized and if stratum is
1377280849Scy		 * below the floor or at or above the ceiling. Note,
1378280849Scy		 * this allows an unsynchronized peer to synchronize to
1379280849Scy		 * us. It would be very strange if he did and then was
1380280849Scy		 * nipped, but that could only happen if we were
1381280849Scy		 * operating at the top end of the range.  It also means
1382280849Scy		 * we will spin an ephemeral association in response to
1383280849Scy		 * MODE_ACTIVE KoDs, which will time out eventually.
1384280849Scy		 */
1385289764Sglebius		if (   hisleap != LEAP_NOTINSYNC
1386289764Sglebius		    && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1387280849Scy			sys_declined++;
1388280849Scy			return;			/* no help */
1389182007Sroberto		}
139054359Sroberto
1391182007Sroberto		/*
1392280849Scy		 * The message is correctly authenticated and allowed.
1393280849Scy		 * Mobilize a symmetric passive association.
1394182007Sroberto		 */
1395280849Scy		if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1396280849Scy		    rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1397280849Scy		    NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1398280849Scy		    sys_ident)) == NULL) {
1399280849Scy			sys_declined++;
1400280849Scy			return;			/* ignore duplicate */
1401280849Scy		}
1402182007Sroberto		break;
1403182007Sroberto
1404280849Scy
140554359Sroberto	/*
1406182007Sroberto	 * Process regular packet. Nothing special.
140754359Sroberto	 */
1408182007Sroberto	case AM_PROCPKT:
1409280849Scy
1410280849Scy#ifdef AUTOKEY
1411280849Scy		/*
1412280849Scy		 * Do not respond if not the same group.
1413280849Scy		 */
1414280849Scy		if (group_test(groupname, peer->ident)) {
1415280849Scy			sys_declined++;
1416280849Scy			return;
1417280849Scy		}
1418280849Scy#endif /* AUTOKEY */
1419294554Sdelphij
1420294554Sdelphij		if (MODE_BROADCAST == hismode) {
1421298695Sdelphij			int	bail = 0;
1422298695Sdelphij			l_fp	tdiff;
1423298695Sdelphij			u_long	deadband;
1424294554Sdelphij
1425294554Sdelphij			DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1426294554Sdelphij				    (current_time - peer->timelastrec),
1427294554Sdelphij				    peer->ppoll, (1 << peer->ppoll)
1428294554Sdelphij				    ));
1429294554Sdelphij			/* Things we can check:
1430294554Sdelphij			 *
1431294554Sdelphij			 * Did the poll interval change?
1432294554Sdelphij			 * Is the poll interval in the packet in-range?
1433294554Sdelphij			 * Did this packet arrive too soon?
1434294554Sdelphij			 * Is the timestamp in this packet monotonic
1435294554Sdelphij			 *  with respect to the previous packet?
1436294554Sdelphij			 */
1437294554Sdelphij
1438294554Sdelphij			/* This is noteworthy, not error-worthy */
1439294554Sdelphij			if (pkt->ppoll != peer->ppoll) {
1440294554Sdelphij				msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud",
1441294554Sdelphij					stoa(&rbufp->recv_srcadr),
1442294554Sdelphij					peer->ppoll, pkt->ppoll);
1443294554Sdelphij			}
1444294554Sdelphij
1445294554Sdelphij			/* This is error-worthy */
1446298695Sdelphij			if (pkt->ppoll < peer->minpoll ||
1447298695Sdelphij			    pkt->ppoll > peer->maxpoll  ) {
1448294554Sdelphij				msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!",
1449294554Sdelphij					pkt->ppoll, stoa(&rbufp->recv_srcadr),
1450294554Sdelphij					peer->minpoll, peer->maxpoll);
1451294554Sdelphij				++bail;
1452294554Sdelphij			}
1453294554Sdelphij
1454309007Sdelphij			/* too early? worth an error, too!
1455309007Sdelphij			 *
1456309007Sdelphij			 * [Bug 3113] Ensure that at least one poll
1457309007Sdelphij			 * interval has elapsed since the last **clean**
1458309007Sdelphij			 * packet was received.  We limit the check to
1459309007Sdelphij			 * **clean** packets to prevent replayed packets
1460309007Sdelphij			 * and incorrectly authenticated packets, which
1461309007Sdelphij			 * we'll discard, from being used to create a
1462309007Sdelphij			 * denial of service condition.
1463309007Sdelphij			 */
1464298695Sdelphij			deadband = (1u << pkt->ppoll);
1465298695Sdelphij			if (FLAG_BC_VOL & peer->flags)
1466298695Sdelphij				deadband -= 3;	/* allow greater fuzz after volley */
1467309007Sdelphij			if ((current_time - peer->timereceived) < deadband) {
1468298695Sdelphij				msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1469294554Sdelphij					stoa(&rbufp->recv_srcadr),
1470309007Sdelphij					(current_time - peer->timereceived),
1471298695Sdelphij					deadband);
1472294554Sdelphij				++bail;
1473294554Sdelphij			}
1474294554Sdelphij
1475309007Sdelphij			/* Alert if time from the server is non-monotonic.
1476309007Sdelphij			 *
1477309007Sdelphij			 * [Bug 3114] is about Broadcast mode replay DoS.
1478309007Sdelphij			 *
1479309007Sdelphij			 * Broadcast mode *assumes* a trusted network.
1480309007Sdelphij			 * Even so, it's nice to be robust in the face
1481309007Sdelphij			 * of attacks.
1482309007Sdelphij			 *
1483309007Sdelphij			 * If we get an authenticated broadcast packet
1484309007Sdelphij			 * with an "earlier" timestamp, it means one of
1485309007Sdelphij			 * two things:
1486309007Sdelphij			 *
1487309007Sdelphij			 * - the broadcast server had a backward step.
1488309007Sdelphij			 *
1489309007Sdelphij			 * - somebody is trying a replay attack.
1490309007Sdelphij			 *
1491309007Sdelphij			 * deadband: By default, we assume the broadcast
1492309007Sdelphij			 * network is trustable, so we take our accepted
1493309007Sdelphij			 * broadcast packets as we receive them.  But
1494309007Sdelphij			 * some folks might want to take additional poll
1495309007Sdelphij			 * delays before believing a backward step.
1496309007Sdelphij			 */
1497309007Sdelphij			if (sys_bcpollbstep) {
1498309007Sdelphij				/* pkt->ppoll or peer->ppoll ? */
1499309007Sdelphij				deadband = (1u << pkt->ppoll)
1500309007Sdelphij					   * sys_bcpollbstep + 2;
1501309007Sdelphij			} else {
1502309007Sdelphij				deadband = 0;
1503309007Sdelphij			}
1504309007Sdelphij
1505309007Sdelphij			if (L_ISZERO(&peer->bxmt)) {
1506309007Sdelphij				tdiff.l_ui = tdiff.l_uf = 0;
1507309007Sdelphij			} else {
1508309007Sdelphij				tdiff = p_xmt;
1509309007Sdelphij				L_SUB(&tdiff, &peer->bxmt);
1510309007Sdelphij			}
1511309007Sdelphij			if (tdiff.l_i < 0 &&
1512309007Sdelphij			    (current_time - peer->timereceived) < deadband)
1513309007Sdelphij			{
1514294554Sdelphij				msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1515294554Sdelphij					stoa(&rbufp->recv_srcadr),
1516294554Sdelphij					peer->bxmt.l_ui, peer->bxmt.l_uf,
1517294554Sdelphij					p_xmt.l_ui, p_xmt.l_uf
1518294554Sdelphij					);
1519294554Sdelphij				++bail;
1520294554Sdelphij			}
1521294554Sdelphij
1522294554Sdelphij			if (bail) {
1523294554Sdelphij				peer->timelastrec = current_time;
1524294554Sdelphij				sys_declined++;
1525294554Sdelphij				return;
1526294554Sdelphij			}
1527294554Sdelphij		}
1528294554Sdelphij
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
1534280849Scy	 * this association might be legitimate and this packet an
1535182007Sroberto	 * attempt to deny service, just ignore it.
153654359Sroberto	 */
1537182007Sroberto	case AM_ERR:
1538280849Scy		sys_declined++;
1539182007Sroberto		return;
1540132454Sroberto
1541132454Sroberto	/*
1542182007Sroberto	 * For everything else there is the bit bucket.
1543132454Sroberto	 */
1544182007Sroberto	default:
1545280849Scy		sys_declined++;
1546182007Sroberto		return;
1547182007Sroberto	}
1548280849Scy
1549280849Scy#ifdef AUTOKEY
1550280849Scy	/*
1551280849Scy	 * If the association is configured for Autokey, the packet must
1552280849Scy	 * have a public key ID; if not, the packet must have a
1553280849Scy	 * symmetric key ID.
1554280849Scy	 */
1555289764Sglebius	if (   is_authentic != AUTH_CRYPTO
1556289764Sglebius	    && (   ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1557289764Sglebius	        || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1558280849Scy		sys_badauth++;
1559280849Scy		return;
1560280849Scy	}
1561280849Scy#endif	/* AUTOKEY */
1562298695Sdelphij
1563280849Scy	peer->received++;
1564182007Sroberto	peer->flash &= ~PKT_TEST_MASK;
1565280849Scy	if (peer->flags & FLAG_XBOGUS) {
1566280849Scy		peer->flags &= ~FLAG_XBOGUS;
1567280849Scy		peer->flash |= TEST3;
1568280849Scy	}
1569132454Sroberto
1570132454Sroberto	/*
1571182007Sroberto	 * Next comes a rigorous schedule of timestamp checking. If the
1572280849Scy	 * transmit timestamp is zero, the server has not initialized in
1573280849Scy	 * interleaved modes or is horribly broken.
1574298695Sdelphij	 *
1575298695Sdelphij	 * A KoD packet we pay attention to cannot have a 0 transmit
1576298695Sdelphij	 * timestamp.
1577132454Sroberto	 */
1578182007Sroberto	if (L_ISZERO(&p_xmt)) {
1579280849Scy		peer->flash |= TEST3;			/* unsynch */
1580301247Sdelphij		if (STRATUM_UNSPEC == hisstratum) {	/* KoD packet */
1581298695Sdelphij			peer->bogusorg++;		/* for TEST2 or TEST3 */
1582298695Sdelphij			msyslog(LOG_INFO,
1583298695Sdelphij				"receive: Unexpected zero transmit timestamp in KoD from %s",
1584298695Sdelphij				ntoa(&peer->srcadr));
1585298695Sdelphij			return;
1586298695Sdelphij		}
1587132454Sroberto
1588132454Sroberto	/*
1589298695Sdelphij	 * 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	 */
1593280849Scy	} else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1594280849Scy		peer->flash |= TEST1;			/* duplicate */
1595182007Sroberto		peer->oldpkt++;
1596280849Scy		return;
1597132454Sroberto
1598132454Sroberto	/*
1599301247Sdelphij	 * If this is a broadcast mode packet, make sure hisstratum
1600301247Sdelphij	 * is appropriate.  Don't do anything else here - we wait to
1601301247Sdelphij	 * see if this is an interleave broadcast packet until after
1602301247Sdelphij	 * we've validated the MAC that SHOULD be provided.
1603301247Sdelphij	 *
1604301247Sdelphij	 * hisstratum should never be 0.
1605301247Sdelphij	 * If hisstratum is 15, then we'll advertise as UNSPEC but
1606301247Sdelphij	 * at least we'll be able to sync with the broadcast server.
1607132454Sroberto	 */
1608280849Scy	} else if (hismode == MODE_BROADCAST) {
1609301247Sdelphij		if (   0 == hisstratum
1610301247Sdelphij		    || STRATUM_UNSPEC <= hisstratum) {
1611301247Sdelphij			/* Is this a ++sys_declined or ??? */
1612301247Sdelphij			msyslog(LOG_INFO,
1613301247Sdelphij				"receive: Unexpected stratum (%d) in broadcast from %s",
1614301247Sdelphij				hisstratum, ntoa(&peer->srcadr));
1615280849Scy			return;
1616280849Scy		}
1617132454Sroberto
1618132454Sroberto	/*
1619298695Sdelphij	 * Basic KoD validation checking:
1620298695Sdelphij	 *
1621298695Sdelphij	 * KoD packets are a mixed-blessing.  Forged KoD packets
1622298695Sdelphij	 * are DoS attacks.  There are rare situations where we might
1623298695Sdelphij	 * get a valid KoD response, though.  Since KoD packets are
1624298695Sdelphij	 * a special case that complicate the checks we do next, we
1625298695Sdelphij	 * handle the basic KoD checks here.
1626298695Sdelphij	 *
1627298695Sdelphij	 * Note that we expect the incoming KoD packet to have its
1628298695Sdelphij	 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1629298695Sdelphij	 * that we have previously sent out.  Watch interleave mode.
1630298695Sdelphij	 */
1631301247Sdelphij	} else if (STRATUM_UNSPEC == hisstratum) {
1632298695Sdelphij		DEBUG_INSIST(!L_ISZERO(&p_xmt));
1633298695Sdelphij		if (   L_ISZERO(&p_org)		/* We checked p_xmt above */
1634298695Sdelphij		    || L_ISZERO(&p_rec)) {
1635298695Sdelphij			peer->bogusorg++;
1636298695Sdelphij			msyslog(LOG_INFO,
1637298695Sdelphij				"receive: KoD packet from %s has a zero org or rec timestamp.  Ignoring.",
1638298695Sdelphij				ntoa(&peer->srcadr));
1639298695Sdelphij			return;
1640298695Sdelphij		}
1641298695Sdelphij
1642298695Sdelphij		if (   !L_ISEQU(&p_xmt, &p_org)
1643298695Sdelphij		    || !L_ISEQU(&p_xmt, &p_rec)) {
1644298695Sdelphij			peer->bogusorg++;
1645298695Sdelphij			msyslog(LOG_INFO,
1646298695Sdelphij				"receive: KoD packet from %s has inconsistent xmt/org/rec timestamps.  Ignoring.",
1647298695Sdelphij				ntoa(&peer->srcadr));
1648298695Sdelphij			return;
1649298695Sdelphij		}
1650298695Sdelphij
1651298695Sdelphij		/* Be conservative */
1652298695Sdelphij		if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1653298695Sdelphij			peer->bogusorg++;
1654298695Sdelphij			msyslog(LOG_INFO,
1655298695Sdelphij				"receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1656298695Sdelphij				p_org.l_ui, p_org.l_uf,
1657298695Sdelphij				ntoa(&peer->srcadr),
1658298695Sdelphij				peer->aorg.l_ui, peer->aorg.l_uf);
1659298695Sdelphij			return;
1660298695Sdelphij		} else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1661298695Sdelphij			peer->bogusorg++;
1662298695Sdelphij			msyslog(LOG_INFO,
1663298695Sdelphij				"receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1664298695Sdelphij				p_org.l_ui, p_org.l_uf,
1665298695Sdelphij				ntoa(&peer->srcadr),
1666298695Sdelphij				peer->borg.l_ui, peer->borg.l_uf);
1667298695Sdelphij			return;
1668298695Sdelphij		}
1669309007Sdelphij
1670298695Sdelphij	/*
1671293423Sdelphij	 * Basic mode checks:
1672289764Sglebius	 *
1673294554Sdelphij	 * If there is no origin timestamp, it's either an initial packet
1674294554Sdelphij	 * or we've already received a response to our query.  Of course,
1675294554Sdelphij	 * should 'aorg' be all-zero because this really was the original
1676298695Sdelphij	 * transmit timestamp, we'll ignore this reply.  There is a window
1677298695Sdelphij	 * of one nanosecond once every 136 years' time where this is
1678298695Sdelphij	 * possible.  We currently ignore this situation.
1679293423Sdelphij	 *
1680293423Sdelphij	 * Otherwise, check for bogus packet in basic mode.
1681293423Sdelphij	 * If it is bogus, switch to interleaved mode and resynchronize,
1682293423Sdelphij	 * but only after confirming the packet is not bogus in
1683293423Sdelphij	 * symmetric interleaved mode.
1684293423Sdelphij	 *
1685289764Sglebius	 * This could also mean somebody is forging packets claiming to
1686289764Sglebius	 * be from us, attempting to cause our server to KoD us.
1687132454Sroberto	 */
1688280849Scy	} else if (peer->flip == 0) {
1689298695Sdelphij		INSIST(0 != hisstratum);
1690301247Sdelphij		INSIST(STRATUM_UNSPEC != hisstratum);
1691309007Sdelphij
1692298695Sdelphij		if (0) {
1693298695Sdelphij		} else if (L_ISZERO(&p_org)) {
1694309007Sdelphij			char *action;
1695309007Sdelphij
1696309007Sdelphij			L_CLR(&peer->aorg);
1697309007Sdelphij			/**/
1698309007Sdelphij			switch (hismode) {
1699309007Sdelphij			/* We allow 0org for: */
1700309007Sdelphij			    case UCHAR_MAX:
1701309007Sdelphij				action = "Allow";
1702309007Sdelphij				break;
1703309007Sdelphij			/* We disallow 0org for: */
1704309007Sdelphij			    case MODE_UNSPEC:
1705309007Sdelphij			    case MODE_ACTIVE:
1706309007Sdelphij			    case MODE_PASSIVE:
1707309007Sdelphij			    case MODE_CLIENT:
1708309007Sdelphij			    case MODE_SERVER:
1709309007Sdelphij			    case MODE_BROADCAST:
1710309007Sdelphij				action = "Drop";
1711309007Sdelphij				peer->bogusorg++;
1712309007Sdelphij				peer->flash |= TEST2;	/* bogus */
1713309007Sdelphij				break;
1714309007Sdelphij			    default:
1715309007Sdelphij				INSIST(!"receive(): impossible hismode");
1716309007Sdelphij				break;
1717309007Sdelphij			}
1718309007Sdelphij			/**/
1719298695Sdelphij			msyslog(LOG_INFO,
1720309007Sdelphij				"receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
1721309007Sdelphij				action, hm_str, ntoa(&peer->srcadr),
1722298695Sdelphij				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1723298695Sdelphij		} else if (!L_ISEQU(&p_org, &peer->aorg)) {
1724298695Sdelphij			/* are there cases here where we should bail? */
1725298695Sdelphij			/* Should we set TEST2 if we decide to try xleave? */
1726280849Scy			peer->bogusorg++;
1727280849Scy			peer->flash |= TEST2;	/* bogus */
1728289764Sglebius			msyslog(LOG_INFO,
1729298695Sdelphij				"receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1730293423Sdelphij				ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1731298695Sdelphij				peer->aorg.l_ui, peer->aorg.l_uf,
1732298695Sdelphij				hm_str, ntoa(&peer->srcadr),
1733293423Sdelphij				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1734289764Sglebius			if (  !L_ISZERO(&peer->dst)
1735289764Sglebius			    && L_ISEQU(&p_org, &peer->dst)) {
1736293423Sdelphij				/* Might be the start of an interleave */
1737298695Sdelphij				if (dynamic_interleave) {
1738298695Sdelphij					peer->flip = 1;
1739298695Sdelphij					report_event(PEVNT_XLEAVE, peer, NULL);
1740298695Sdelphij				} else {
1741298695Sdelphij					msyslog(LOG_INFO,
1742298695Sdelphij						"receive: Dynamic interleave from %s@%s denied",
1743298695Sdelphij						hm_str, ntoa(&peer->srcadr));
1744298695Sdelphij				}
1745182007Sroberto			}
1746280849Scy		} else {
1747280849Scy			L_CLR(&peer->aorg);
1748182007Sroberto		}
1749280849Scy
1750280849Scy	/*
1751280849Scy	 * Check for valid nonzero timestamp fields.
1752280849Scy	 */
1753301247Sdelphij	} else if (   L_ISZERO(&p_org)
1754301247Sdelphij		   || L_ISZERO(&p_rec)
1755301247Sdelphij		   || L_ISZERO(&peer->dst)) {
1756280849Scy		peer->flash |= TEST3;		/* unsynch */
1757280849Scy
1758280849Scy	/*
1759280849Scy	 * Check for bogus packet in interleaved symmetric mode. This
1760280849Scy	 * can happen if a packet is lost, duplicated or crossed. If
1761280849Scy	 * found, flip and resynchronize.
1762280849Scy	 */
1763289764Sglebius	} else if (   !L_ISZERO(&peer->dst)
1764289764Sglebius		   && !L_ISEQU(&p_org, &peer->dst)) {
1765280849Scy		peer->bogusorg++;
1766280849Scy		peer->flags |= FLAG_XBOGUS;
1767280849Scy		peer->flash |= TEST2;		/* bogus */
1768289764Sglebius		return; /* Bogus packet, we are done */
1769182007Sroberto	}
1770132454Sroberto
1771301247Sdelphij	/**/
1772301247Sdelphij
1773132454Sroberto	/*
1774280849Scy	 * If this is a crypto_NAK, the server cannot authenticate a
1775280849Scy	 * client packet. The server might have just changed keys. Clear
1776280849Scy	 * the association and restart the protocol.
1777280849Scy	 */
1778298695Sdelphij	if (crypto_nak_test == VALIDNAK) {
1779280849Scy		report_event(PEVNT_AUTH, peer, "crypto_NAK");
1780280849Scy		peer->flash |= TEST5;		/* bad auth */
1781280849Scy		peer->badauth++;
1782280849Scy		if (peer->flags & FLAG_PREEMPT) {
1783294554Sdelphij			if (unpeer_crypto_nak_early) {
1784294554Sdelphij				unpeer(peer);
1785294554Sdelphij			}
1786280849Scy			return;
1787280849Scy		}
1788280849Scy#ifdef AUTOKEY
1789301247Sdelphij		if (peer->crypto) {
1790280849Scy			peer_clear(peer, "AUTH");
1791301247Sdelphij		}
1792280849Scy#endif	/* AUTOKEY */
1793280849Scy		return;
1794182007Sroberto
1795282408Scy	/*
1796282408Scy	 * If the digest fails or it's missing for authenticated
1797282408Scy	 * associations, the client cannot authenticate a server
1798280849Scy	 * reply to a client packet previously sent. The loopback check
1799280849Scy	 * is designed to avoid a bait-and-switch attack, which was
1800280849Scy	 * possible in past versions. If symmetric modes, return a
1801280849Scy	 * crypto-NAK. The peer should restart the protocol.
1802182007Sroberto	 */
1803282408Scy	} else if (!AUTH(peer->keyid || has_mac ||
1804282408Scy			 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1805301247Sdelphij
1806301247Sdelphij		if (peer->flash & PKT_TEST_MASK) {
1807301247Sdelphij			msyslog(LOG_INFO,
1808301247Sdelphij				"receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
1809301247Sdelphij				ntoa(&peer->srcadr));
1810301247Sdelphij			return;
1811301247Sdelphij		}
1812301247Sdelphij
1813280849Scy		report_event(PEVNT_AUTH, peer, "digest");
1814280849Scy		peer->flash |= TEST5;		/* bad auth */
1815280849Scy		peer->badauth++;
1816289764Sglebius		if (   has_mac
1817301247Sdelphij		    && (   hismode == MODE_ACTIVE
1818301247Sdelphij			|| hismode == MODE_PASSIVE))
1819132454Sroberto			fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1820280849Scy		if (peer->flags & FLAG_PREEMPT) {
1821294554Sdelphij			if (unpeer_digest_early) {
1822294554Sdelphij				unpeer(peer);
1823294554Sdelphij			}
1824280849Scy		}
1825280849Scy#ifdef AUTOKEY
1826301247Sdelphij		else if (peer_clear_digest_early && peer->crypto) {
1827280849Scy			peer_clear(peer, "AUTH");
1828301247Sdelphij		}
1829280849Scy#endif	/* AUTOKEY */
1830280849Scy		return;
183154359Sroberto	}
183254359Sroberto
1833182007Sroberto	/*
1834301247Sdelphij	 * For broadcast packets:
1835301247Sdelphij	 *
1836301247Sdelphij	 * HMS: This next line never made much sense to me, even
1837301247Sdelphij	 * when it was up higher:
1838301247Sdelphij	 *   If an initial volley, bail out now and let the
1839301247Sdelphij	 *   client do its stuff.
1840301247Sdelphij	 *
1841301247Sdelphij	 * If the packet has not failed authentication, then
1842301247Sdelphij	 * - if the origin timestamp is nonzero this is an
1843301247Sdelphij	 *   interleaved broadcast, so restart the protocol.
1844301247Sdelphij	 * - else, this is not an interleaved broadcast packet.
1845282408Scy	 */
1846301247Sdelphij	if (hismode == MODE_BROADCAST) {
1847301247Sdelphij		if (   is_authentic == AUTH_OK
1848301247Sdelphij		    || is_authentic == AUTH_NONE) {
1849301247Sdelphij			if (!L_ISZERO(&p_org)) {
1850301247Sdelphij				if (!(peer->flags & FLAG_XB)) {
1851301247Sdelphij					msyslog(LOG_INFO,
1852301247Sdelphij						"receive: Broadcast server at %s is in interleave mode",
1853301247Sdelphij						ntoa(&peer->srcadr));
1854301247Sdelphij					peer->flags |= FLAG_XB;
1855301247Sdelphij					peer->aorg = p_xmt;
1856301247Sdelphij					peer->borg = rbufp->recv_time;
1857301247Sdelphij					report_event(PEVNT_XLEAVE, peer, NULL);
1858301247Sdelphij					return;
1859301247Sdelphij				}
1860301247Sdelphij			} else if (peer->flags & FLAG_XB) {
1861301247Sdelphij				msyslog(LOG_INFO,
1862301247Sdelphij					"receive: Broadcast server at %s is no longer in interleave mode",
1863301247Sdelphij					ntoa(&peer->srcadr));
1864301247Sdelphij				peer->flags &= ~FLAG_XB;
1865301247Sdelphij			}
1866301247Sdelphij		} else {
1867301247Sdelphij			msyslog(LOG_INFO,
1868301247Sdelphij				"receive: Bad broadcast auth (%d) from %s",
1869301247Sdelphij				is_authentic, ntoa(&peer->srcadr));
1870301247Sdelphij		}
1871309007Sdelphij
1872309007Sdelphij		/*
1873309007Sdelphij		 * Now that we know the packet is correctly authenticated,
1874309007Sdelphij		 * update peer->bxmt.
1875309007Sdelphij		 */
1876309007Sdelphij		peer->bxmt = p_xmt;
1877301247Sdelphij	}
1878301247Sdelphij
1879301247Sdelphij
1880301247Sdelphij	/*
1881301247Sdelphij	** Update the state variables.
1882301247Sdelphij	*/
1883282408Scy	if (peer->flip == 0) {
1884282408Scy		if (hismode != MODE_BROADCAST)
1885282408Scy			peer->rec = p_xmt;
1886282408Scy		peer->dst = rbufp->recv_time;
1887282408Scy	}
1888282408Scy	peer->xmt = p_xmt;
1889282408Scy
1890282408Scy	/*
1891280849Scy	 * Set the peer ppoll to the maximum of the packet ppoll and the
1892280849Scy	 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1893280849Scy	 * this maximum and advance the headway to give the sender some
1894280849Scy	 * headroom. Very intricate.
1895280849Scy	 */
1896289764Sglebius
1897289764Sglebius	/*
1898289764Sglebius	 * Check for any kiss codes. Note this is only used when a server
1899289764Sglebius	 * responds to a packet request
1900289764Sglebius	 */
1901289764Sglebius
1902289764Sglebius	kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1903289764Sglebius
1904289764Sglebius	/*
1905289764Sglebius	 * Check to see if this is a RATE Kiss Code
1906289764Sglebius	 * Currently this kiss code will accept whatever poll
1907289764Sglebius	 * rate that the server sends
1908289764Sglebius	 */
1909280849Scy	peer->ppoll = max(peer->minpoll, pkt->ppoll);
1910289764Sglebius	if (kissCode == RATEKISS) {
1911289764Sglebius		peer->selbroken++;	/* Increment the KoD count */
1912280849Scy		report_event(PEVNT_RATE, peer, NULL);
1913280849Scy		if (pkt->ppoll > peer->minpoll)
1914280849Scy			peer->minpoll = peer->ppoll;
1915280849Scy		peer->burst = peer->retry = 0;
1916280849Scy		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1917280849Scy		poll_update(peer, pkt->ppoll);
1918280849Scy		return;				/* kiss-o'-death */
1919280849Scy	}
1920289764Sglebius	if (kissCode != NOKISS) {
1921289764Sglebius		peer->selbroken++;	/* Increment the KoD count */
1922289764Sglebius		return;		/* Drop any other kiss code packets */
1923289764Sglebius	}
1924280849Scy
1925301247Sdelphij
1926294554Sdelphij	/*
1927301247Sdelphij	 * XXX
1928301247Sdelphij	 */
1929301247Sdelphij
1930301247Sdelphij
1931301247Sdelphij	/*
1932294554Sdelphij	 * If:
1933294554Sdelphij	 *	- this is a *cast (uni-, broad-, or m-) server packet
1934298695Sdelphij	 *	- and it's symmetric-key authenticated
1935294554Sdelphij	 * then see if the sender's IP is trusted for this keyid.
1936294554Sdelphij	 * If it is, great - nothing special to do here.
1937294554Sdelphij	 * Otherwise, we should report and bail.
1938298695Sdelphij	 *
1939298695Sdelphij	 * Autokey-authenticated packets are accepted.
1940294554Sdelphij	 */
1941289764Sglebius
1942294554Sdelphij	switch (hismode) {
1943294554Sdelphij	    case MODE_SERVER:		/* server mode */
1944294554Sdelphij	    case MODE_BROADCAST:	/* broadcast mode */
1945294554Sdelphij	    case MODE_ACTIVE:		/* symmetric active mode */
1946298695Sdelphij	    case MODE_PASSIVE:		/* symmetric passive mode */
1947294554Sdelphij		if (   is_authentic == AUTH_OK
1948298695Sdelphij		    && skeyid
1949298695Sdelphij		    && skeyid <= NTP_MAXKEY
1950294554Sdelphij		    && !authistrustedip(skeyid, &peer->srcadr)) {
1951294554Sdelphij			report_event(PEVNT_AUTH, peer, "authIP");
1952294554Sdelphij			peer->badauth++;
1953294554Sdelphij			return;
1954294554Sdelphij		}
1955309007Sdelphij		break;
1956294554Sdelphij
1957294554Sdelphij	    case MODE_CLIENT:		/* client mode */
1958294554Sdelphij#if 0		/* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
1959294554Sdelphij	    case MODE_CONTROL:		/* control mode */
1960294554Sdelphij#endif
1961294554Sdelphij	    case MODE_PRIVATE:		/* private mode */
1962294554Sdelphij	    case MODE_BCLIENT:		/* broadcast client mode */
1963309007Sdelphij		break;
1964298695Sdelphij
1965298695Sdelphij	    case MODE_UNSPEC:		/* unspecified (old version) */
1966294554Sdelphij	    default:
1967298695Sdelphij		msyslog(LOG_INFO,
1968298695Sdelphij			"receive: Unexpected mode (%d) in packet from %s",
1969298695Sdelphij			hismode, ntoa(&peer->srcadr));
1970309007Sdelphij		break;
1971294554Sdelphij	}
1972294554Sdelphij
1973294554Sdelphij
1974280849Scy	/*
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;
1979294554Sdelphij	peer->timelastrec = current_time;
1980182007Sroberto	if (is_authentic == AUTH_OK)
1981182007Sroberto		peer->flags |= FLAG_AUTHENTIC;
1982182007Sroberto	else
1983182007Sroberto		peer->flags &= ~FLAG_AUTHENTIC;
1984280849Scy
1985280849Scy#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
2004280849Scy	 *    match, sit the dance and call for new autokey values.
2005182007Sroberto	 *
2006280849Scy	 * In case of crypto error, fire the orchestra, stop dancing and
2007280849Scy	 * restart the protocol.
200854359Sroberto	 */
2009280849Scy	if (peer->flags & FLAG_SKEY) {
2010280849Scy		/*
2011280849Scy		 * Decrement remaining autokey hashes. This isn't
2012280849Scy		 * perfect if a packet is lost, but results in no harm.
2013280849Scy		 */
2014280849Scy		ap = (struct autokey *)peer->recval.ptr;
2015280849Scy		if (ap != NULL) {
2016280849Scy			if (ap->seq > 0)
2017280849Scy				ap->seq--;
2018280849Scy		}
2019182007Sroberto		peer->flash |= TEST8;
2020132454Sroberto		rval = crypto_recv(peer, rbufp);
2021280849Scy		if (rval == XEVNT_OK) {
2022280849Scy			peer->unreach = 0;
2023280849Scy		} else {
2024280849Scy			if (rval == XEVNT_ERR) {
2025280849Scy				report_event(PEVNT_RESTART, peer,
2026280849Scy				    "crypto error");
2027280849Scy				peer_clear(peer, "CRYP");
2028280849Scy				peer->flash |= TEST9;	/* bad crypt */
2029294554Sdelphij				if (peer->flags & FLAG_PREEMPT) {
2030294554Sdelphij					if (unpeer_crypto_early) {
2031294554Sdelphij						unpeer(peer);
2032294554Sdelphij					}
2033294554Sdelphij				}
2034280849Scy			}
2035182007Sroberto			return;
2036280849Scy		}
2037132454Sroberto
2038280849Scy		/*
2039280849Scy		 * If server mode, verify the receive key ID matches
2040280849Scy		 * the transmit key ID.
2041280849Scy		 */
2042280849Scy		if (hismode == MODE_SERVER) {
204382505Sroberto			if (skeyid == peer->keyid)
2044182007Sroberto				peer->flash &= ~TEST8;
2045280849Scy
2046280849Scy		/*
2047280849Scy		 * If an extension field is present, verify only that it
2048280849Scy		 * has been correctly signed. We don't need a sequence
2049280849Scy		 * check here, but the sequence continues.
2050280849Scy		 */
2051182007Sroberto		} else if (!(peer->flash & TEST8)) {
205282505Sroberto			peer->pkeyid = skeyid;
2053280849Scy
2054280849Scy		/*
2055280849Scy		 * Now the fun part. Here, skeyid is the current ID in
2056280849Scy		 * the packet, pkeyid is the ID in the last packet and
2057280849Scy		 * tkeyid is the hash of skeyid. If the autokey values
2058280849Scy		 * have not been received, this is an automatic error.
2059280849Scy		 * If so, check that the tkeyid matches pkeyid. If not,
2060280849Scy		 * hash tkeyid and try again. If the number of hashes
2061280849Scy		 * exceeds the number remaining in the sequence, declare
2062280849Scy		 * a successful failure and refresh the autokey values.
2063280849Scy		 */
2064280849Scy		} else if (ap != NULL) {
206582505Sroberto			int i;
206682505Sroberto
206782505Sroberto			for (i = 0; ; i++) {
2068289764Sglebius				if (   tkeyid == peer->pkeyid
2069289764Sglebius				    || tkeyid == ap->key) {
2070182007Sroberto					peer->flash &= ~TEST8;
207182505Sroberto					peer->pkeyid = skeyid;
2072280849Scy					ap->seq -= i;
207382505Sroberto					break;
207482505Sroberto				}
2075280849Scy				if (i > ap->seq) {
2076280849Scy					peer->crypto &=
2077280849Scy					    ~CRYPTO_FLAG_AUTO;
207882505Sroberto					break;
2079280849Scy				}
208054359Sroberto				tkeyid = session_key(
208182505Sroberto				    &rbufp->recv_srcadr, dstadr_sin,
208282505Sroberto				    tkeyid, pkeyid, 0);
208354359Sroberto			}
2084280849Scy			if (peer->flash & TEST8)
2085280849Scy				report_event(PEVNT_AUTH, peer, "keylist");
208654359Sroberto		}
2087182007Sroberto		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2088280849Scy			peer->flash |= TEST8;	/* bad autokey */
208982505Sroberto
209082505Sroberto		/*
2091280849Scy		 * The maximum lifetime of the protocol is about one
2092280849Scy		 * week before restarting the Autokey protocol to
2093280849Scy		 * refresh certificates and leapseconds values.
209482505Sroberto		 */
2095280849Scy		if (current_time > peer->refresh) {
2096280849Scy			report_event(PEVNT_RESTART, peer,
2097280849Scy			    "crypto refresh");
2098280849Scy			peer_clear(peer, "TIME");
2099280849Scy			return;
2100132454Sroberto		}
210154359Sroberto	}
2102280849Scy#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	 */
2109280849Scy	process_packet(peer, pkt, rbufp->recv_length);
2110182007Sroberto
2111182007Sroberto	/*
2112280849Scy	 * In interleaved mode update the state variables. Also adjust the
2113280849Scy	 * transmit phase to avoid crossover.
2114182007Sroberto	 */
2115280849Scy	if (peer->flip != 0) {
2116280849Scy		peer->rec = p_rec;
2117280849Scy		peer->dst = rbufp->recv_time;
2118280849Scy		if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2119280849Scy		    peer->hpoll)) / 2)
2120280849Scy			peer->nextdate++;
2121280849Scy		else
2122280849Scy			peer->nextdate--;
2123182007Sroberto	}
212454359Sroberto}
212554359Sroberto
212654359Sroberto
212754359Sroberto/*
2128301247Sdelphij * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2129301247Sdelphij *	Or almost, at least.  If we're in here we have a reasonable
2130301247Sdelphij *	expectation that we will be having a long term
213154359Sroberto *	relationship with this host.
213254359Sroberto */
213382505Srobertovoid
213454359Srobertoprocess_packet(
213554359Sroberto	register struct peer *peer,
2136280849Scy	register struct pkt *pkt,
2137280849Scy	u_int	len
213854359Sroberto	)
213954359Sroberto{
2140182007Sroberto	double	t34, t21;
2141132454Sroberto	double	p_offset, p_del, p_disp;
2142280849Scy	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
2143280849Scy	u_char	pmode, pleap, pversion, pstratum;
2144280849Scy	char	statstr[NTP_MAXSTRLEN];
2145280849Scy#ifdef ASSYM
2146280849Scy	int	itemp;
2147280849Scy	double	etemp, ftemp, td;
2148280849Scy#endif /* ASSYM */
214954359Sroberto
2150301247Sdelphij#if 0
215154359Sroberto	sys_processed++;
215254359Sroberto	peer->processed++;
2153301247Sdelphij#endif
215454359Sroberto	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2155280849Scy	p_offset = 0;
2156280849Scy	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
215754359Sroberto	NTOHL_FP(&pkt->reftime, &p_reftime);
2158280849Scy	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);
2163280849Scy	pversion = PKT_VERSION(pkt->li_vn_mode);
2164132454Sroberto	pstratum = PKT_TO_STRATUM(pkt->stratum);
216554359Sroberto
2166301247Sdelphij	/**/
2167301247Sdelphij
2168301247Sdelphij	/**/
2169301247Sdelphij
217054359Sroberto	/*
2171301247Sdelphij	 * Verify the server is synchronized; that is, the leap bits,
2172301247Sdelphij	 * stratum and root distance are valid.
2173301247Sdelphij	 */
2174301247Sdelphij	if (   pleap == LEAP_NOTINSYNC		/* test 6 */
2175301247Sdelphij	    || pstratum < sys_floor || pstratum >= sys_ceiling)
2176301247Sdelphij		peer->flash |= TEST6;		/* bad synch or strat */
2177301247Sdelphij	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
2178301247Sdelphij		peer->flash |= TEST7;		/* bad header */
2179301247Sdelphij
2180301247Sdelphij	/*
2181301247Sdelphij	 * If any tests fail at this point, the packet is discarded.
2182301247Sdelphij	 * Note that some flashers may have already been set in the
2183301247Sdelphij	 * receive() routine.
2184301247Sdelphij	 */
2185301247Sdelphij	if (peer->flash & PKT_TEST_MASK) {
2186301247Sdelphij		peer->seldisptoolarge++;
2187301247Sdelphij		DPRINTF(1, ("packet: flash header %04x\n",
2188301247Sdelphij			    peer->flash));
2189301247Sdelphij		return;
2190301247Sdelphij	}
2191301247Sdelphij
2192301247Sdelphij	/**/
2193301247Sdelphij
2194301247Sdelphij#if 1
2195301247Sdelphij	sys_processed++;
2196301247Sdelphij	peer->processed++;
2197301247Sdelphij#endif
2198301247Sdelphij
2199301247Sdelphij	/*
2200280849Scy	 * Capture the header values in the client/peer association..
220154359Sroberto	 */
2202280849Scy	record_raw_stats(&peer->srcadr, peer->dstadr ?
2203280849Scy	    &peer->dstadr->sin : NULL,
2204280849Scy	    &p_org, &p_rec, &p_xmt, &peer->dst,
2205280849Scy	    pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2206280849Scy	    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;
2212280849Scy	peer->rootdisp = p_disp;
2213182007Sroberto	peer->refid = pkt->refid;		/* network byte order */
2214182007Sroberto	peer->reftime = p_reftime;
221582505Sroberto
221682505Sroberto	/*
2217280849Scy	 * First, if either burst mode is armed, enable the burst.
2218280849Scy	 * Compute the headway for the next packet and delay if
2219280849Scy	 * necessary to avoid exceeding the threshold.
222082505Sroberto	 */
2221280849Scy	if (peer->retry > 0) {
2222280849Scy		peer->retry = 0;
2223280849Scy		if (peer->reach)
2224280849Scy			peer->burst = min(1 << (peer->hpoll -
2225280849Scy			    peer->minpoll), NTP_SHIFT) - 1;
2226280849Scy		else
2227280849Scy			peer->burst = NTP_IBURST - 1;
2228280849Scy		if (peer->burst > 0)
2229280849Scy			peer->nextdate = current_time;
2230280849Scy	}
2231280849Scy	poll_update(peer, peer->hpoll);
2232280849Scy
2233301247Sdelphij	/**/
2234132454Sroberto
2235132454Sroberto	/*
2236280849Scy	 * If the peer was previously unreachable, raise a trap. In any
2237280849Scy	 * case, mark it reachable.
2238282408Scy	 */
2239280849Scy	if (!peer->reach) {
2240280849Scy		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
2250280849Scy	 * 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-
2265280849Scy	 * double arithmetic. This preserves the accuracy while
2266280849Scy	 * retaining the 68-year span.
2267182007Sroberto	 *
2268280849Scy	 * There are three interleaving schemes, basic, interleaved
2269280849Scy	 * symmetric and interleaved broadcast. The timestamps are
2270280849Scy	 * idioscyncratically different. See the onwire briefing/white
2271280849Scy	 * paper at www.eecis.udel.edu/~mills for details.
2272280849Scy	 *
2273280849Scy	 * Interleaved symmetric mode
2274280849Scy	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2275280849Scy	 * t4 = peer->dst
227654359Sroberto	 */
2277280849Scy	if (peer->flip != 0) {
2278280849Scy		ci = p_xmt;				/* t3 - t4 */
2279280849Scy		L_SUB(&ci, &peer->dst);
2280280849Scy		LFPTOD(&ci, t34);
2281280849Scy		ci = p_rec;				/* t2 - t1 */
2282280849Scy		if (peer->flip > 0)
2283280849Scy			L_SUB(&ci, &peer->borg);
2284280849Scy		else
2285280849Scy			L_SUB(&ci, &peer->aorg);
2286280849Scy		LFPTOD(&ci, t21);
2287280849Scy		p_del = t21 - t34;
2288280849Scy		p_offset = (t21 + t34) / 2.;
2289280849Scy		if (p_del < 0 || p_del > 1.) {
2290280849Scy			snprintf(statstr, sizeof(statstr),
2291280849Scy			    "t21 %.6f t34 %.6f", t21, t34);
2292280849Scy			report_event(PEVNT_XERR, peer, statstr);
2293280849Scy			return;
2294280849Scy		}
229554359Sroberto
229654359Sroberto	/*
2297280849Scy	 * Broadcast modes
229854359Sroberto	 */
2299280849Scy	} else if (peer->pmode == MODE_BROADCAST) {
2300280849Scy
2301280849Scy		/*
2302280849Scy		 * Interleaved broadcast mode. Use interleaved timestamps.
2303280849Scy		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2304280849Scy		 */
2305282408Scy		if (peer->flags & FLAG_XB) {
2306282408Scy			ci = p_org;			/* delay */
2307280849Scy			L_SUB(&ci, &peer->aorg);
2308280849Scy			LFPTOD(&ci, t34);
2309280849Scy			ci = p_org;			/* t2 - t1 */
2310280849Scy			L_SUB(&ci, &peer->borg);
2311280849Scy			LFPTOD(&ci, t21);
2312280849Scy			peer->aorg = p_xmt;
2313280849Scy			peer->borg = peer->dst;
2314280849Scy			if (t34 < 0 || t34 > 1.) {
2315298695Sdelphij				/* drop all if in the initial volley */
2316298695Sdelphij				if (FLAG_BC_VOL & peer->flags)
2317298695Sdelphij					goto bcc_init_volley_fail;
2318280849Scy				snprintf(statstr, sizeof(statstr),
2319280849Scy				    "offset %.6f delay %.6f", t21, t34);
2320280849Scy				report_event(PEVNT_XERR, peer, statstr);
232182505Sroberto				return;
2322280849Scy			}
2323280849Scy			p_offset = t21;
2324280849Scy			peer->xleave = t34;
232554359Sroberto
2326280849Scy		/*
2327280849Scy		 * Basic broadcast - use direct timestamps.
2328280849Scy		 * t3 = p_xmt, t4 = peer->dst
2329280849Scy		 */
2330280849Scy		} else {
2331280849Scy			ci = p_xmt;		/* t3 - t4 */
2332280849Scy			L_SUB(&ci, &peer->dst);
2333280849Scy			LFPTOD(&ci, t34);
2334280849Scy			p_offset = t34;
233554359Sroberto		}
2336280849Scy
2337280849Scy		/*
2338280849Scy		 * When calibration is complete and the clock is
2339280849Scy		 * synchronized, the bias is calculated as the difference
2340280849Scy		 * between the unicast timestamp and the broadcast
2341280849Scy		 * timestamp. This works for both basic and interleaved
2342280849Scy		 * modes.
2343298695Sdelphij		 * [Bug 3031] Don't keep this peer when the delay
2344298695Sdelphij		 * calculation gives reason to suspect clock steps.
2345298695Sdelphij		 * This is assumed for delays > 50ms.
2346280849Scy		 */
2347280849Scy		if (FLAG_BC_VOL & peer->flags) {
2348280849Scy			peer->flags &= ~FLAG_BC_VOL;
2349280849Scy			peer->delay = fabs(peer->offset - p_offset) * 2;
2350298695Sdelphij			DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2351298695Sdelphij				peer->delay));
2352298695Sdelphij			if (peer->delay > fabs(sys_bdelay)) {
2353298695Sdelphij		bcc_init_volley_fail:
2354298695Sdelphij				DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2355298695Sdelphij				unpeer(peer);
2356298695Sdelphij				return;
2357298695Sdelphij			}
2358280849Scy		}
2359298695Sdelphij		peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
236054359Sroberto		p_del = peer->delay;
2361280849Scy		p_offset += p_del / 2;
2362280849Scy
2363280849Scy
2364280849Scy	/*
2365280849Scy	 * Basic mode, otherwise known as the old fashioned way.
2366280849Scy	 *
2367280849Scy	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2368280849Scy	 */
236954359Sroberto	} else {
2370280849Scy		ci = p_xmt;				/* t3 - t4 */
2371280849Scy		L_SUB(&ci, &peer->dst);
2372280849Scy		LFPTOD(&ci, t34);
2373280849Scy		ci = p_rec;				/* t2 - t1 */
2374280849Scy		L_SUB(&ci, &p_org);
2375280849Scy		LFPTOD(&ci, t21);
2376280849Scy		p_del = fabs(t21 - t34);
2377182007Sroberto		p_offset = (t21 + t34) / 2.;
237854359Sroberto	}
237982505Sroberto	p_del = max(p_del, LOGTOD(sys_precision));
2380280849Scy	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2381280849Scy	    clock_phi * p_del;
2382280849Scy
2383280849Scy#if ASSYM
2384280849Scy	/*
2385280849Scy	 * This code calculates the outbound and inbound data rates by
2386280849Scy	 * measuring the differences between timestamps at different
2387280849Scy	 * packet lengths. This is helpful in cases of large asymmetric
2388280849Scy	 * delays commonly experienced on deep space communication
2389280849Scy	 * links.
2390280849Scy	 */
2391280849Scy	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2392280849Scy		itemp = peer->t21_bytes - peer->t21_last;
2393280849Scy		if (itemp > 25) {
2394280849Scy			etemp = t21 - peer->t21;
2395280849Scy			if (fabs(etemp) > 1e-6) {
2396280849Scy				ftemp = itemp / etemp;
2397280849Scy				if (ftemp > 1000.)
2398280849Scy					peer->r21 = ftemp;
2399280849Scy			}
2400280849Scy		}
2401280849Scy		itemp = len - peer->t34_bytes;
2402280849Scy		if (itemp > 25) {
2403280849Scy			etemp = -t34 - peer->t34;
2404280849Scy			if (fabs(etemp) > 1e-6) {
2405280849Scy				ftemp = itemp / etemp;
2406280849Scy				if (ftemp > 1000.)
2407280849Scy					peer->r34 = ftemp;
2408280849Scy			}
2409280849Scy		}
2410280849Scy	}
2411280849Scy
2412280849Scy	/*
2413280849Scy	 * The following section compensates for different data rates on
2414280849Scy	 * the outbound (d21) and inbound (t34) directions. To do this,
2415280849Scy	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2416280849Scy	 * the roundtrip delay. Then it calculates the correction as a
2417280849Scy	 * fraction of d.
2418280849Scy	 */
2419293423Sdelphij	peer->t21 = t21;
2420280849Scy	peer->t21_last = peer->t21_bytes;
2421280849Scy	peer->t34 = -t34;
2422280849Scy	peer->t34_bytes = len;
2423293423Sdelphij	DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2424293423Sdelphij		    peer->t21_bytes, peer->t34, peer->t34_bytes));
2425280849Scy	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2426280849Scy		if (peer->pmode != MODE_BROADCAST)
2427280849Scy			td = (peer->r34 / (peer->r21 + peer->r34) -
2428280849Scy			    .5) * p_del;
2429280849Scy		else
2430280849Scy			td = 0;
2431280849Scy
2432280849Scy		/*
2433293423Sdelphij		 * Unfortunately, in many cases the errors are
2434280849Scy		 * unacceptable, so for the present the rates are not
2435280849Scy		 * used. In future, we might find conditions where the
2436280849Scy		 * calculations are useful, so this should be considered
2437280849Scy		 * a work in progress.
2438280849Scy		 */
2439280849Scy		t21 -= td;
2440280849Scy		t34 -= td;
2441293423Sdelphij		DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2442280849Scy			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2443293423Sdelphij			    td));
2444282408Scy	}
2445280849Scy#endif /* ASSYM */
2446280849Scy
2447280849Scy	/*
2448280849Scy	 * That was awesome. Now hand off to the clock filter.
2449280849Scy	 */
2450280849Scy	clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2451280849Scy
2452280849Scy	/*
2453280849Scy	 * If we are in broadcast calibrate mode, return to broadcast
2454280849Scy	 * client mode when the client is fit and the autokey dance is
2455280849Scy	 * complete.
2456280849Scy	 */
2457289764Sglebius	if (   (FLAG_BC_VOL & peer->flags)
2458289764Sglebius	    && MODE_CLIENT == peer->hmode
2459289764Sglebius	    && !(TEST11 & peer_unfit(peer))) {	/* distance exceeded */
2460280849Scy#ifdef AUTOKEY
2461280849Scy		if (peer->flags & FLAG_SKEY) {
2462280849Scy			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2463280849Scy				peer->hmode = MODE_BCLIENT;
2464280849Scy		} else {
2465280849Scy			peer->hmode = MODE_BCLIENT;
2466280849Scy		}
2467280849Scy#else	/* !AUTOKEY follows */
2468280849Scy		peer->hmode = MODE_BCLIENT;
2469280849Scy#endif	/* !AUTOKEY */
2470280849Scy	}
247154359Sroberto}
247254359Sroberto
247354359Sroberto
247454359Sroberto/*
247554359Sroberto * clock_update - Called at system process update intervals.
247654359Sroberto */
247754359Srobertostatic void
2478280849Scyclock_update(
2479280849Scy	struct peer *peer	/* peer structure pointer */
2480280849Scy	)
248154359Sroberto{
2482182007Sroberto	double	dtemp;
2483280849Scy	l_fp	now;
2484280849Scy#ifdef HAVE_LIBSCF_H
2485280849Scy	char	*fmri;
2486280849Scy#endif /* HAVE_LIBSCF_H */
248754359Sroberto
248854359Sroberto	/*
2489280849Scy	 * Update the system state variables. We do this very carefully,
2490280849Scy	 * as the poll interval might need to be clamped differently.
249154359Sroberto	 */
2492280849Scy	sys_peer = peer;
2493280849Scy	sys_epoch = peer->epoch;
2494280849Scy	if (sys_poll < peer->minpoll)
2495280849Scy		sys_poll = peer->minpoll;
2496280849Scy	if (sys_poll > peer->maxpoll)
2497280849Scy		sys_poll = peer->maxpoll;
2498280849Scy	poll_update(peer, sys_poll);
2499280849Scy	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2500289764Sglebius	if (   peer->stratum == STRATUM_REFCLOCK
2501289764Sglebius	    || peer->stratum == STRATUM_UNSPEC)
2502280849Scy		sys_refid = peer->refid;
2503280849Scy	else
2504280849Scy		sys_refid = addr2refid(&peer->srcadr);
2505280849Scy	/*
2506280849Scy	 * Root Dispersion (E) is defined (in RFC 5905) as:
2507280849Scy	 *
2508280849Scy	 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2509280849Scy	 *
2510280849Scy	 * where:
2511280849Scy	 *  p.epsilon_r is the PollProc's root dispersion
2512280849Scy	 *  p.epsilon   is the PollProc's dispersion
2513280849Scy	 *  p.psi       is the PollProc's jitter
2514280849Scy	 *  THETA       is the combined offset
2515280849Scy	 *
2516280849Scy	 * NB: Think Hard about where these numbers come from and
2517280849Scy	 * what they mean.  When did peer->update happen?  Has anything
2518280849Scy	 * interesting happened since then?  What values are the most
2519280849Scy	 * defensible?  Why?
2520280849Scy	 *
2521280849Scy	 * DLM thinks this equation is probably the best of all worse choices.
2522280849Scy	 */
2523280849Scy	dtemp	= peer->rootdisp
2524280849Scy		+ peer->disp
2525280849Scy		+ sys_jitter
2526280849Scy		+ clock_phi * (current_time - peer->update)
2527280849Scy		+ fabs(sys_offset);
2528182007Sroberto
2529280849Scy	if (dtemp > sys_mindisp)
2530280849Scy		sys_rootdisp = dtemp;
2531280849Scy	else
2532280849Scy		sys_rootdisp = sys_mindisp;
2533280849Scy	sys_rootdelay = peer->delay + peer->rootdelay;
2534280849Scy	sys_reftime = peer->dst;
2535280849Scy
2536293423Sdelphij	DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2537293423Sdelphij		    current_time, peer->epoch, peer->associd));
253854359Sroberto
253982505Sroberto	/*
2540280849Scy	 * Comes now the moment of truth. Crank the clock discipline and
2541280849Scy	 * see what comes out.
2542280849Scy	 */
2543280849Scy	switch (local_clock(peer, sys_offset)) {
2544280849Scy
2545280849Scy	/*
2546182007Sroberto	 * Clock exceeds panic threshold. Life as we know it ends.
254782505Sroberto	 */
254882505Sroberto	case -1:
2549280849Scy#ifdef HAVE_LIBSCF_H
2550280849Scy		/*
2551280849Scy		 * For Solaris enter the maintenance mode.
2552280849Scy		 */
2553280849Scy		if ((fmri = getenv("SMF_FMRI")) != NULL) {
2554280849Scy			if (smf_maintain_instance(fmri, 0) < 0) {
2555280849Scy				printf("smf_maintain_instance: %s\n",
2556280849Scy				    scf_strerror(scf_error()));
2557280849Scy				exit(1);
2558280849Scy			}
2559280849Scy			/*
2560280849Scy			 * Sleep until SMF kills us.
2561280849Scy			 */
2562280849Scy			for (;;)
2563280849Scy				pause();
2564280849Scy		}
2565280849Scy#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();
2574285169Scy		set_sys_leap(LEAP_NOTINSYNC);
2575182007Sroberto		sys_stratum = STRATUM_UNSPEC;
2576280849Scy		memcpy(&sys_refid, "STEP", 4);
2577182007Sroberto		sys_rootdelay = 0;
2578280849Scy		sys_rootdisp = 0;
2579280849Scy		L_CLR(&sys_reftime);
2580280849Scy		sys_jitter = LOGTOD(sys_precision);
2581280849Scy		leapsec_reset_frame();
258254359Sroberto		break;
258354359Sroberto
258482505Sroberto	/*
2585280849Scy	 * Clock was slewed. Handle the leapsecond stuff.
258682505Sroberto	 */
2587182007Sroberto	case 1:
2588182007Sroberto
2589182007Sroberto		/*
2590280849Scy		 * If this is the first time the clock is set, reset the
2591280849Scy		 * leap bits. If crypto, the timer will goose the setup
2592280849Scy		 * process.
2593182007Sroberto		 */
2594280849Scy		if (sys_leap == LEAP_NOTINSYNC) {
2595285169Scy			set_sys_leap(LEAP_NOWARNING);
2596280849Scy#ifdef AUTOKEY
2597280849Scy			if (crypto_flags)
2598280849Scy				crypto_update();
2599280849Scy#endif	/* AUTOKEY */
2600280849Scy			/*
2601280849Scy			 * If our parent process is waiting for the
2602280849Scy			 * first clock sync, send them home satisfied.
2603280849Scy			 */
2604280849Scy#ifdef HAVE_WORKING_FORK
2605280849Scy			if (waitsync_fd_to_close != -1) {
2606280849Scy				close(waitsync_fd_to_close);
2607280849Scy				waitsync_fd_to_close = -1;
2608280849Scy				DPRINTF(1, ("notified parent --wait-sync is done\n"));
2609280849Scy			}
2610280849Scy#endif /* HAVE_WORKING_FORK */
2611280849Scy
2612182007Sroberto		}
2613280849Scy
2614280849Scy		/*
2615280849Scy		 * If there is no leap second pending and the number of
2616280849Scy		 * survivor leap bits is greater than half the number of
2617280849Scy		 * survivors, try to schedule a leap for the end of the
2618280849Scy		 * current month. (This only works if no leap second for
2619280849Scy		 * that range is in the table, so doing this more than
2620280849Scy		 * once is mostly harmless.)
2621280849Scy		 */
2622280849Scy		if (leapsec == LSPROX_NOWARN) {
2623289764Sglebius			if (   leap_vote_ins > leap_vote_del
2624280849Scy			    && leap_vote_ins > sys_survivors / 2) {
2625280849Scy				get_systime(&now);
2626280849Scy				leapsec_add_dyn(TRUE, now.l_ui, NULL);
2627280849Scy			}
2628289764Sglebius			if (   leap_vote_del > leap_vote_ins
2629280849Scy			    && leap_vote_del > sys_survivors / 2) {
2630280849Scy				get_systime(&now);
2631280849Scy				leapsec_add_dyn(FALSE, now.l_ui, NULL);
2632280849Scy			}
2633132454Sroberto		}
2634182007Sroberto		break;
2635280849Scy
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(
2651280849Scy	struct peer *peer,	/* peer structure pointer */
2652280849Scy	u_char	mpoll
265354359Sroberto	)
265454359Sroberto{
2655280849Scy	u_long	next, utemp;
2656280849Scy	u_char	hpoll;
265754359Sroberto
265854359Sroberto	/*
2659182007Sroberto	 * This routine figures out when the next poll should be sent.
2660280849Scy	 * That turns out to be wickedly complicated. One problem is
2661280849Scy	 * that sometimes the time for the next poll is in the past when
2662280849Scy	 * the poll interval is reduced. We watch out for races here
2663280849Scy	 * between the receive process and the poll process.
2664182007Sroberto	 *
2665280849Scy	 * Clamp the poll interval between minpoll and maxpoll.
266654359Sroberto	 */
2667280849Scy	hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2668182007Sroberto
2669280849Scy#ifdef AUTOKEY
2670182007Sroberto	/*
2671280849Scy	 * If during the crypto protocol the poll interval has changed,
2672280849Scy	 * the lifetimes in the key list are probably bogus. Purge the
2673280849Scy	 * the key list and regenerate it later.
2674182007Sroberto	 */
2675280849Scy	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2676182007Sroberto		key_expire(peer);
2677280849Scy#endif	/* AUTOKEY */
2678182007Sroberto	peer->hpoll = hpoll;
267982505Sroberto
268082505Sroberto	/*
2681280849Scy	 * There are three variables important for poll scheduling, the
2682280849Scy	 * current time (current_time), next scheduled time (nextdate)
2683280849Scy	 * and the earliest time (utemp). The earliest time is 2 s
2684280849Scy	 * seconds, but could be more due to rate management. When
2685280849Scy	 * sending in a burst, use the earliest time. When not in a
2686280849Scy	 * burst but with a reply pending, send at the earliest time
2687280849Scy	 * unless the next scheduled time has not advanced. This can
2688280849Scy	 * only happen if multiple replies are pending in the same
2689280849Scy	 * response interval. Otherwise, send at the later of the next
2690280849Scy	 * scheduled time and the earliest time.
2691280849Scy	 *
2692280849Scy	 * Now we figure out if there is an override. If a burst is in
2693280849Scy	 * progress and we get called from the receive process, just
2694280849Scy	 * slink away. If called from the poll process, delay 1 s for a
2695280849Scy	 * reference clock, otherwise 2 s.
269682505Sroberto	 */
2697280849Scy	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2698280849Scy	    (1 << peer->minpoll), ntp_minpkt);
269954359Sroberto	if (peer->burst > 0) {
2700280849Scy		if (peer->nextdate > current_time)
270154359Sroberto			return;
270282505Sroberto#ifdef REFCLOCK
270382505Sroberto		else if (peer->flags & FLAG_REFCLOCK)
2704280849Scy			peer->nextdate = current_time + RESP_DELAY;
2705182007Sroberto#endif /* REFCLOCK */
270654359Sroberto		else
2707280849Scy			peer->nextdate = utemp;
2708280849Scy
2709280849Scy#ifdef AUTOKEY
2710182007Sroberto	/*
2711280849Scy	 * If a burst is not in progress and a crypto response message
2712280849Scy	 * is pending, delay 2 s, but only if this is a new interval.
2713182007Sroberto	 */
2714280849Scy	} else if (peer->cmmd != NULL) {
2715280849Scy		if (peer->nextdate > current_time) {
2716280849Scy			if (peer->nextdate + ntp_minpkt != utemp)
2717280849Scy				peer->nextdate = utemp;
2718280849Scy		} else {
2719280849Scy			peer->nextdate = utemp;
2720280849Scy		}
2721280849Scy#endif	/* AUTOKEY */
2722182007Sroberto
272382505Sroberto	/*
2724280849Scy	 * The ordinary case. If a retry, use minpoll; if unreachable,
2725280849Scy	 * use host poll; otherwise, use the minimum of host and peer
2726280849Scy	 * polls; In other words, oversampling is okay but
2727280849Scy	 * understampling is evil. Use the maximum of this value and the
2728280849Scy	 * headway. If the average headway is greater than the headway
2729280849Scy	 * threshold, increase the headway by the minimum interval.
273082505Sroberto	 */
2731280849Scy	} else {
2732280849Scy		if (peer->retry > 0)
2733280849Scy			hpoll = peer->minpoll;
2734280849Scy		else if (!(peer->reach))
2735280849Scy			hpoll = peer->hpoll;
2736280849Scy		else
2737280849Scy			hpoll = min(peer->ppoll, peer->hpoll);
2738280849Scy#ifdef REFCLOCK
2739280849Scy		if (peer->flags & FLAG_REFCLOCK)
2740280849Scy			next = 1 << hpoll;
2741280849Scy		else
2742280849Scy#endif /* REFCLOCK */
2743280849Scy			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2744280849Scy			    hpoll) >> 12;
2745280849Scy		next += peer->outdate;
2746280849Scy		if (next > utemp)
2747280849Scy			peer->nextdate = next;
2748280849Scy		else
2749280849Scy			peer->nextdate = utemp;
2750280849Scy		if (peer->throttle > (1 << peer->minpoll))
2751280849Scy			peer->nextdate += ntp_minpkt;
2752280849Scy	}
2753280849Scy	DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2754280849Scy		    current_time, ntoa(&peer->srcadr), peer->hpoll,
2755280849Scy		    peer->burst, peer->retry, peer->throttle,
2756280849Scy		    utemp - current_time, peer->nextdate -
2757280849Scy		    current_time));
275854359Sroberto}
275954359Sroberto
2760280849Scy
276154359Sroberto/*
2762280849Scy * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
2763280849Scy * spec.
276454359Sroberto */
276554359Srobertovoid
2766280849Scypeer_clear(
2767280849Scy	struct peer *peer,		/* peer structure */
2768280849Scy	const char *ident		/* tally lights */
2769280849Scy	)
277054359Sroberto{
2771280849Scy	u_char	u;
2772309007Sdelphij	l_fp	bxmt = peer->bxmt;	/* bcast clients retain this! */
2773280849Scy
2774280849Scy#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	 */
2784280849Scy	key_expire(peer);
2785132454Sroberto	if (peer->iffval != NULL)
2786132454Sroberto		BN_free(peer->iffval);
2787132454Sroberto	value_free(&peer->cookval);
2788132454Sroberto	value_free(&peer->recval);
2789280849Scy	value_free(&peer->encrypt);
2790280849Scy	value_free(&peer->sndval);
2791280849Scy	if (peer->cmmd != NULL)
2792182007Sroberto		free(peer->cmmd);
2793280849Scy	if (peer->subject != NULL)
2794280849Scy		free(peer->subject);
2795280849Scy	if (peer->issuer != NULL)
2796280849Scy		free(peer->issuer);
2797280849Scy#endif /* AUTOKEY */
2798182007Sroberto
279982505Sroberto	/*
2800280849Scy	 * Clear all values, including the optional crypto values above.
280182505Sroberto	 */
2802280849Scy	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;
2806280849Scy	peer->flash = peer_unfit(peer);
2807182007Sroberto	peer->jitter = LOGTOD(sys_precision);
2808280849Scy
2809309007Sdelphij	/* Don't throw away our broadcast replay protection */
2810309007Sdelphij	if (peer->hmode == MODE_BCLIENT)
2811309007Sdelphij		peer->bxmt = bxmt;
2812309007Sdelphij
2813280849Scy	/*
2814280849Scy	 * If interleave mode, initialize the alternate origin switch.
2815280849Scy	 */
2816280849Scy	if (peer->flags & FLAG_XLEAVE)
2817280849Scy		peer->flip = 1;
2818280849Scy	for (u = 0; u < NTP_SHIFT; u++) {
2819280849Scy		peer->filter_order[u] = u;
2820280849Scy		peer->filter_disp[u] = MAXDISPERSE;
2821182007Sroberto	}
282282505Sroberto#ifdef REFCLOCK
282382505Sroberto	if (!(peer->flags & FLAG_REFCLOCK)) {
2824280849Scy#endif
282582505Sroberto		peer->leap = LEAP_NOTINSYNC;
282682505Sroberto		peer->stratum = STRATUM_UNSPEC;
2827132454Sroberto		memcpy(&peer->refid, ident, 4);
2828280849Scy#ifdef REFCLOCK
282982505Sroberto	}
2830280849Scy#endif
283154359Sroberto
283254359Sroberto	/*
2833182007Sroberto	 * During initialization use the association count to spread out
2834280849Scy	 * the polls at one-second intervals. Passive associations'
2835280849Scy	 * first poll is delayed by the "discard minimum" to avoid rate
2836280849Scy	 * limiting. Other post-startup new or cleared associations
2837280849Scy	 * randomize the first poll over the minimum poll interval to
2838280849Scy	 * avoid implosion.
283954359Sroberto	 */
2840132454Sroberto	peer->nextdate = peer->update = peer->outdate = current_time;
2841280849Scy	if (initializing) {
2842182007Sroberto		peer->nextdate += peer_associations;
2843280849Scy	} else if (MODE_PASSIVE == peer->hmode) {
2844280849Scy		peer->nextdate += ntp_minpkt;
2845280849Scy	} else {
2846280849Scy		peer->nextdate += ntp_random() % peer->minpoll;
2847280849Scy	}
2848280849Scy#ifdef AUTOKEY
2849280849Scy	peer->refresh = current_time + (1 << NTP_REFRESH);
2850280849Scy#endif	/* AUTOKEY */
2851293423Sdelphij	DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
2852280849Scy		    current_time, peer->nextdate, peer->associd,
2853293423Sdelphij		    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;
2873280849Scy	char	tbuf[80];
287454359Sroberto
287554359Sroberto	/*
2876280849Scy	 * A sample consists of the offset, delay, dispersion and epoch
2877280849Scy	 * of arrival. The offset and delay are determined by the on-
2878280849Scy	 * wire protocol. The dispersion grows from the last outbound
2879280849Scy	 * packet to the arrival of this one increased by the sum of the
2880280849Scy	 * peer precision and the system precision as required by the
2881280849Scy	 * error budget. First, shift the new arrival into the shift
2882280849Scy	 * register discarding the oldest one.
288354359Sroberto	 */
288454359Sroberto	j = peer->filter_nextpt;
288582505Sroberto	peer->filter_offset[j] = sample_offset;
2886280849Scy	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
2894280849Scy	 * time initialize the distance and index lists. Since samples
2895280849Scy	 * become increasingly uncorrelated beyond the Allan intercept,
2896280849Scy	 * only under exceptional cases will an older sample be used.
2897280849Scy	 * Therefore, the distance list uses a compound metric. If the
2898280849Scy	 * dispersion is greater than the maximum dispersion, clamp the
2899280849Scy	 * distance at that value. If the time since the last update is
2900280849Scy	 * less than the Allan intercept use the delay; otherwise, use
2901280849Scy	 * 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;
2908282408Scy		if (peer->filter_disp[j] >= MAXDISPERSE) {
2909132454Sroberto			peer->filter_disp[j] = MAXDISPERSE;
291082505Sroberto			dst[i] = MAXDISPERSE;
2911280849Scy		} else if (peer->update - peer->filter_epoch[j] >
2912280849Scy		    (u_long)ULOGTOD(allan_xpt)) {
2913280849Scy			dst[i] = peer->filter_delay[j] +
2914280849Scy			    peer->filter_disp[j];
2915280849Scy		} else {
2916132454Sroberto			dst[i] = peer->filter_delay[j];
2917280849Scy		}
291882505Sroberto		ord[i] = j;
2919280849Scy		j = (j + 1) % NTP_SHIFT;
292082505Sroberto	}
292154359Sroberto
2922280849Scy	/*
2923282408Scy	 * If the clock has stabilized, sort the samples by distance.
292454359Sroberto	 */
2925280849Scy	if (freq_cnt == 0) {
2926182007Sroberto		for (i = 1; i < NTP_SHIFT; i++) {
2927182007Sroberto			for (j = 0; j < i; j++) {
2928280849Scy				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
2942280849Scy	 * can see it later. Prune the distance list to leave only
2943280849Scy	 * samples less than the maximum dispersion, which disfavors
2944280849Scy	 * uncorrelated samples older than the Allan intercept. To
2945280849Scy	 * further improve the jitter estimate, of the remainder leave
2946280849Scy	 * only samples less than the maximum distance, but keep at
2947280849Scy	 * 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];
2952289764Sglebius		if (   dst[i] >= MAXDISPERSE
2953289764Sglebius		    || (m >= 2 && dst[i] >= sys_maxdist))
295482505Sroberto			continue;
295582505Sroberto		m++;
295682505Sroberto	}
2957282408Scy
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
2962280849Scy	 * 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	 */
2981280849Scy	if (m == 0) {
2982280849Scy		clock_select();
298382505Sroberto		return;
2984280849Scy	}
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	/*
2993280849Scy	 * If the the new sample and the current sample are both valid
2994280849Scy	 * and the difference between their offsets exceeds CLOCK_SGATE
2995280849Scy	 * (3) times the jitter and the interval between them is less
2996280849Scy	 * than twice the host poll interval, consider the new sample
2997280849Scy	 * a popcorn spike and ignore it.
299854359Sroberto	 */
2999289764Sglebius	if (   peer->disp < sys_maxdist
3000289764Sglebius	    && peer->filter_disp[k] < sys_maxdist
3001289764Sglebius	    && etemp > CLOCK_SGATE * peer->jitter
3002289764Sglebius	    && peer->filter_epoch[k] - peer->epoch
3003289764Sglebius	       < 2. * ULOGTOD(peer->hpoll)) {
3004280849Scy		snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3005280849Scy		report_event(PEVNT_POPCORN, peer, tbuf);
300654359Sroberto		return;
300754359Sroberto	}
300854359Sroberto
300954359Sroberto	/*
3010280849Scy	 * A new minimum sample is useful only if it is later than the
3011280849Scy	 * last one used. In this design the maximum lifetime of any
3012280849Scy	 * sample is not greater than eight times the poll interval, so
3013280849Scy	 * the maximum interval between minimum samples is eight
3014280849Scy	 * packets.
301554359Sroberto	 */
3016280849Scy	if (peer->filter_epoch[k] <= peer->epoch) {
3017293423Sdelphij	DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3018293423Sdelphij		    peer->filter_epoch[k]));
301954359Sroberto		return;
302054359Sroberto	}
3021280849Scy	peer->epoch = peer->filter_epoch[k];
302282505Sroberto
302382505Sroberto	/*
302482505Sroberto	 * The mitigated sample statistics are saved for later
3025280849Scy	 * processing. If not synchronized or not in a burst, tickle the
3026280849Scy	 * clock select algorithm.
302782505Sroberto	 */
3028280849Scy	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3029280849Scy	    peer->offset, peer->delay, peer->disp, peer->jitter);
3030293423Sdelphij	DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
303182505Sroberto		    m, peer->offset, peer->delay, peer->disp,
3032293423Sdelphij		    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 *
3041280849Scy * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3042280849Scy * be enabled, even if declared falseticker, (2) only the prefer peer
3043280849Scy * can be selected as the system peer, (3) if the external source is
3044280849Scy * down, the system leap bits are set to 11 and the stratum set to
3045280849Scy * infinity.
304654359Sroberto */
304754359Srobertovoid
304854359Srobertoclock_select(void)
304954359Sroberto{
3050132454Sroberto	struct peer *peer;
3051132454Sroberto	int	i, j, k, n;
3052280849Scy	int	nlist, nl2;
3053280849Scy	int	allow;
3054280849Scy	int	speer;
3055182007Sroberto	double	d, e, f, g;
3056132454Sroberto	double	high, low;
3057280849Scy	double	speermet;
3058280849Scy	double	orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3059280849Scy	struct endpoint endp;
306054359Sroberto	struct peer *osys_peer;
3061280849Scy	struct peer *sys_prefer = NULL;	/* prefer peer */
3062280849Scy	struct peer *typesystem = NULL;
3063280849Scy	struct peer *typeorphan = NULL;
3064280849Scy#ifdef REFCLOCK
306582505Sroberto	struct peer *typeacts = NULL;
306682505Sroberto	struct peer *typelocal = NULL;
3067280849Scy	struct peer *typepps = NULL;
3068280849Scy#endif /* REFCLOCK */
306954359Sroberto	static struct endpoint *endpoint = NULL;
307082505Sroberto	static int *indx = NULL;
3071280849Scy	static peer_select *peers = NULL;
307254359Sroberto	static u_int endpoint_size = 0;
3073280849Scy	static u_int peers_size = 0;
307482505Sroberto	static u_int indx_size = 0;
3075280849Scy	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
3084285169Scy	set_sys_leap(LEAP_NOTINSYNC);
3085132454Sroberto	sys_stratum = STRATUM_UNSPEC;
3086132454Sroberto	memcpy(&sys_refid, "DOWN", 4);
3087132454Sroberto#endif /* LOCKCLOCK */
308854359Sroberto
308954359Sroberto	/*
3090280849Scy	 * Allocate dynamic space depending on the number of
3091280849Scy	 * associations.
3092280849Scy	 */
3093280849Scy	nlist = 1;
3094280849Scy	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3095280849Scy		nlist++;
3096280849Scy	endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3097280849Scy	peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3098280849Scy	indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3099280849Scy	octets = endpoint_size + peers_size + indx_size;
3100280849Scy	endpoint = erealloc(endpoint, octets);
3101280849Scy	peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3102280849Scy	indx = INC_ALIGNED_PTR(peers, peers_size);
3103280849Scy
3104280849Scy	/*
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	 */
3114280849Scy	nlist = nl2 = 0;	/* none yet */
3115280849Scy	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3116280849Scy		peer->new_status = CTL_PST_SEL_REJECT;
311754359Sroberto
3118280849Scy		/*
3119280849Scy		 * Leave the island immediately if the peer is
3120280849Scy		 * unfit to synchronize.
3121280849Scy		 */
3122309007Sdelphij		if (peer_unfit(peer)) {
3123280849Scy			continue;
3124309007Sdelphij		}
312582505Sroberto
3126280849Scy		/*
3127280849Scy		 * If this peer is an orphan parent, elect the
3128280849Scy		 * one with the lowest metric defined as the
3129280849Scy		 * IPv4 address or the first 64 bits of the
3130280849Scy		 * hashed IPv6 address.  To ensure convergence
3131280849Scy		 * on the same selected orphan, consider as
3132280849Scy		 * well that this system may have the lowest
3133280849Scy		 * metric and be the orphan parent.  If this
3134280849Scy		 * system wins, sys_peer will be NULL to trigger
3135280849Scy		 * orphan mode in timer().
3136280849Scy		 */
3137280849Scy		if (peer->stratum == sys_orphan) {
3138280849Scy			u_int32	localmet;
3139280849Scy			u_int32 peermet;
314054359Sroberto
3141280849Scy			if (peer->dstadr != NULL)
3142280849Scy				localmet = ntohl(peer->dstadr->addr_refid);
3143280849Scy			else
3144280849Scy				localmet = U_INT32_MAX;
3145280849Scy			peermet = ntohl(addr2refid(&peer->srcadr));
3146280849Scy			if (peermet < localmet && peermet < orphmet) {
3147280849Scy				typeorphan = peer;
3148280849Scy				orphmet = peermet;
314954359Sroberto			}
3150280849Scy			continue;
3151280849Scy		}
315254359Sroberto
3153280849Scy		/*
3154280849Scy		 * If this peer could have the orphan parent
3155280849Scy		 * as a synchronization ancestor, exclude it
3156282408Scy		 * from selection to avoid forming a
3157280849Scy		 * synchronization loop within the orphan mesh,
3158282408Scy		 * triggering stratum climb to infinity
3159280849Scy		 * instability.  Peers at stratum higher than
3160280849Scy		 * the orphan stratum could have the orphan
3161280849Scy		 * parent in ancestry so are excluded.
3162280849Scy		 * See http://bugs.ntp.org/2050
3163280849Scy		 */
3164309007Sdelphij		if (peer->stratum > sys_orphan) {
3165280849Scy			continue;
3166309007Sdelphij		}
3167280849Scy#ifdef REFCLOCK
3168280849Scy		/*
3169280849Scy		 * The following are special cases. We deal
3170280849Scy		 * with them later.
3171280849Scy		 */
3172280849Scy		if (!(peer->flags & FLAG_PREFER)) {
3173280849Scy			switch (peer->refclktype) {
3174280849Scy			case REFCLK_LOCALCLOCK:
3175289764Sglebius				if (   current_time > orphwait
3176289764Sglebius				    && typelocal == NULL)
3177280849Scy					typelocal = peer;
3178280849Scy				continue;
3179182007Sroberto
3180280849Scy			case REFCLK_ACTS:
3181289764Sglebius				if (   current_time > orphwait
3182289764Sglebius				    && typeacts == NULL)
3183280849Scy					typeacts = peer;
3184280849Scy				continue;
318554359Sroberto			}
3186280849Scy		}
3187280849Scy#endif /* REFCLOCK */
318854359Sroberto
3189280849Scy		/*
3190280849Scy		 * If we get this far, the peer can stay on the
3191280849Scy		 * island, but does not yet have the immunity
3192280849Scy		 * idol.
3193280849Scy		 */
3194280849Scy		peer->new_status = CTL_PST_SEL_SANE;
3195280849Scy		f = root_distance(peer);
3196280849Scy		peers[nlist].peer = peer;
3197280849Scy		peers[nlist].error = peer->jitter;
3198280849Scy		peers[nlist].synch = f;
3199280849Scy		nlist++;
3200182007Sroberto
3201280849Scy		/*
3202280849Scy		 * Insert each interval endpoint on the unsorted
3203280849Scy		 * endpoint[] list.
3204280849Scy		 */
3205280849Scy		e = peer->offset;
3206280849Scy		endpoint[nl2].type = -1;	/* lower end */
3207280849Scy		endpoint[nl2].val = e - f;
3208280849Scy		nl2++;
3209280849Scy		endpoint[nl2].type = 1;		/* upper end */
3210280849Scy		endpoint[nl2].val = e + f;
3211280849Scy		nl2++;
3212280849Scy	}
3213280849Scy	/*
3214280849Scy	 * Construct sorted indx[] of endpoint[] indexes ordered by
3215280849Scy	 * offset.
3216280849Scy	 */
3217280849Scy	for (i = 0; i < nl2; i++)
3218280849Scy		indx[i] = i;
3219280849Scy	for (i = 0; i < nl2; i++) {
3220280849Scy		endp = endpoint[indx[i]];
3221280849Scy		e = endp.val;
3222280849Scy		k = i;
3223280849Scy		for (j = i + 1; j < nl2; j++) {
3224280849Scy			endp = endpoint[indx[j]];
3225280849Scy			if (endp.val < e) {
3226280849Scy				e = endp.val;
3227280849Scy				k = j;
322854359Sroberto			}
322954359Sroberto		}
3230280849Scy		if (k != i) {
3231280849Scy			j = indx[k];
3232280849Scy			indx[k] = indx[i];
3233280849Scy			indx[i] = j;
3234280849Scy		}
323554359Sroberto	}
3236280849Scy	for (i = 0; i < nl2; i++)
3237280849Scy		DPRINTF(3, ("select: endpoint %2d %.6f\n",
3238280849Scy			endpoint[indx[i]].type, endpoint[indx[i]].val));
3239280849Scy
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
3259280849Scy	 * 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		/*
3267282408Scy		 * Bound the interval (low, high) as the smallest
3268280849Scy		 * interval containing points from the most sources.
3269132454Sroberto		 */
3270132454Sroberto		n = 0;
3271280849Scy		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;
3278280849Scy		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	/*
3295280849Scy	 * Clustering algorithm. Whittle candidate list of falsetickers,
3296280849Scy	 * who leave the island immediately. The TRUE peer is always a
3297182007Sroberto	 * truechimer. We must leave at least one peer to collect the
3298280849Scy	 * million bucks.
3299280849Scy	 *
3300280849Scy	 * We assert the correct time is contained in the interval, but
3301280849Scy	 * the best offset estimate for the interval might not be
3302280849Scy	 * contained in the interval. For this purpose, a truechimer is
3303282408Scy	 * defined as the midpoint of an interval that overlaps the
3304280849Scy	 * intersection interval.
3305182007Sroberto	 */
3306182007Sroberto	j = 0;
3307182007Sroberto	for (i = 0; i < nlist; i++) {
3308280849Scy		double	h;
3309280849Scy
3310280849Scy		peer = peers[i].peer;
3311280849Scy		h = peers[i].synch;
3312289764Sglebius		if ((   high <= low
3313289764Sglebius		     || peer->offset + h < low
3314289764Sglebius		     || peer->offset - h > high
3315289764Sglebius		    ) && !(peer->flags & FLAG_TRUE))
3316182007Sroberto			continue;
3317182007Sroberto
3318280849Scy#ifdef REFCLOCK
3319182007Sroberto		/*
3320280849Scy		 * Eligible PPS peers must survive the intersection
3321280849Scy		 * algorithm. Use the first one found, but don't
3322280849Scy		 * include any of them in the cluster population.
3323182007Sroberto		 */
3324280849Scy		if (peer->flags & FLAG_PPS) {
3325282408Scy			if (typepps == NULL)
3326280849Scy				typepps = peer;
3327282408Scy			if (!(peer->flags & FLAG_TSTAMP_PPS))
3328282408Scy				continue;
3329182007Sroberto		}
3330280849Scy#endif /* REFCLOCK */
3331182007Sroberto
3332280849Scy		if (j != i)
3333280849Scy			peers[j] = peers[i];
3334182007Sroberto		j++;
3335182007Sroberto	}
3336182007Sroberto	nlist = j;
3337182007Sroberto
3338182007Sroberto	/*
3339282408Scy	 * If no survivors remain at this point, check if the modem
3340280849Scy	 * driver, local driver or orphan parent in that order. If so,
3341280849Scy	 * nominate the first one found as the only survivor.
3342280849Scy	 * Otherwise, give up and leave the island to the rats.
334354359Sroberto	 */
3344182007Sroberto	if (nlist == 0) {
3345280849Scy		peers[0].error = 0;
3346280849Scy		peers[0].synch = sys_mindisp;
3347280849Scy#ifdef REFCLOCK
3348280849Scy		if (typeacts != NULL) {
3349280849Scy			peers[0].peer = typeacts;
335054359Sroberto			nlist = 1;
3351280849Scy		} else if (typelocal != NULL) {
3352280849Scy			peers[0].peer = typelocal;
335354359Sroberto			nlist = 1;
3354280849Scy		} else
3355280849Scy#endif /* REFCLOCK */
3356280849Scy		if (typeorphan != NULL) {
3357280849Scy			peers[0].peer = typeorphan;
3358280849Scy			nlist = 1;
335954359Sroberto		}
336054359Sroberto	}
336154359Sroberto
336254359Sroberto	/*
3363280849Scy	 * Mark the candidates at this point as truechimers.
3364132454Sroberto	 */
3365280849Scy	for (i = 0; i < nlist; i++) {
3366280849Scy		peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3367280849Scy		DPRINTF(2, ("select: survivor %s %f\n",
3368280849Scy			stoa(&peers[i].peer->srcadr), peers[i].synch));
3369280849Scy	}
3370132454Sroberto
337154359Sroberto	/*
3372289764Sglebius	 * Now, vote outliers off the island by select jitter weighted
3373182007Sroberto	 * by root distance. Continue voting as long as there are more
3374280849Scy	 * than sys_minclock survivors and the select jitter of the peer
3375280849Scy	 * with the worst metric is greater than the minimum peer
3376282408Scy	 * jitter. Stop if we are about to discard a TRUE or PREFER
3377280849Scy	 * peer, who of course have the immunity idol.
337854359Sroberto	 */
337954359Sroberto	while (1) {
338082505Sroberto		d = 1e9;
338182505Sroberto		e = -1e9;
3382280849Scy		g = 0;
338382505Sroberto		k = 0;
338482505Sroberto		for (i = 0; i < nlist; i++) {
3385280849Scy			if (peers[i].error < d)
3386280849Scy				d = peers[i].error;
3387280849Scy			peers[i].seljit = 0;
338882505Sroberto			if (nlist > 1) {
3389280849Scy				f = 0;
339082505Sroberto				for (j = 0; j < nlist; j++)
3391280849Scy					f += DIFF(peers[j].peer->offset,
3392280849Scy					    peers[i].peer->offset);
3393280849Scy				peers[i].seljit = SQRT(f / (nlist - 1));
339454359Sroberto			}
3395280849Scy			if (peers[i].seljit * peers[i].synch > e) {
3396280849Scy				g = peers[i].seljit;
3397280849Scy				e = peers[i].seljit * peers[i].synch;
339854359Sroberto				k = i;
339954359Sroberto			}
340054359Sroberto		}
3401280849Scy		g = max(g, LOGTOD(sys_precision));
3402289764Sglebius		if (   nlist <= max(1, sys_minclock)
3403289764Sglebius		    || g <= d
3404289764Sglebius		    || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3405132454Sroberto			break;
3406280849Scy
3407280849Scy		DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3408280849Scy			ntoa(&peers[k].peer->srcadr), g, d));
3409280849Scy		if (nlist > sys_maxclock)
3410280849Scy			peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3411280849Scy		for (j = k + 1; j < nlist; j++)
3412280849Scy			peers[j - 1] = peers[j];
341354359Sroberto		nlist--;
341454359Sroberto	}
341582505Sroberto
341682505Sroberto	/*
3417132454Sroberto	 * What remains is a list usually not greater than sys_minclock
3418280849Scy	 * peers. Note that unsynchronized peers cannot survive this
3419280849Scy	 * far.  Count and mark these survivors.
3420280849Scy	 *
3421280849Scy	 * While at it, count the number of leap warning bits found.
3422280849Scy	 * This will be used later to vote the system leap warning bit.
3423280849Scy	 * If a leap warning bit is found on a reference clock, the vote
3424280849Scy	 * is always won.
3425280849Scy	 *
3426280849Scy	 * Choose the system peer using a hybrid metric composed of the
3427280849Scy	 * selection jitter scaled by the root distance augmented by
3428280849Scy	 * stratum scaled by sys_mindisp (.001 by default). The goal of
3429280849Scy	 * the small stratum factor is to avoid clockhop between a
3430280849Scy	 * reference clock and a network peer which has a refclock and
3431280849Scy	 * is using an older ntpd, which does not floor sys_rootdisp at
3432280849Scy	 * sys_mindisp.
3433280849Scy	 *
3434280849Scy	 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3435280849Scy	 * in selecting the system peer, using a weight of 1 second of
3436280849Scy	 * additional root distance per stratum.  This heavy bias is no
3437280849Scy	 * longer appropriate, as the scaled root distance provides a
3438280849Scy	 * more rational metric carrying the cumulative error budget.
343954359Sroberto	 */
3440280849Scy	e = 1e9;
3441280849Scy	speer = 0;
3442280849Scy	leap_vote_ins = 0;
3443280849Scy	leap_vote_del = 0;
3444182007Sroberto	for (i = 0; i < nlist; i++) {
3445280849Scy		peer = peers[i].peer;
3446280849Scy		peer->unreach = 0;
3447280849Scy		peer->new_status = CTL_PST_SEL_SYNCCAND;
3448182007Sroberto		sys_survivors++;
3449280849Scy		if (peer->leap == LEAP_ADDSECOND) {
3450280849Scy			if (peer->flags & FLAG_REFCLOCK)
3451280849Scy				leap_vote_ins = nlist;
3452280849Scy			else if (leap_vote_ins < nlist)
3453280849Scy				leap_vote_ins++;
3454280849Scy		}
3455280849Scy		if (peer->leap == LEAP_DELSECOND) {
3456280849Scy			if (peer->flags & FLAG_REFCLOCK)
3457280849Scy				leap_vote_del = nlist;
3458280849Scy			else if (leap_vote_del < nlist)
3459280849Scy				leap_vote_del++;
3460280849Scy		}
3461132454Sroberto		if (peer->flags & FLAG_PREFER)
3462132454Sroberto			sys_prefer = peer;
3463280849Scy		speermet = peers[i].seljit * peers[i].synch +
3464280849Scy		    peer->stratum * sys_mindisp;
3465280849Scy		if (speermet < e) {
3466280849Scy			e = speermet;
3467280849Scy			speer = i;
3468280849Scy		}
346954359Sroberto	}
347054359Sroberto
347154359Sroberto	/*
3472280849Scy	 * Unless there are at least sys_misane survivors, leave the
3473280849Scy	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3474280849Scy	 * use the selected survivor speer. However, if the current
3475280849Scy	 * system peer is not speer, stay with the current system peer
3476280849Scy	 * as long as it doesn't get too old or too ugly.
3477132454Sroberto	 */
3478280849Scy	if (nlist > 0 && nlist >= sys_minsane) {
3479280849Scy		double	x;
3480280849Scy
3481280849Scy		typesystem = peers[speer].peer;
3482280849Scy		if (osys_peer == NULL || osys_peer == typesystem) {
3483282408Scy			sys_clockhop = 0;
3484280849Scy		} else if ((x = fabs(typesystem->offset -
3485280849Scy		    osys_peer->offset)) < sys_mindisp) {
3486280849Scy			if (sys_clockhop == 0)
3487280849Scy				sys_clockhop = sys_mindisp;
3488280849Scy			else
3489280849Scy				sys_clockhop *= .5;
3490280849Scy			DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3491280849Scy				j, x, sys_clockhop));
3492280849Scy			if (fabs(x) < sys_clockhop)
3493280849Scy				typesystem = osys_peer;
3494280849Scy			else
3495280849Scy				sys_clockhop = 0;
3496280849Scy		} else {
3497280849Scy			sys_clockhop = 0;
3498280849Scy		}
3499182007Sroberto	}
3500132454Sroberto
3501132454Sroberto	/*
3502280849Scy	 * Mitigation rules of the game. We have the pick of the
3503280849Scy	 * litter in typesystem if any survivors are left. If
3504280849Scy	 * there is a prefer peer, use its offset and jitter.
3505280849Scy	 * Otherwise, use the combined offset and jitter of all kitters.
350654359Sroberto	 */
3507280849Scy	if (typesystem != NULL) {
3508280849Scy		if (sys_prefer == NULL) {
3509280849Scy			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3510280849Scy			clock_combine(peers, sys_survivors, speer);
3511182007Sroberto		} else {
3512280849Scy			typesystem = sys_prefer;
3513280849Scy			sys_clockhop = 0;
3514280849Scy			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3515280849Scy			sys_offset = typesystem->offset;
3516280849Scy			sys_jitter = typesystem->jitter;
3517182007Sroberto		}
3518280849Scy		DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3519280849Scy			sys_offset, sys_jitter));
3520280849Scy	}
3521280849Scy#ifdef REFCLOCK
3522280849Scy	/*
3523280849Scy	 * If a PPS driver is lit and the combined offset is less than
3524280849Scy	 * 0.4 s, select the driver as the PPS peer and use its offset
3525280849Scy	 * and jitter. However, if this is the atom driver, use it only
3526280849Scy	 * if there is a prefer peer or there are no survivors and none
3527280849Scy	 * are required.
3528280849Scy	 */
3529289764Sglebius	if (   typepps != NULL
3530289764Sglebius	    && fabs(sys_offset) < 0.4
3531289764Sglebius	    && (   typepps->refclktype != REFCLK_ATOM_PPS
3532289764Sglebius		|| (   typepps->refclktype == REFCLK_ATOM_PPS
3533289764Sglebius		    && (   sys_prefer != NULL
3534289764Sglebius			|| (typesystem == NULL && sys_minsane == 0))))) {
3535280849Scy		typesystem = typepps;
3536280849Scy		sys_clockhop = 0;
3537280849Scy		typesystem->new_status = CTL_PST_SEL_PPS;
3538293423Sdelphij		sys_offset = typesystem->offset;
3539280849Scy		sys_jitter = typesystem->jitter;
3540280849Scy		DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3541280849Scy			sys_offset, sys_jitter));
3542280849Scy	}
3543280849Scy#endif /* REFCLOCK */
3544182007Sroberto
3545280849Scy	/*
3546280849Scy	 * If there are no survivors at this point, there is no
3547280849Scy	 * system peer. If so and this is an old update, keep the
3548280849Scy	 * current statistics, but do not update the clock.
3549280849Scy	 */
3550280849Scy	if (typesystem == NULL) {
3551280849Scy		if (osys_peer != NULL) {
3552280849Scy			if (sys_orphwait > 0)
3553280849Scy				orphwait = current_time + sys_orphwait;
3554280849Scy			report_event(EVNT_NOPEER, NULL, NULL);
3555182007Sroberto		}
3556280849Scy		sys_peer = NULL;
3557280849Scy		for (peer = peer_list; peer != NULL; peer = peer->p_link)
3558280849Scy			peer->status = peer->new_status;
3559280849Scy		return;
356054359Sroberto	}
3561182007Sroberto
3562182007Sroberto	/*
3563280849Scy	 * Do not use old data, as this may mess up the clock discipline
3564280849Scy	 * stability.
3565182007Sroberto	 */
3566280849Scy	if (typesystem->epoch <= sys_epoch)
3567280849Scy		return;
3568132454Sroberto
3569280849Scy	/*
3570280849Scy	 * We have found the alpha male. Wind the clock.
3571280849Scy	 */
3572280849Scy	if (osys_peer != typesystem)
3573280849Scy		report_event(PEVNT_NEWPEER, typesystem, NULL);
3574280849Scy	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3575280849Scy		peer->status = peer->new_status;
3576280849Scy	clock_update(typesystem);
357754359Sroberto}
357854359Sroberto
3579182007Sroberto
3580182007Srobertostatic void
358154359Srobertoclock_combine(
3582280849Scy	peer_select *	peers,	/* survivor list */
3583280849Scy	int		npeers,	/* number of survivors */
3584280849Scy	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++) {
3592280849Scy		x = 1. / peers[i].synch;
3593280849Scy		y += x;
3594280849Scy		z += x * peers[i].peer->offset;
3595280849Scy		w += x * DIFF(peers[i].peer->offset,
3596280849Scy		    peers[syspeer].peer->offset);
359754359Sroberto	}
3598182007Sroberto	sys_offset = z / y;
3599280849Scy	sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
360054359Sroberto}
360154359Sroberto
3602280849Scy
360354359Sroberto/*
360454359Sroberto * root_distance - compute synchronization distance from peer to root
360554359Sroberto */
360654359Srobertostatic double
360754359Srobertoroot_distance(
3608280849Scy	struct peer *peer	/* peer structure pointer */
360954359Sroberto	)
361054359Sroberto{
3611280849Scy	double	dtemp;
3612182007Sroberto
361382505Sroberto	/*
3614280849Scy	 * Root Distance (LAMBDA) is defined as:
3615309007Sdelphij	 * (delta + DELTA)/2 + epsilon + EPSILON + D
3616280849Scy	 *
3617280849Scy	 * where:
3618280849Scy	 *  delta   is the round-trip delay
3619280849Scy	 *  DELTA   is the root delay
3620309007Sdelphij	 *  epsilon is the peer dispersion
3621280849Scy	 *	    + (15 usec each second)
3622280849Scy	 *  EPSILON is the root dispersion
3623309007Sdelphij	 *  D       is sys_jitter
3624280849Scy	 *
3625280849Scy	 * NB: Think hard about why we are using these values, and what
3626280849Scy	 * the alternatives are, and the various pros/cons.
3627280849Scy	 *
3628280849Scy	 * DLM thinks these are probably the best choices from any of the
3629280849Scy	 * other worse choices.
3630280849Scy	 */
3631280849Scy	dtemp = (peer->delay + peer->rootdelay) / 2
3632309007Sdelphij		+ peer->disp
3633280849Scy		  + clock_phi * (current_time - peer->update)
3634280849Scy		+ peer->rootdisp
3635280849Scy		+ peer->jitter;
3636280849Scy	/*
363782505Sroberto	 * Careful squeak here. The value returned must be greater than
3638182007Sroberto	 * the minimum root dispersion in order to avoid clockhop with
3639280849Scy	 * highly precise reference clocks. Note that the root distance
3640280849Scy	 * cannot exceed the sys_maxdist, as this is the cutoff by the
3641280849Scy	 * selection algorithm.
364282505Sroberto	 */
3643280849Scy	if (dtemp < sys_mindisp)
3644280849Scy		dtemp = sys_mindisp;
3645280849Scy	return (dtemp);
364654359Sroberto}
364754359Sroberto
3648280849Scy
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 */
3658280849Scy	size_t	sendlen, authlen;
3659182007Sroberto	keyid_t	xkeyid = 0;	/* transmit key ID */
3660280849Scy	l_fp	xmt_tx, xmt_ty;
366154359Sroberto
3662280849Scy	if (!peer->dstadr)	/* drop peers without interface */
3663182007Sroberto		return;
3664182007Sroberto
3665280849Scy	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3666280849Scy	    peer->hmode);
3667280849Scy	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
366854359Sroberto	xpkt.ppoll = peer->hpoll;
366954359Sroberto	xpkt.precision = sys_precision;
3670280849Scy	xpkt.refid = sys_refid;
3671280849Scy	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3672280849Scy	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
367354359Sroberto	HTONL_FP(&sys_reftime, &xpkt.reftime);
3674280849Scy	HTONL_FP(&peer->rec, &xpkt.org);
3675280849Scy	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;
3690293423Sdelphij	if (
3691280849Scy#ifdef AUTOKEY
3692293423Sdelphij	    !(peer->flags & FLAG_SKEY) &&
3693280849Scy#endif	/* !AUTOKEY */
3694293423Sdelphij	    peer->keyid == 0) {
3695280849Scy
3696280849Scy		/*
3697280849Scy		 * Transmit a-priori timestamps
3698280849Scy		 */
3699280849Scy		get_systime(&xmt_tx);
3700280849Scy		if (peer->flip == 0) {	/* basic mode */
3701280849Scy			peer->aorg = xmt_tx;
3702280849Scy			HTONL_FP(&xmt_tx, &xpkt.xmt);
3703280849Scy		} else {		/* interleaved modes */
3704280849Scy			if (peer->hmode == MODE_BROADCAST) { /* bcst */
3705280849Scy				HTONL_FP(&xmt_tx, &xpkt.xmt);
3706280849Scy				if (peer->flip > 0)
3707280849Scy					HTONL_FP(&peer->borg,
3708280849Scy					    &xpkt.org);
3709280849Scy				else
3710280849Scy					HTONL_FP(&peer->aorg,
3711280849Scy					    &xpkt.org);
3712280849Scy			} else {	/* symmetric */
3713280849Scy				if (peer->flip > 0)
3714280849Scy					HTONL_FP(&peer->borg,
3715280849Scy					    &xpkt.xmt);
3716280849Scy				else
3717280849Scy					HTONL_FP(&peer->aorg,
3718280849Scy					    &xpkt.xmt);
3719280849Scy			}
3720280849Scy		}
3721280849Scy		peer->t21_bytes = sendlen;
3722132454Sroberto		sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3723280849Scy		    &xpkt, sendlen);
372482505Sroberto		peer->sent++;
3725280849Scy		peer->throttle += (1 << peer->minpoll) - 2;
3726280849Scy
3727280849Scy		/*
3728280849Scy		 * Capture a-posteriori timestamps
3729280849Scy		 */
3730280849Scy		get_systime(&xmt_ty);
3731280849Scy		if (peer->flip != 0) {		/* interleaved modes */
3732280849Scy			if (peer->flip > 0)
3733280849Scy				peer->aorg = xmt_ty;
3734280849Scy			else
3735280849Scy				peer->borg = xmt_ty;
3736280849Scy			peer->flip = -peer->flip;
3737280849Scy		}
3738280849Scy		L_SUB(&xmt_ty, &xmt_tx);
3739280849Scy		LFPTOD(&xmt_ty, peer->xleave);
3740293423Sdelphij		DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3741293423Sdelphij			    current_time,
3742293423Sdelphij			    peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3743293423Sdelphij		            stoa(&peer->srcadr), peer->hmode, sendlen,
3744293423Sdelphij			    xmt_tx.l_ui, xmt_tx.l_uf));
374582505Sroberto		return;
374682505Sroberto	}
374754359Sroberto
374882505Sroberto	/*
3749280849Scy	 * Authentication is enabled, so the transmitted packet must be
3750280849Scy	 * authenticated. If autokey is enabled, fuss with the various
3751280849Scy	 * modes; otherwise, symmetric key cryptography is used.
375282505Sroberto	 */
3753280849Scy#ifdef AUTOKEY
3754280849Scy	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
3770280849Scy		 * 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) {
3780282408Scy
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
3796280849Scy			 * key cache, a birthday has happened or the key
3797280849Scy			 * has expired, so the pseudo-random sequence is
3798280849Scy			 * broken. In that case, purge the keylist and
3799280849Scy			 * 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
3815280849Scy		/*
3816280849Scy		 * In broadcast server mode the autokey values are
3817280849Scy		 * required by the broadcast clients. Push them when a
3818280849Scy		 * new keylist is generated; otherwise, push the
3819280849Scy		 * association message so the client can request them at
3820280849Scy		 * other times.
3821280849Scy		 */
382282505Sroberto		case MODE_BROADCAST:
382382505Sroberto			if (peer->flags & FLAG_ASSOC)
3824132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO |
3825280849Scy				    CRYPTO_RESP, peer->associd, NULL);
382682505Sroberto			else
3827132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC |
3828280849Scy				    CRYPTO_RESP, peer->associd, NULL);
382982505Sroberto			break;
383082505Sroberto
383154359Sroberto		/*
3832282408Scy		 * In symmetric modes the parameter, certificate,
3833280849Scy		 * identity, cookie and autokey exchanges are
3834280849Scy		 * required. The leapsecond exchange is optional. But, a
3835280849Scy		 * peer will not believe the other peer until the other
3836280849Scy		 * peer has synchronized, so the certificate exchange
3837280849Scy		 * might loop until then. If a peer finds a broken
3838280849Scy		 * autokey sequence, it uses the autokey exchange to
3839280849Scy		 * retrieve the autokey values. In any case, if a new
3840280849Scy		 * keylist is generated, the autokey values are pushed.
384154359Sroberto		 */
384282505Sroberto		case MODE_ACTIVE:
384382505Sroberto		case MODE_PASSIVE:
3844280849Scy
3845182007Sroberto			/*
3846280849Scy			 * Parameter, certificate and identity.
3847182007Sroberto			 */
384882505Sroberto			if (!peer->crypto)
3849132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC,
3850280849Scy				    peer->associd, hostval.ptr);
3851280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3852132454Sroberto				exten = crypto_args(peer, CRYPTO_CERT,
3853280849Scy				    peer->associd, peer->issuer);
3854182007Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3855182007Sroberto				exten = crypto_args(peer,
3856280849Scy				    crypto_ident(peer), peer->associd,
3857280849Scy				    NULL);
3858132454Sroberto
3859132454Sroberto			/*
3860280849Scy			 * Cookie and autokey. We request the cookie
3861280849Scy			 * only when the this peer and the other peer
3862280849Scy			 * are synchronized. But, this peer needs the
3863280849Scy			 * autokey values when the cookie is zero. Any
3864280849Scy			 * time we regenerate the key list, we offer the
3865280849Scy			 * autokey values without being asked. If for
3866280849Scy			 * some reason either peer finds a broken
3867280849Scy			 * autokey sequence, the autokey exchange is
3868280849Scy			 * used to retrieve the autokey values.
3869132454Sroberto			 */
3870289764Sglebius			else if (   sys_leap != LEAP_NOTINSYNC
3871289764Sglebius				 && peer->leap != LEAP_NOTINSYNC
3872289764Sglebius				 && !(peer->crypto & CRYPTO_FLAG_COOK))
3873132454Sroberto				exten = crypto_args(peer, CRYPTO_COOK,
3874280849Scy				    peer->associd, NULL);
3875132454Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3876132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO,
3877280849Scy				    peer->associd, NULL);
3878289764Sglebius			else if (   peer->flags & FLAG_ASSOC
3879289764Sglebius				 && peer->crypto & CRYPTO_FLAG_SIGN)
3880280849Scy				exten = crypto_args(peer, CRYPTO_AUTO |
3881280849Scy				    CRYPTO_RESP, peer->assoc, NULL);
3882132454Sroberto
3883132454Sroberto			/*
3884280849Scy			 * Wait for clock sync, then sign the
3885280849Scy			 * certificate and retrieve the leapsecond
3886280849Scy			 * values.
3887132454Sroberto			 */
3888280849Scy			else if (sys_leap == LEAP_NOTINSYNC)
3889280849Scy				break;
3890280849Scy
3891280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3892280849Scy				exten = crypto_args(peer, CRYPTO_SIGN,
3893280849Scy				    peer->associd, hostval.ptr);
3894280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3895280849Scy				exten = crypto_args(peer, CRYPTO_LEAP,
3896280849Scy				    peer->associd, NULL);
389782505Sroberto			break;
389882505Sroberto
389982505Sroberto		/*
3900280849Scy		 * In client mode the parameter, certificate, identity,
3901280849Scy		 * cookie and sign exchanges are required. The
3902280849Scy		 * leapsecond exchange is optional. If broadcast client
3903280849Scy		 * mode the same exchanges are required, except that the
3904280849Scy		 * autokey exchange is substitutes for the cookie
3905280849Scy		 * exchange, since the cookie is always zero. If the
3906280849Scy		 * broadcast client finds a broken autokey sequence, it
3907280849Scy		 * uses the autokey exchange to retrieve the autokey
3908280849Scy		 * values.
390982505Sroberto		 */
391082505Sroberto		case MODE_CLIENT:
3911280849Scy
3912182007Sroberto			/*
3913280849Scy			 * Parameter, certificate and identity.
3914182007Sroberto			 */
391582505Sroberto			if (!peer->crypto)
3916132454Sroberto				exten = crypto_args(peer, CRYPTO_ASSOC,
3917280849Scy				    peer->associd, hostval.ptr);
3918280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3919132454Sroberto				exten = crypto_args(peer, CRYPTO_CERT,
3920280849Scy				    peer->associd, peer->issuer);
3921182007Sroberto			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3922182007Sroberto				exten = crypto_args(peer,
3923280849Scy				    crypto_ident(peer), peer->associd,
3924280849Scy				    NULL);
3925132454Sroberto
3926132454Sroberto			/*
3927280849Scy			 * Cookie and autokey. These are requests, but
3928280849Scy			 * we use the peer association ID with autokey
3929280849Scy			 * rather than our own.
3930132454Sroberto			 */
3931280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3932132454Sroberto				exten = crypto_args(peer, CRYPTO_COOK,
3933280849Scy				    peer->associd, NULL);
3934280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3935132454Sroberto				exten = crypto_args(peer, CRYPTO_AUTO,
3936280849Scy				    peer->assoc, NULL);
3937132454Sroberto
3938132454Sroberto			/*
3939280849Scy			 * Wait for clock sync, then sign the
3940280849Scy			 * certificate and retrieve the leapsecond
3941280849Scy			 * values.
3942132454Sroberto			 */
3943280849Scy			else if (sys_leap == LEAP_NOTINSYNC)
3944280849Scy				break;
3945280849Scy
3946280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3947132454Sroberto				exten = crypto_args(peer, CRYPTO_SIGN,
3948280849Scy				    peer->associd, hostval.ptr);
3949280849Scy			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3950280849Scy				exten = crypto_args(peer, CRYPTO_LEAP,
3951280849Scy				    peer->associd, NULL);
395282505Sroberto			break;
395382505Sroberto		}
395482505Sroberto
395582505Sroberto		/*
3956280849Scy		 * Add a queued extension field if present. This is
3957280849Scy		 * always a request message, so the reply ID is already
3958280849Scy		 * in the message. If an error occurs, the error bit is
3959280849Scy		 * lit in the response.
3960182007Sroberto		 */
3961182007Sroberto		if (peer->cmmd != NULL) {
3962280849Scy			u_int32 temp32;
3963280849Scy
3964280849Scy			temp32 = CRYPTO_RESP;
3965280849Scy			peer->cmmd->opcode |= htonl(temp32);
3966280849Scy			sendlen += crypto_xmit(peer, &xpkt, NULL,
3967280849Scy			    sendlen, peer->cmmd, 0);
3968182007Sroberto			free(peer->cmmd);
3969182007Sroberto			peer->cmmd = NULL;
3970182007Sroberto		}
3971280849Scy
3972280849Scy		/*
3973280849Scy		 * Add an extension field created above. All but the
3974280849Scy		 * autokey response message are request messages.
3975280849Scy		 */
3976182007Sroberto		if (exten != NULL) {
3977280849Scy			if (exten->opcode != 0)
3978280849Scy				sendlen += crypto_xmit(peer, &xpkt,
3979280849Scy				    NULL, sendlen, exten, 0);
3980182007Sroberto			free(exten);
3981182007Sroberto		}
3982182007Sroberto
3983182007Sroberto		/*
3984280849Scy		 * Calculate the next session key. Since extension
3985280849Scy		 * fields are present, the cookie value is zero.
398682505Sroberto		 */
3987280849Scy		if (sendlen > (int)LEN_PKT_NOMAC) {
398882505Sroberto			session_key(&peer->dstadr->sin, &peer->srcadr,
398982505Sroberto			    xkeyid, 0, 2);
3990182007Sroberto		}
3991282408Scy	}
3992280849Scy#endif	/* AUTOKEY */
3993182007Sroberto
3994182007Sroberto	/*
3995280849Scy	 * Transmit a-priori timestamps
3996182007Sroberto	 */
3997280849Scy	get_systime(&xmt_tx);
3998280849Scy	if (peer->flip == 0) {		/* basic mode */
3999280849Scy		peer->aorg = xmt_tx;
4000280849Scy		HTONL_FP(&xmt_tx, &xpkt.xmt);
4001280849Scy	} else {			/* interleaved modes */
4002280849Scy		if (peer->hmode == MODE_BROADCAST) { /* bcst */
4003280849Scy			HTONL_FP(&xmt_tx, &xpkt.xmt);
4004280849Scy			if (peer->flip > 0)
4005280849Scy				HTONL_FP(&peer->borg, &xpkt.org);
4006280849Scy			else
4007280849Scy				HTONL_FP(&peer->aorg, &xpkt.org);
4008280849Scy		} else {		/* symmetric */
4009280849Scy			if (peer->flip > 0)
4010280849Scy				HTONL_FP(&peer->borg, &xpkt.xmt);
4011280849Scy			else
4012280849Scy				HTONL_FP(&peer->aorg, &xpkt.xmt);
4013280849Scy		}
4014280849Scy	}
401582505Sroberto	xkeyid = peer->keyid;
401682505Sroberto	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
401782505Sroberto	if (authlen == 0) {
4018280849Scy		report_event(PEVNT_AUTH, peer, "no key");
4019280849Scy		peer->flash |= TEST5;		/* auth error */
4020280849Scy		peer->badauth++;
402182505Sroberto		return;
402282505Sroberto	}
402382505Sroberto	sendlen += authlen;
4024280849Scy#ifdef AUTOKEY
402582505Sroberto	if (xkeyid > NTP_MAXKEY)
402682505Sroberto		authtrust(xkeyid, 0);
4027280849Scy#endif	/* AUTOKEY */
402882505Sroberto	if (sendlen > sizeof(xpkt)) {
4029293423Sdelphij		msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4030132454Sroberto		exit (-1);
403182505Sroberto	}
4032280849Scy	peer->t21_bytes = sendlen;
4033132454Sroberto	sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
4034280849Scy	    sendlen);
4035280849Scy	peer->sent++;
4036280849Scy	peer->throttle += (1 << peer->minpoll) - 2;
403782505Sroberto
403882505Sroberto	/*
4039280849Scy	 * Capture a-posteriori timestamps
404082505Sroberto	 */
4041280849Scy	get_systime(&xmt_ty);
4042280849Scy	if (peer->flip != 0) {			/* interleaved modes */
4043280849Scy		if (peer->flip > 0)
4044280849Scy			peer->aorg = xmt_ty;
4045280849Scy		else
4046280849Scy			peer->borg = xmt_ty;
4047280849Scy		peer->flip = -peer->flip;
4048280849Scy	}
4049280849Scy	L_SUB(&xmt_ty, &xmt_tx);
4050280849Scy	LFPTOD(&xmt_ty, peer->xleave);
4051280849Scy#ifdef AUTOKEY
4052293423Sdelphij	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4053280849Scy		    current_time, latoa(peer->dstadr),
4054280849Scy		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4055293423Sdelphij		    peer->keynumber));
4056280849Scy#else	/* !AUTOKEY follows */
4057293423Sdelphij	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %d\n",
4058280849Scy		    current_time, peer->dstadr ?
4059280849Scy		    ntoa(&peer->dstadr->sin) : "-",
4060293423Sdelphij		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4061280849Scy#endif	/* !AUTOKEY */
4062293423Sdelphij
4063293423Sdelphij	return;
406454359Sroberto}
406554359Sroberto
406682505Sroberto
4067285169Scy#ifdef LEAP_SMEAR
4068285169Scy
4069285169Scystatic void
4070293423Sdelphijleap_smear_add_offs(
4071293423Sdelphij	l_fp *t,
4072293423Sdelphij	l_fp *t_recv
4073293423Sdelphij	)
4074293423Sdelphij{
4075293423Sdelphij
4076285169Scy	L_ADD(t, &leap_smear.offset);
4077293423Sdelphij
4078309007Sdelphij	/*
4079309007Sdelphij	** XXX: Should the smear be added to the root dispersion?
4080309007Sdelphij	*/
4081309007Sdelphij
4082293423Sdelphij	return;
4083285169Scy}
4084285169Scy
4085285169Scy#endif  /* LEAP_SMEAR */
4086285169Scy
4087285169Scy
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 */
4095280849Scy	int	xmode,		/* receive mode */
4096132454Sroberto	keyid_t	xkeyid,		/* transmit key ID */
4097280849Scy	int	flags		/* restrict mask */
409854359Sroberto	)
409954359Sroberto{
4100280849Scy	struct pkt xpkt;	/* transmit packet structure */
4101280849Scy	struct pkt *rpkt;	/* receive packet structure */
4102280849Scy	l_fp	xmt_tx, xmt_ty;
4103293423Sdelphij	size_t	sendlen;
4104280849Scy#ifdef AUTOKEY
4105132454Sroberto	u_int32	temp32;
4106132454Sroberto#endif
410754359Sroberto
410854359Sroberto	/*
410982505Sroberto	 * Initialize transmit packet header fields from the receive
4110280849Scy	 * buffer provided. We leave the fields intact as received, but
4111280849Scy	 * set the peer poll at the maximum of the receive peer poll and
4112280849Scy	 * the system minimum poll (ntp_minpoll). This is for KoD rate
4113280849Scy	 * control and not strictly specification compliant, but doesn't
4114280849Scy	 * break anything.
4115182007Sroberto	 *
4116280849Scy	 * If the gazinta was from a multicast address, the gazoutta
4117280849Scy	 * 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	/*
4124280849Scy	 * If this is a kiss-o'-death (KoD) packet, show leap
4125182007Sroberto	 * unsynchronized, stratum zero, reference ID the four-character
4126280849Scy	 * kiss code and system root delay. Note we don't reveal the
4127280849Scy	 * local time, so these packets can't be used for
4128280849Scy	 * synchronization.
4129182007Sroberto	 */
4130280849Scy	if (flags & RES_KOD) {
4131280849Scy		sys_kodsent++;
4132132454Sroberto		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4133132454Sroberto		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4134280849Scy		xpkt.stratum = STRATUM_PKT_UNSPEC;
4135280849Scy		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4136280849Scy		xpkt.precision = rpkt->precision;
4137182007Sroberto		memcpy(&xpkt.refid, "RATE", 4);
4138280849Scy		xpkt.rootdelay = rpkt->rootdelay;
4139280849Scy		xpkt.rootdisp = rpkt->rootdisp;
4140280849Scy		xpkt.reftime = rpkt->reftime;
4141280849Scy		xpkt.org = rpkt->xmt;
4142280849Scy		xpkt.rec = rpkt->xmt;
4143280849Scy		xpkt.xmt = rpkt->xmt;
4144182007Sroberto
4145182007Sroberto	/*
4146182007Sroberto	 * This is a normal packet. Use the system variables.
4147182007Sroberto	 */
4148280849Scy	} else {
4149285169Scy#ifdef LEAP_SMEAR
4150285169Scy		/*
4151285169Scy		 * Make copies of the variables which can be affected by smearing.
4152285169Scy		 */
4153285169Scy		l_fp this_ref_time;
4154285169Scy		l_fp this_recv_time;
4155285169Scy#endif
4156285169Scy
4157285169Scy		/*
4158285169Scy		 * If we are inside the leap smear interval we add the current smear offset to
4159285169Scy		 * the packet receive time, to the packet transmit time, and eventually to the
4160285169Scy		 * reftime to make sure the reftime isn't later than the transmit/receive times.
4161285169Scy		 */
4162285169Scy		xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
416382505Sroberto		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4164285169Scy
416582505Sroberto		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4166280849Scy		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4167280849Scy		xpkt.precision = sys_precision;
416882505Sroberto		xpkt.refid = sys_refid;
4169182007Sroberto		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4170280849Scy		xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4171285169Scy
4172285169Scy#ifdef LEAP_SMEAR
4173285169Scy		this_ref_time = sys_reftime;
4174285169Scy		if (leap_smear.in_progress) {
4175285169Scy			leap_smear_add_offs(&this_ref_time, NULL);
4176285169Scy			xpkt.refid = convertLFPToRefID(leap_smear.offset);
4177285169Scy			DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4178285169Scy				ntohl(xpkt.refid),
4179285169Scy				lfptoa(&leap_smear.offset, 8)
4180285169Scy				));
4181285169Scy		}
4182285169Scy		HTONL_FP(&this_ref_time, &xpkt.reftime);
4183285169Scy#else
4184280849Scy		HTONL_FP(&sys_reftime, &xpkt.reftime);
4185285169Scy#endif
4186285169Scy
4187280849Scy		xpkt.org = rpkt->xmt;
4188285169Scy
4189285169Scy#ifdef LEAP_SMEAR
4190285169Scy		this_recv_time = rbufp->recv_time;
4191285169Scy		if (leap_smear.in_progress)
4192285169Scy			leap_smear_add_offs(&this_recv_time, NULL);
4193285169Scy		HTONL_FP(&this_recv_time, &xpkt.rec);
4194285169Scy#else
4195280849Scy		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4196285169Scy#endif
4197285169Scy
4198280849Scy		get_systime(&xmt_tx);
4199285169Scy#ifdef LEAP_SMEAR
4200285169Scy		if (leap_smear.in_progress)
4201285169Scy			leap_smear_add_offs(&xmt_tx, &this_recv_time);
4202285169Scy#endif
4203280849Scy		HTONL_FP(&xmt_tx, &xpkt.xmt);
4204280849Scy	}
4205182007Sroberto
4206280849Scy#ifdef HAVE_NTP_SIGND
4207280849Scy	if (flags & RES_MSSNTP) {
4208280849Scy		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4209280849Scy		return;
421082505Sroberto	}
4211280849Scy#endif /* HAVE_NTP_SIGND */
421282505Sroberto
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);
4222293423Sdelphij		DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4223132454Sroberto			    current_time, stoa(&rbufp->dstadr->sin),
4224293423Sdelphij			    stoa(&rbufp->recv_srcadr), xmode,
4225293423Sdelphij			    (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	 */
4237280849Scy#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);
4252293423Sdelphij		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);
4257280849Scy			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4258280849Scy			    sendlen, (struct exten *)rpkt->exten,
4259280849Scy			    cookie);
426082505Sroberto		} else {
426182505Sroberto			session_key(&rbufp->dstadr->sin,
426282505Sroberto			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
426382505Sroberto		}
426482505Sroberto	}
4265280849Scy#endif	/* AUTOKEY */
4266280849Scy	get_systime(&xmt_tx);
4267280849Scy	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4268280849Scy#ifdef AUTOKEY
426982505Sroberto	if (xkeyid > NTP_MAXKEY)
427082505Sroberto		authtrust(xkeyid, 0);
4271280849Scy#endif	/* AUTOKEY */
427282505Sroberto	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4273280849Scy	get_systime(&xmt_ty);
4274280849Scy	L_SUB(&xmt_ty, &xmt_tx);
4275280849Scy	sys_authdelay = xmt_ty;
4276293423Sdelphij	DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
427782505Sroberto		    current_time, ntoa(&rbufp->dstadr->sin),
4278293423Sdelphij		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4279293423Sdelphij		    (u_long)sendlen));
428054359Sroberto}
428154359Sroberto
428282505Sroberto
428354359Sroberto/*
4284280849Scy * pool_xmit - resolve hostname or send unicast solicitation for pool.
4285280849Scy */
4286280849Scystatic void
4287280849Scypool_xmit(
4288280849Scy	struct peer *pool	/* pool solicitor association */
4289280849Scy	)
4290280849Scy{
4291280849Scy#ifdef WORKER
4292280849Scy	struct pkt		xpkt;	/* transmit packet structure */
4293280849Scy	struct addrinfo		hints;
4294280849Scy	int			rc;
4295280849Scy	struct interface *	lcladr;
4296280849Scy	sockaddr_u *		rmtadr;
4297280849Scy	int			restrict_mask;
4298280849Scy	struct peer *		p;
4299280849Scy	l_fp			xmt_tx;
4300280849Scy
4301280849Scy	if (NULL == pool->ai) {
4302280849Scy		if (pool->addrs != NULL) {
4303280849Scy			/* free() is used with copy_addrinfo_list() */
4304280849Scy			free(pool->addrs);
4305280849Scy			pool->addrs = NULL;
4306280849Scy		}
4307280849Scy		ZERO(hints);
4308280849Scy		hints.ai_family = AF(&pool->srcadr);
4309280849Scy		hints.ai_socktype = SOCK_DGRAM;
4310280849Scy		hints.ai_protocol = IPPROTO_UDP;
4311280849Scy		/* ignore getaddrinfo_sometime() errors, we will retry */
4312280849Scy		rc = getaddrinfo_sometime(
4313280849Scy			pool->hostname,
4314280849Scy			"ntp",
4315280849Scy			&hints,
4316280849Scy			0,			/* no retry */
4317280849Scy			&pool_name_resolved,
4318280849Scy			(void *)(intptr_t)pool->associd);
4319280849Scy		if (!rc)
4320280849Scy			DPRINTF(1, ("pool DNS lookup %s started\n",
4321280849Scy				pool->hostname));
4322280849Scy		else
4323280849Scy			msyslog(LOG_ERR,
4324289764Sglebius				"unable to start pool DNS %s: %m",
4325280849Scy				pool->hostname);
4326280849Scy		return;
4327280849Scy	}
4328280849Scy
4329280849Scy	do {
4330280849Scy		/* copy_addrinfo_list ai_addr points to a sockaddr_u */
4331280849Scy		rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4332280849Scy		pool->ai = pool->ai->ai_next;
4333280849Scy		p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
4334280849Scy	} while (p != NULL && pool->ai != NULL);
4335280849Scy	if (p != NULL)
4336280849Scy		return;	/* out of addresses, re-query DNS next poll */
4337280849Scy	restrict_mask = restrictions(rmtadr);
4338280849Scy	if (RES_FLAGS & restrict_mask)
4339282408Scy		restrict_source(rmtadr, 0,
4340280849Scy				current_time + POOL_SOLICIT_WINDOW + 1);
4341280849Scy	lcladr = findinterface(rmtadr);
4342280849Scy	memset(&xpkt, 0, sizeof(xpkt));
4343280849Scy	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4344280849Scy					 MODE_CLIENT);
4345280849Scy	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4346280849Scy	xpkt.ppoll = pool->hpoll;
4347280849Scy	xpkt.precision = sys_precision;
4348280849Scy	xpkt.refid = sys_refid;
4349280849Scy	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4350280849Scy	xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4351280849Scy	HTONL_FP(&sys_reftime, &xpkt.reftime);
4352280849Scy	get_systime(&xmt_tx);
4353280849Scy	pool->aorg = xmt_tx;
4354280849Scy	HTONL_FP(&xmt_tx, &xpkt.xmt);
4355280849Scy	sendpkt(rmtadr, lcladr,	sys_ttl[pool->ttl], &xpkt,
4356280849Scy		LEN_PKT_NOMAC);
4357280849Scy	pool->sent++;
4358280849Scy	pool->throttle += (1 << pool->minpoll) - 2;
4359293423Sdelphij	DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4360293423Sdelphij		    current_time, latoa(lcladr), stoa(rmtadr)));
4361280849Scy	msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4362280849Scy#endif	/* WORKER */
4363280849Scy}
4364280849Scy
4365280849Scy
4366280849Scy#ifdef AUTOKEY
4367280849Scy	/*
4368280849Scy	 * group_test - test if this is the same group
4369280849Scy	 *
4370280849Scy	 * host		assoc		return		action
4371280849Scy	 * none		none		0		mobilize *
4372280849Scy	 * none		group		0		mobilize *
4373280849Scy	 * group	none		0		mobilize *
4374280849Scy	 * group	group		1		mobilize
4375280849Scy	 * group	different	1		ignore
4376280849Scy	 * * ignore if notrust
4377280849Scy	 */
4378293423Sdelphijint
4379293423Sdelphijgroup_test(
4380280849Scy	char	*grp,
4381280849Scy	char	*ident
4382280849Scy	)
4383280849Scy{
4384280849Scy	if (grp == NULL)
4385280849Scy		return (0);
4386280849Scy
4387280849Scy	if (strcmp(grp, sys_groupname) == 0)
4388280849Scy		return (0);
4389280849Scy
4390280849Scy	if (ident == NULL)
4391280849Scy		return (1);
4392280849Scy
4393280849Scy	if (strcmp(grp, ident) == 0)
4394280849Scy		return (0);
4395280849Scy
4396280849Scy	return (1);
4397280849Scy}
4398280849Scy#endif /* AUTOKEY */
4399280849Scy
4400298695Sdelphij
4401280849Scy#ifdef WORKER
4402280849Scyvoid
4403280849Scypool_name_resolved(
4404280849Scy	int			rescode,
4405280849Scy	int			gai_errno,
4406280849Scy	void *			context,
4407280849Scy	const char *		name,
4408280849Scy	const char *		service,
4409280849Scy	const struct addrinfo *	hints,
4410280849Scy	const struct addrinfo *	res
4411280849Scy	)
4412280849Scy{
4413280849Scy	struct peer *	pool;	/* pool solicitor association */
4414280849Scy	associd_t	assoc;
4415280849Scy
4416280849Scy	if (rescode) {
4417280849Scy		msyslog(LOG_ERR,
4418280849Scy			"error resolving pool %s: %s (%d)",
4419280849Scy			name, gai_strerror(rescode), rescode);
4420280849Scy		return;
4421280849Scy	}
4422280849Scy
4423280849Scy	assoc = (associd_t)(intptr_t)context;
4424280849Scy	pool = findpeerbyassoc(assoc);
4425280849Scy	if (NULL == pool) {
4426280849Scy		msyslog(LOG_ERR,
4427280849Scy			"Could not find assoc %u for pool DNS %s",
4428280849Scy			assoc, name);
4429280849Scy		return;
4430280849Scy	}
4431280849Scy	DPRINTF(1, ("pool DNS %s completed\n", name));
4432280849Scy	pool->addrs = copy_addrinfo_list(res);
4433280849Scy	pool->ai = pool->addrs;
4434280849Scy	pool_xmit(pool);
4435280849Scy
4436280849Scy}
4437280849Scy#endif	/* WORKER */
4438280849Scy
4439280849Scy
4440280849Scy#ifdef AUTOKEY
4441280849Scy/*
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;
4459280849Scy	peer->flags &= ~FLAG_ASSOC;
4460293423Sdelphij	DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4461293423Sdelphij		    peer->associd));
446254359Sroberto}
4463280849Scy#endif	/* AUTOKEY */
446454359Sroberto
4465132454Sroberto
446654359Sroberto/*
4467280849Scy * local_refid(peer) - check peer refid to avoid selecting peers
4468280849Scy *		       currently synced to this ntpd.
4469280849Scy */
4470280849Scystatic int
4471280849Scylocal_refid(
4472280849Scy	struct peer *	p
4473280849Scy	)
4474280849Scy{
4475280849Scy	endpt *	unicast_ep;
4476280849Scy
4477280849Scy	if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4478280849Scy		unicast_ep = p->dstadr;
4479280849Scy	else
4480280849Scy		unicast_ep = findinterface(&p->srcadr);
4481280849Scy
4482280849Scy	if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4483280849Scy		return TRUE;
4484280849Scy	else
4485280849Scy		return FALSE;
4486280849Scy}
4487280849Scy
4488280849Scy
4489280849Scy/*
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
4494280849Scy * > 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
4508280849Scy	 * greater than or equal to the ceiling.
4509182007Sroberto	 */
4510289764Sglebius	if (   peer->leap == LEAP_NOTINSYNC
4511289764Sglebius	    || peer->stratum < sys_floor
4512309007Sdelphij	    || peer->stratum >= sys_ceiling) {
4513280849Scy		rval |= TEST10;		/* bad synch or stratum */
4514309007Sdelphij	}
4515182007Sroberto
4516182007Sroberto	/*
4517280849Scy	 * A distance error for a remote peer occurs if the root
4518280849Scy	 * distance is greater than or equal to the distance threshold
4519280849Scy	 * plus the increment due to one host poll interval.
4520182007Sroberto	 */
4521289764Sglebius	if (   !(peer->flags & FLAG_REFCLOCK)
4522289764Sglebius	    && root_distance(peer) >= sys_maxdist
4523309007Sdelphij				      + clock_phi * ULOGTOD(peer->hpoll)) {
4524182007Sroberto		rval |= TEST11;		/* distance exceeded */
4525309007Sdelphij	}
4526182007Sroberto
4527182007Sroberto	/*
4528182007Sroberto	 * A loop error occurs if the remote peer is synchronized to the
4529280849Scy	 * local peer or if the remote peer is synchronized to the same
4530280849Scy	 * server as the local peer but only if the remote peer is
4531280849Scy	 * neither a reference clock nor an orphan.
4532182007Sroberto	 */
4533309007Sdelphij	if (peer->stratum > 1 && local_refid(peer)) {
4534280849Scy		rval |= TEST12;		/* synchronization loop */
4535309007Sdelphij	}
4536182007Sroberto
4537182007Sroberto	/*
4538182007Sroberto	 * An unreachable error occurs if the server is unreachable or
4539182007Sroberto	 * the noselect bit is set.
4540182007Sroberto	 */
4541309007Sdelphij	if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
4542182007Sroberto		rval |= TEST13;		/* unreachable */
4543309007Sdelphij	}
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 */
4554280849Scy#define MINSTEP		20e-9	/* minimum clock increment (s) */
4555280849Scy#define MAXSTEP		1	/* maximum clock increment (s) */
4556280849Scy#define MINCHANGES	12	/* minimum number of step samples */
4557280849Scy#define MAXLOOPS	((int)(1. / MINSTEP))	/* avoid infinite loop */
455854359Sroberto
455954359Sroberto/*
4560280849Scy * This routine measures the system precision defined as the minimum of
4561280849Scy * a sequence of differences between successive readings of the system
4562280849Scy * clock. However, if a difference is less than MINSTEP, the clock has
4563280849Scy * been read more than once during a clock tick and the difference is
4564280849Scy * ignored. We set MINSTEP greater than zero in case something happens
4565280849Scy * like a cache miss, and to tolerate underlying system clocks which
4566280849Scy * ensure each reading is strictly greater than prior readings while
4567280849Scy * using an underlying stepping (not interpolated) clock.
4568132454Sroberto *
4569280849Scy * sys_tick and sys_precision represent the time to read the clock for
4570280849Scy * systems with high-precision clocks, and the tick interval or step
4571280849Scy * size for lower-precision stepping clocks.
4572280849Scy *
4573280849Scy * This routine also measures the time to read the clock on stepping
4574280849Scy * system clocks by counting the number of readings between changes of
4575280849Scy * the underlying clock.  With either type of clock, the minimum time
4576280849Scy * to read the clock is saved as sys_fuzz, and used to ensure the
4577280849Scy * get_systime() readings always increase and are fuzzed below sys_fuzz.
457854359Sroberto */
4579280849Scyvoid
4580280849Scymeasure_precision(void)
458154359Sroberto{
4582280849Scy	/*
4583280849Scy	 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4584280849Scy	 * is effectively disabled.  trunc_os_clock is FALSE to disable
4585280849Scy	 * get_ostime() simulation of a low-precision system clock.
4586280849Scy	 */
4587280849Scy	set_sys_fuzz(0.);
4588280849Scy	trunc_os_clock = FALSE;
4589280849Scy	measured_tick = measure_tick_fuzz();
4590280849Scy	set_sys_tick_precision(measured_tick);
4591280849Scy	msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4592280849Scy		sys_tick * 1e6, sys_precision);
4593280849Scy	if (sys_fuzz < sys_tick) {
4594280849Scy		msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4595280849Scy			sys_fuzz * 1e6);
4596280849Scy	}
4597280849Scy}
4598280849Scy
4599280849Scy
4600280849Scy/*
4601280849Scy * measure_tick_fuzz()
4602280849Scy *
4603280849Scy * measures the minimum time to read the clock (stored in sys_fuzz)
4604280849Scy * and returns the tick, the larger of the minimum increment observed
4605280849Scy * between successive clock readings and the time to read the clock.
4606280849Scy */
4607280849Scydouble
4608280849Scymeasure_tick_fuzz(void)
4609280849Scy{
4610280849Scy	l_fp	minstep;	/* MINSTEP as l_fp */
4611132454Sroberto	l_fp	val;		/* current seconds fraction */
4612132454Sroberto	l_fp	last;		/* last seconds fraction */
4613280849Scy	l_fp	ldiff;		/* val - last */
4614132454Sroberto	double	tick;		/* computed tick value */
4615280849Scy	double	diff;
4616280849Scy	long	repeats;
4617280849Scy	long	max_repeats;
4618280849Scy	int	changes;
4619132454Sroberto	int	i;		/* log2 precision */
462054359Sroberto
4621280849Scy	tick = MAXSTEP;
4622280849Scy	max_repeats = 0;
4623280849Scy	repeats = 0;
4624280849Scy	changes = 0;
4625280849Scy	DTOLFP(MINSTEP, &minstep);
4626132454Sroberto	get_systime(&last);
4627280849Scy	for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4628132454Sroberto		get_systime(&val);
4629280849Scy		ldiff = val;
4630280849Scy		L_SUB(&ldiff, &last);
4631132454Sroberto		last = val;
4632280849Scy		if (L_ISGT(&ldiff, &minstep)) {
4633280849Scy			max_repeats = max(repeats, max_repeats);
4634280849Scy			repeats = 0;
4635280849Scy			changes++;
4636280849Scy			LFPTOD(&ldiff, diff);
4637280849Scy			tick = min(diff, tick);
4638280849Scy		} else {
4639280849Scy			repeats++;
4640280849Scy		}
464154359Sroberto	}
4642280849Scy	if (changes < MINCHANGES) {
4643280849Scy		msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4644280849Scy		exit(1);
4645280849Scy	}
4646132454Sroberto
4647280849Scy	if (0 == max_repeats) {
4648280849Scy		set_sys_fuzz(tick);
4649280849Scy	} else {
4650280849Scy		set_sys_fuzz(tick / max_repeats);
4651280849Scy	}
4652280849Scy
4653280849Scy	return tick;
4654280849Scy}
4655280849Scy
4656280849Scy
4657280849Scyvoid
4658280849Scyset_sys_tick_precision(
4659280849Scy	double tick
4660280849Scy	)
4661280849Scy{
4662280849Scy	int i;
4663280849Scy
4664280849Scy	if (tick > 1.) {
4665280849Scy		msyslog(LOG_ERR,
4666280849Scy			"unsupported tick %.3f > 1s ignored", tick);
4667280849Scy		return;
4668280849Scy	}
4669280849Scy	if (tick < measured_tick) {
4670280849Scy		msyslog(LOG_ERR,
4671280849Scy			"proto: tick %.3f less than measured tick %.3f, ignored",
4672280849Scy			tick, measured_tick);
4673280849Scy		return;
4674280849Scy	} else if (tick > measured_tick) {
4675280849Scy		trunc_os_clock = TRUE;
4676280849Scy		msyslog(LOG_NOTICE,
4677280849Scy			"proto: truncating system clock to multiples of %.9f",
4678280849Scy			tick);
4679280849Scy	}
4680280849Scy	sys_tick = tick;
4681280849Scy
4682132454Sroberto	/*
4683132454Sroberto	 * Find the nearest power of two.
4684132454Sroberto	 */
4685280849Scy	for (i = 0; tick <= 1; i--)
4686132454Sroberto		tick *= 2;
4687280849Scy	if (tick - 1 > 1 - tick / 2)
4688280849Scy		i++;
468954359Sroberto
4690280849Scy	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
4705280849Scy	 * broadcasting, require authentication.
470654359Sroberto	 */
4707285169Scy	set_sys_leap(LEAP_NOTINSYNC);
470854359Sroberto	sys_stratum = STRATUM_UNSPEC;
4709132454Sroberto	memcpy(&sys_refid, "INIT", 4);
4710280849Scy	sys_peer = NULL;
471154359Sroberto	sys_rootdelay = 0;
4712280849Scy	sys_rootdisp = 0;
471354359Sroberto	L_CLR(&sys_reftime);
4714280849Scy	sys_jitter = 0;
4715280849Scy	measure_precision();
4716280849Scy	get_systime(&dummy);
471782505Sroberto	sys_survivors = 0;
4718132454Sroberto	sys_manycastserver = 0;
471954359Sroberto	sys_bclient = 0;
4720298695Sdelphij	sys_bdelay = BDELAY_DEFAULT;	/*[Bug 3031] delay cutoff */
472154359Sroberto	sys_authenticate = 1;
4722280849Scy	sys_stattime = current_time;
4723280849Scy	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	}
4729280849Scy	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,
4742280849Scy	sockaddr_u *svalue
474354359Sroberto	)
474454359Sroberto{
474554359Sroberto	/*
474654359Sroberto	 * Figure out what he wants to change, then do it
474754359Sroberto	 */
4748280849Scy	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4749280849Scy		    item, value, dvalue));
4750280849Scy
475154359Sroberto	switch (item) {
4752132454Sroberto
4753132454Sroberto	/*
4754280849Scy	 * enable and disable commands - arguments are Boolean.
4755132454Sroberto	 */
4756280849Scy	case PROTO_AUTHENTICATE: /* authentication (auth) */
4757280849Scy		sys_authenticate = value;
475854359Sroberto		break;
475954359Sroberto
4760280849Scy	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4761280849Scy		sys_bclient = (int)value;
4762280849Scy		if (sys_bclient == 0)
4763280849Scy			io_unsetbclient();
4764280849Scy		else
4765280849Scy			io_setbclient();
476654359Sroberto		break;
476754359Sroberto
4768280849Scy#ifdef REFCLOCK
4769280849Scy	case PROTO_CAL:		/* refclock calibrate (calibrate) */
4770280849Scy		cal_enable = value;
4771280849Scy		break;
4772280849Scy#endif /* REFCLOCK */
4773280849Scy
4774280849Scy	case PROTO_KERNEL:	/* kernel discipline (kernel) */
4775280849Scy		select_loop(value);
4776280849Scy		break;
4777280849Scy
4778280849Scy	case PROTO_MONITOR:	/* monitoring (monitor) */
477954359Sroberto		if (value)
478054359Sroberto			mon_start(MON_ON);
4781285169Scy		else {
478254359Sroberto			mon_stop(MON_ON);
4783285169Scy			if (mon_enabled)
4784285169Scy				msyslog(LOG_WARNING,
4785285169Scy					"restrict: 'monitor' cannot be disabled while 'limited' is enabled");
4786285169Scy		}
478754359Sroberto		break;
478854359Sroberto
4789280849Scy	case PROTO_NTP:		/* NTP discipline (ntp) */
4790280849Scy		ntp_enable = value;
479154359Sroberto		break;
479254359Sroberto
4793280849Scy	case PROTO_MODE7:	/* mode7 management (ntpdc) */
4794280849Scy		ntp_mode7 = value;
479554359Sroberto		break;
479654359Sroberto
4797280849Scy	case PROTO_PPS:		/* PPS discipline (pps) */
4798280849Scy		hardpps_enable = value;
4799182007Sroberto		break;
4800182007Sroberto
4801280849Scy	case PROTO_FILEGEN:	/* statistics (stats) */
4802280849Scy		stats_control = value;
480354359Sroberto		break;
480454359Sroberto
4805132454Sroberto	/*
4806280849Scy	 * tos command - arguments are double, sometimes cast to int
4807132454Sroberto	 */
4808309007Sdelphij
4809309007Sdelphij	case PROTO_BCPOLLBSTEP:	/* Broadcast Poll Backstep gate (bcpollbstep) */
4810309007Sdelphij		sys_bcpollbstep = (u_char)dvalue;
4811309007Sdelphij		break;
4812309007Sdelphij
4813280849Scy	case PROTO_BEACON:	/* manycast beacon (beacon) */
4814280849Scy		sys_beacon = (int)dvalue;
481554359Sroberto		break;
481654359Sroberto
4817280849Scy	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
4818298695Sdelphij		sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
481954359Sroberto		break;
482054359Sroberto
4821280849Scy	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
4822280849Scy		sys_ceiling = (int)dvalue;
4823132454Sroberto		break;
4824132454Sroberto
4825280849Scy	case PROTO_COHORT:	/* cohort switch (cohort) */
4826280849Scy		sys_cohort = (int)dvalue;
482754359Sroberto		break;
482854359Sroberto
4829280849Scy	case PROTO_FLOOR:	/* stratum floor (floor) */
4830280849Scy		sys_floor = (int)dvalue;
483182505Sroberto		break;
483282505Sroberto
4833280849Scy	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
4834182007Sroberto		sys_maxclock = (int)dvalue;
4835132454Sroberto		break;
4836132454Sroberto
4837280849Scy	case PROTO_MAXDIST:	/* select threshold (maxdist) */
4838280849Scy		sys_maxdist = dvalue;
4839132454Sroberto		break;
4840132454Sroberto
4841280849Scy	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
4842280849Scy		break;		/* NOT USED */
4843132454Sroberto
4844280849Scy	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
4845280849Scy		sys_minclock = (int)dvalue;
4846132454Sroberto		break;
4847132454Sroberto
4848280849Scy	case PROTO_MINDISP:	/* minimum distance (mindist) */
4849280849Scy		sys_mindisp = dvalue;
4850182007Sroberto		break;
4851182007Sroberto
4852280849Scy	case PROTO_MINSANE:	/* minimum survivors (minsane) */
4853280849Scy		sys_minsane = (int)dvalue;
4854132454Sroberto		break;
4855182007Sroberto
4856280849Scy	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
4857280849Scy		sys_orphan = (int)dvalue;
4858182007Sroberto		break;
4859182007Sroberto
4860280849Scy	case PROTO_ORPHWAIT:	/* orphan wait (orphwait) */
4861280849Scy		orphwait -= sys_orphwait;
4862280849Scy		sys_orphwait = (int)dvalue;
4863280849Scy		orphwait += sys_orphwait;
4864182007Sroberto		break;
4865182007Sroberto
4866182007Sroberto	/*
4867280849Scy	 * Miscellaneous commands
4868182007Sroberto	 */
4869280849Scy	case PROTO_MULTICAST_ADD: /* add group address */
4870280849Scy		if (svalue != NULL)
4871280849Scy			io_multicast_add(svalue);
4872280849Scy		sys_bclient = 1;
4873182007Sroberto		break;
4874182007Sroberto
4875280849Scy	case PROTO_MULTICAST_DEL: /* delete group address */
4876280849Scy		if (svalue != NULL)
4877280849Scy			io_multicast_del(svalue);
4878132454Sroberto		break;
4879132454Sroberto
4880294554Sdelphij	/*
4881301247Sdelphij	 * Peer_clear Early policy choices
4882301247Sdelphij	 */
4883301247Sdelphij
4884301247Sdelphij	case PROTO_PCEDIGEST:	/* Digest */
4885301247Sdelphij		peer_clear_digest_early = value;
4886301247Sdelphij		break;
4887301247Sdelphij
4888301247Sdelphij	/*
4889294554Sdelphij	 * Unpeer Early policy choices
4890294554Sdelphij	 */
4891294554Sdelphij
4892294554Sdelphij	case PROTO_UECRYPTO:	/* Crypto */
4893294554Sdelphij		unpeer_crypto_early = value;
4894294554Sdelphij		break;
4895294554Sdelphij
4896294554Sdelphij	case PROTO_UECRYPTONAK:	/* Crypto_NAK */
4897294554Sdelphij		unpeer_crypto_nak_early = value;
4898294554Sdelphij		break;
4899294554Sdelphij
4900294554Sdelphij	case PROTO_UEDIGEST:	/* Digest */
4901294554Sdelphij		unpeer_digest_early = value;
4902294554Sdelphij		break;
4903294554Sdelphij
490456749Sroberto	default:
4905280849Scy		msyslog(LOG_NOTICE,
4906280849Scy		    "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;
4920280849Scy	sys_newversion = 0;
4921280849Scy	sys_oldversion = 0;
4922280849Scy	sys_declined = 0;
4923132454Sroberto	sys_restricted = 0;
492454359Sroberto	sys_badlength = 0;
492554359Sroberto	sys_badauth = 0;
492654359Sroberto	sys_limitrejected = 0;
4927280849Scy	sys_kodsent = 0;
492854359Sroberto}
4929