xref: /netbsd/external/bsd/ntp/dist/ntpd/ntp_proto.c (revision e03b00c8)
1 /*	$NetBSD: ntp_proto.c,v 1.19 2022/10/09 21:41:03 christos Exp $	*/
2 
3 /*
4  * ntp_proto.c - NTP version 4 protocol machinery
5  *
6  * ATTENTION: Get approval from Harlan on all changes to this file!
7  *	    (Harlan will be discussing these changes with Dave Mills.)
8  *
9  */
10 #ifdef HAVE_CONFIG_H
11 #include <config.h>
12 #endif
13 
14 #include "ntpd.h"
15 #include "ntp_stdlib.h"
16 #include "ntp_unixtime.h"
17 #include "ntp_control.h"
18 #include "ntp_string.h"
19 #include "ntp_leapsec.h"
20 #include "ntp_psl.h"
21 #include "refidsmear.h"
22 #include "lib_strbuf.h"
23 
24 #include <stdio.h>
25 #ifdef HAVE_LIBSCF_H
26 #include <libscf.h>
27 #endif
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 
32 /* [Bug 3031] define automatic broadcastdelay cutoff preset */
33 #ifndef BDELAY_DEFAULT
34 # define BDELAY_DEFAULT (-0.050)
35 #endif
36 
37 #define SRVFUZ_SHIFT	6	/* 64 seconds */
38 #define SRVRSP_FUZZ(x)					\
39 	do {						\
40 		x.l_uf &= 0;				\
41 		x.l_ui &= ~((1 << SRVFUZ_SHIFT) - 1U);	\
42 	} while(0)
43 
44 /*
45  * This macro defines the authentication state. If x is 1 authentication
46  * is required; otherwise it is optional.
47  */
48 #define	AUTH(x, y)	((x) ? (y) == AUTH_OK \
49 			     : (y) == AUTH_OK || (y) == AUTH_NONE)
50 
51 typedef enum
52 auth_state {
53 	AUTH_UNKNOWN = -1,	/* Unknown */
54 	AUTH_NONE,		/* authentication not required */
55 	AUTH_OK,		/* authentication OK */
56 	AUTH_ERROR,		/* authentication error */
57 	AUTH_CRYPTO		/* crypto_NAK */
58 } auth_code;
59 
60 /*
61  * Set up Kiss Code values
62  */
63 
64 typedef enum
65 kiss_codes {
66 	NOKISS,				/* No Kiss Code */
67 	RATEKISS,			/* Rate limit Kiss Code */
68 	DENYKISS,			/* Deny Kiss */
69 	RSTRKISS,			/* Restricted Kiss */
70 	XKISS				/* Experimental Kiss */
71 } kiss_code;
72 
73 typedef enum
74 nak_error_codes {
75 	NONAK,				/* No NAK seen */
76 	INVALIDNAK,			/* NAK cannot be used */
77 	VALIDNAK			/* NAK is valid */
78 } nak_code;
79 
80 /*
81  * traffic shaping parameters
82  */
83 #define	NTP_IBURST	6	/* packets in iburst */
84 #define	RESP_DELAY	1	/* refclock burst delay (s) */
85 
86 /*
87  * pool soliciting restriction duration (s)
88  */
89 #define	POOL_SOLICIT_WINDOW	8
90 
91 /*
92  * flag bits propagated from pool to individual peers
93  */
94 #define POOL_FLAG_PMASK		(FLAG_IBURST | FLAG_NOSELECT)
95 
96 /*
97  * peer_select groups statistics for a peer used by clock_select() and
98  * clock_cluster().
99  */
100 typedef struct peer_select_tag {
101 	struct peer *	peer;
102 	double		synch;	/* sync distance */
103 	double		error;	/* jitter */
104 	double		seljit;	/* selection jitter */
105 } peer_select;
106 
107 /*
108  * System variables are declared here. Unless specified otherwise, all
109  * times are in seconds.
110  */
111 u_char	sys_leap;		/* system leap indicator, use set_sys_leap() to change this */
112 u_char	xmt_leap;		/* leap indicator sent in client requests, set up by set_sys_leap() */
113 u_char	sys_stratum;		/* system stratum */
114 s_char	sys_precision;		/* local clock precision (log2 s) */
115 double	sys_rootdelay;		/* roundtrip delay to root (primary source) */
116 double	sys_rootdisp;		/* dispersion to root (primary source) */
117 double	prev_rootdisp;		/* previous root dispersion */
118 double	p2_rootdisp;		/* previous previous root dispersion */
119 u_int32 sys_refid;		/* reference id (network byte order) */
120 l_fp	sys_reftime;		/* last update time */
121 l_fp	prev_reftime;		/* previous sys_reftime */
122 l_fp	p2_reftime;		/* previous previous sys_reftime */
123 u_long	prev_time;		/* "current_time" when saved prev_time */
124 u_long	p2_time;		/* previous prev_time */
125 struct	peer *sys_peer;		/* current peer */
126 
127 #ifdef LEAP_SMEAR
128 struct leap_smear_info leap_smear;
129 #endif
130 int leap_sec_in_progress;
131 
132 /*
133  * Rate controls. Leaky buckets are used to throttle the packet
134  * transmission rates in order to protect busy servers such as at NIST
135  * and USNO. There is a counter for each association and another for KoD
136  * packets. The association counter decrements each second, but not
137  * below zero. Each time a packet is sent the counter is incremented by
138  * a configurable value representing the average interval between
139  * packets. A packet is delayed as long as the counter is greater than
140  * zero. Note this does not affect the time value computations.
141  */
142 /*
143  * Nonspecified system state variables
144  */
145 int	sys_bclient;		/* broadcast client enable */
146 double	sys_bdelay;		/* broadcast client default delay */
147 int	sys_authenticate;	/* requre authentication for config */
148 l_fp	sys_authdelay;		/* authentication delay */
149 double	sys_offset;	/* current local clock offset */
150 double	sys_mindisp = MINDISPERSE; /* minimum distance (s) */
151 double	sys_maxdist = MAXDISTANCE; /* selection threshold */
152 double	sys_jitter;		/* system jitter */
153 u_long	sys_epoch;		/* last clock update time */
154 static	double sys_clockhop;	/* clockhop threshold */
155 static int leap_vote_ins;	/* leap consensus for insert */
156 static int leap_vote_del;	/* leap consensus for delete */
157 keyid_t	sys_private;		/* private value for session seed */
158 int	sys_manycastserver;	/* respond to manycast client pkts */
159 int	ntp_mode7;		/* respond to ntpdc (mode7) */
160 int	peer_ntpdate;		/* active peers in ntpdate mode */
161 int	sys_survivors;		/* truest of the truechimers */
162 char	*sys_ident = NULL;	/* identity scheme */
163 
164 /*
165  * TOS and multicast mapping stuff
166  */
167 int	sys_floor = 0;		/* cluster stratum floor */
168 u_char	sys_bcpollbstep = 0;	/* Broadcast Poll backstep gate */
169 int	sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
170 int	sys_minsane = 1;	/* minimum candidates */
171 int	sys_minclock = NTP_MINCLOCK; /* minimum candidates */
172 int	sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
173 int	sys_cohort = 0;		/* cohort switch */
174 int	sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
175 int	sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
176 int	sys_beacon = BEACON;	/* manycast beacon interval */
177 u_int	sys_ttlmax;		/* max ttl mapping vector index */
178 u_char	sys_ttl[MAX_TTL];	/* ttl mapping vector */
179 
180 /*
181  * Statistics counters - first the good, then the bad
182  */
183 u_long	sys_stattime;		/* elapsed time */
184 u_long	sys_received;		/* packets received */
185 u_long	sys_processed;		/* packets for this host */
186 u_long	sys_newversion;		/* current version */
187 u_long	sys_oldversion;		/* old version */
188 u_long	sys_restricted;		/* access denied */
189 u_long	sys_badlength;		/* bad length or format */
190 u_long	sys_badauth;		/* bad authentication */
191 u_long	sys_declined;		/* declined */
192 u_long	sys_limitrejected;	/* rate exceeded */
193 u_long	sys_kodsent;		/* KoD sent */
194 
195 /*
196  * Mechanism knobs: how soon do we peer_clear() or unpeer()?
197  *
198  * The default way is "on-receipt".  If this was a packet from a
199  * well-behaved source, on-receipt will offer the fastest recovery.
200  * If this was from a DoS attack, the default way makes it easier
201  * for a bad-guy to DoS us.  So look and see what bites you harder
202  * and choose according to your environment.
203  */
204 int peer_clear_digest_early	= 1;	/* bad digest (TEST5) and Autokey */
205 int unpeer_crypto_early		= 1;	/* bad crypto (TEST9) */
206 int unpeer_crypto_nak_early	= 1;	/* crypto_NAK (TEST5) */
207 int unpeer_digest_early		= 1;	/* bad digest (TEST5) */
208 
209 int dynamic_interleave = DYNAMIC_INTERLEAVE;	/* Bug 2978 mitigation */
210 
211 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
212 nak_code	valid_NAK	(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
213 static	double	root_distance	(struct peer *);
214 static	void	clock_combine	(peer_select *, int, int);
215 static	void	peer_xmit	(struct peer *);
216 static	void	fast_xmit	(struct recvbuf *, int, keyid_t, int);
217 static	void	pool_xmit	(struct peer *);
218 static	void	clock_update	(struct peer *);
219 static	void	measure_precision(void);
220 static	double	measure_tick_fuzz(void);
221 static	int	local_refid	(struct peer *);
222 static	int	peer_unfit	(struct peer *);
223 #ifdef AUTOKEY
224 static	int	group_test	(char *, char *);
225 #endif /* AUTOKEY */
226 #ifdef WORKER
227 void	pool_name_resolved	(int, int, void *, const char *,
228 				 const char *, const struct addrinfo *,
229 				 const struct addrinfo *);
230 #endif /* WORKER */
231 
232 const char *	amtoa		(int am);
233 
234 
235 void
set_sys_leap(u_char new_sys_leap)236 set_sys_leap(
237 	u_char new_sys_leap
238 	)
239 {
240 	sys_leap = new_sys_leap;
241 	xmt_leap = sys_leap;
242 
243 	/*
244 	 * Under certain conditions we send faked leap bits to clients, so
245 	 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
246 	 */
247 	if (xmt_leap != LEAP_NOTINSYNC) {
248 		if (leap_sec_in_progress) {
249 			/* always send "not sync" */
250 			xmt_leap = LEAP_NOTINSYNC;
251 		}
252 #ifdef LEAP_SMEAR
253 		else {
254 			/*
255 			 * If leap smear is enabled in general we must
256 			 * never send a leap second warning to clients,
257 			 * so make sure we only send "in sync".
258 			 */
259 			if (leap_smear.enabled)
260 				xmt_leap = LEAP_NOWARNING;
261 		}
262 #endif	/* LEAP_SMEAR */
263 	}
264 }
265 
266 
267 /*
268  * Kiss Code check
269  */
270 int
kiss_code_check(u_char hisleap,u_char hisstratum,u_char hismode,u_int32 refid)271 kiss_code_check(
272 	u_char hisleap,
273 	u_char hisstratum,
274 	u_char hismode,
275 	u_int32 refid
276 	)
277 {
278 
279 	if (   hismode == MODE_SERVER
280 	    && hisleap == LEAP_NOTINSYNC
281 	    && hisstratum == STRATUM_UNSPEC) {
282 		if(memcmp(&refid,"RATE", 4) == 0) {
283 			return (RATEKISS);
284 		} else if(memcmp(&refid,"DENY", 4) == 0) {
285 			return (DENYKISS);
286 		} else if(memcmp(&refid,"RSTR", 4) == 0) {
287 			return (RSTRKISS);
288 		} else if(memcmp(&refid,"X", 1) == 0) {
289 			return (XKISS);
290 		}
291 	}
292 	return (NOKISS);
293 }
294 
295 
296 /*
297  * Check that NAK is valid
298  */
299 nak_code
valid_NAK(struct peer * peer,struct recvbuf * rbufp,u_char hismode)300 valid_NAK(
301 	  struct peer *peer,
302 	  struct recvbuf *rbufp,
303 	  u_char hismode
304 	  )
305 {
306 	int		base_packet_length = MIN_V4_PKT_LEN;
307 	int		remainder_size;
308 	struct pkt *	rpkt;
309 	int		keyid;
310 	l_fp		p_org;	/* origin timestamp */
311 	const l_fp *	myorg;	/* selected peer origin */
312 
313 	/*
314 	 * Check to see if there is something beyond the basic packet
315 	 */
316 	if (rbufp->recv_length == base_packet_length) {
317 		return NONAK;
318 	}
319 
320 	remainder_size = rbufp->recv_length - base_packet_length;
321 	/*
322 	 * Is this a potential NAK?
323 	 */
324 	if (remainder_size != 4) {
325 		return NONAK;
326 	}
327 
328 	/*
329 	 * Only server responses can contain NAK's
330 	 */
331 
332 	if (hismode != MODE_SERVER &&
333 	    hismode != MODE_ACTIVE &&
334 	    hismode != MODE_PASSIVE
335 	    ) {
336 		return INVALIDNAK;
337 	}
338 
339 	/*
340 	 * Make sure that the extra field in the packet is all zeros
341 	 */
342 	rpkt = &rbufp->recv_pkt;
343 	keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
344 	if (keyid != 0) {
345 		return INVALIDNAK;
346 	}
347 
348 	/*
349 	 * During the first few packets of the autokey dance there will
350 	 * not (yet) be a keyid, but in this case FLAG_SKEY is set.
351 	 * So the NAK is invalid if either there's no peer, or
352 	 * if the keyid is 0 and FLAG_SKEY is not set.
353 	 */
354 	if (!peer || (!peer->keyid && !(peer->flags & FLAG_SKEY))) {
355 		return INVALIDNAK;
356 	}
357 
358 	/*
359 	 * The ORIGIN must match, or this cannot be a valid NAK, either.
360 	 */
361 
362 	if (FLAG_LOOPNONCE & peer->flags) {
363 		myorg = &peer->nonce;
364 	} else {
365 		if (peer->flip > 0) {
366 			myorg = &peer->borg;
367 		} else {
368 			myorg = &peer->aorg;
369 		}
370 	}
371 
372 	NTOHL_FP(&rpkt->org, &p_org);
373 
374 	if (L_ISZERO(&p_org) ||
375 	    L_ISZERO( myorg) ||
376 	    !L_ISEQU(&p_org, myorg)) {
377 		return INVALIDNAK;
378 	}
379 
380 	/* If we ever passed all that checks, we should be safe. Well,
381 	 * as safe as we can ever be with an unauthenticated crypto-nak.
382 	 */
383 	return VALIDNAK;
384 }
385 
386 
387 /*
388  * transmit - transmit procedure called by poll timeout
389  */
390 void
transmit(struct peer * peer)391 transmit(
392 	struct peer *peer	/* peer structure pointer */
393 	)
394 {
395 	u_char	hpoll;
396 
397 	/*
398 	 * The polling state machine. There are two kinds of machines,
399 	 * those that never expect a reply (broadcast and manycast
400 	 * server modes) and those that do (all other modes). The dance
401 	 * is intricate...
402 	 */
403 	hpoll = peer->hpoll;
404 
405 	/*
406 	 * If we haven't received anything (even if unsync) since last
407 	 * send, reset ppoll.
408 	 */
409 	if (peer->outdate > peer->timelastrec && !peer->reach)
410 		peer->ppoll = peer->maxpoll;
411 
412 	/*
413 	 * In broadcast mode the poll interval is never changed from
414 	 * minpoll.
415 	 */
416 	if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
417 		peer->outdate = current_time;
418 		poll_update(peer, hpoll, 0);
419 		if (sys_leap != LEAP_NOTINSYNC)
420 			peer_xmit(peer);
421 		return;
422 	}
423 
424 	/*
425 	 * In manycast mode we start with unity ttl. The ttl is
426 	 * increased by one for each poll until either sys_maxclock
427 	 * servers have been found or the maximum ttl is reached. When
428 	 * sys_maxclock servers are found we stop polling until one or
429 	 * more servers have timed out or until less than sys_minclock
430 	 * associations turn up. In this case additional better servers
431 	 * are dragged in and preempt the existing ones.  Once every
432 	 * sys_beacon seconds we are to transmit unconditionally, but
433 	 * this code is not quite right -- peer->unreach counts polls
434 	 * and is being compared with sys_beacon, so the beacons happen
435 	 * every sys_beacon polls.
436 	 */
437 	if (peer->cast_flags & MDF_ACAST) {
438 		peer->outdate = current_time;
439 		poll_update(peer, hpoll, 0);
440 		if (peer->unreach > sys_beacon) {
441 			peer->unreach = 0;
442 			peer->ttl = 0;
443 			peer_xmit(peer);
444 		} else if (   sys_survivors < sys_minclock
445 			   || peer_associations < sys_maxclock) {
446 			if (peer->ttl < sys_ttlmax)
447 				peer->ttl++;
448 			peer_xmit(peer);
449 		}
450 		peer->unreach++;
451 		return;
452 	}
453 
454 	/*
455 	 * Pool associations transmit unicast solicitations when there
456 	 * are less than a hard limit of 2 * sys_maxclock associations,
457 	 * and either less than sys_minclock survivors or less than
458 	 * sys_maxclock associations.  The hard limit prevents unbounded
459 	 * growth in associations if the system clock or network quality
460 	 * result in survivor count dipping below sys_minclock often.
461 	 * This was observed testing with pool, where sys_maxclock == 12
462 	 * resulted in 60 associations without the hard limit.  A
463 	 * similar hard limit on manycastclient ephemeral associations
464 	 * may be appropriate.
465 	 */
466 	if (peer->cast_flags & MDF_POOL) {
467 		peer->outdate = current_time;
468 		poll_update(peer, hpoll, 0);
469 		if (   (peer_associations <= 2 * sys_maxclock)
470 		    && (   peer_associations < sys_maxclock
471 			|| sys_survivors < sys_minclock))
472 			pool_xmit(peer);
473 		return;
474 	}
475 
476 	/*
477 	 * In unicast modes the dance is much more intricate. It is
478 	 * designed to back off whenever possible to minimize network
479 	 * traffic.
480 	 */
481 	if (peer->burst == 0) {
482 		u_char oreach;
483 
484 		/*
485 		 * Update the reachability status. If not heard for
486 		 * three consecutive polls, stuff infinity in the clock
487 		 * filter.
488 		 */
489 		oreach = peer->reach;
490 		peer->outdate = current_time;
491 		peer->unreach++;
492 		peer->reach <<= 1;
493 		if (!peer->reach) {
494 
495 			/*
496 			 * Here the peer is unreachable. If it was
497 			 * previously reachable raise a trap. Send a
498 			 * burst if enabled.
499 			 */
500 			clock_filter(peer, 0., 0., MAXDISPERSE);
501 			if (oreach) {
502 				peer_unfit(peer);
503 				report_event(PEVNT_UNREACH, peer, NULL);
504 			}
505 			if (   (peer->flags & FLAG_IBURST)
506 			    && peer->retry == 0)
507 				peer->retry = NTP_RETRY;
508 		} else {
509 
510 			/*
511 			 * Here the peer is reachable. Send a burst if
512 			 * enabled and the peer is fit.  Reset unreach
513 			 * for persistent and ephemeral associations.
514 			 * Unreach is also reset for survivors in
515 			 * clock_select().
516 			 */
517 			hpoll = sys_poll;
518 			if (!(peer->flags & FLAG_PREEMPT))
519 				peer->unreach = 0;
520 			if (   (peer->flags & FLAG_BURST)
521 			    && peer->retry == 0
522 			    && !peer_unfit(peer))
523 				peer->retry = NTP_RETRY;
524 		}
525 
526 		/*
527 		 * Watch for timeout.  If ephemeral, toss the rascal;
528 		 * otherwise, bump the poll interval. Note the
529 		 * poll_update() routine will clamp it to maxpoll.
530 		 * If preemptible and we have more peers than maxclock,
531 		 * and this peer has the minimum score of preemptibles,
532 		 * demobilize.
533 		 */
534 		if (peer->unreach >= NTP_UNREACH) {
535 			hpoll++;
536 			/* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
537 			if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
538 				report_event(PEVNT_RESTART, peer, "timeout");
539 				peer_clear(peer, "TIME");
540 				unpeer(peer);
541 				return;
542 			}
543 			if (   (peer->flags & FLAG_PREEMPT)
544 			    && (peer_associations > sys_maxclock)
545 			    && score_all(peer)) {
546 				report_event(PEVNT_RESTART, peer, "timeout");
547 				peer_clear(peer, "TIME");
548 				unpeer(peer);
549 				return;
550 			}
551 		}
552 	} else {
553 		peer->burst--;
554 		if (peer->burst == 0) {
555 
556 			/*
557 			 * If ntpdate mode and the clock has not been
558 			 * set and all peers have completed the burst,
559 			 * we declare a successful failure.
560 			 */
561 			if (mode_ntpdate) {
562 				peer_ntpdate--;
563 				if (peer_ntpdate == 0) {
564 					msyslog(LOG_NOTICE,
565 					    "ntpd: no servers found");
566 					if (!msyslog_term)
567 						printf(
568 						    "ntpd: no servers found\n");
569 					exit (0);
570 				}
571 			}
572 		}
573 	}
574 	if (peer->retry > 0)
575 		peer->retry--;
576 
577 	/*
578 	 * Do not transmit if in broadcast client mode.
579 	 */
580 	poll_update(peer, hpoll, (peer->hmode == MODE_CLIENT));
581 	if (peer->hmode != MODE_BCLIENT)
582 		peer_xmit(peer);
583 
584 	return;
585 }
586 
587 
588 const char *
amtoa(int am)589 amtoa(
590 	int am
591 	)
592 {
593 	char *bp;
594 
595 	switch(am) {
596 	    case AM_ERR:	return "AM_ERR";
597 	    case AM_NOMATCH:	return "AM_NOMATCH";
598 	    case AM_PROCPKT:	return "AM_PROCPKT";
599 	    case AM_BCST:	return "AM_BCST";
600 	    case AM_FXMIT:	return "AM_FXMIT";
601 	    case AM_MANYCAST:	return "AM_MANYCAST";
602 	    case AM_NEWPASS:	return "AM_NEWPASS";
603 	    case AM_NEWBCL:	return "AM_NEWBCL";
604 	    case AM_POSSBCL:	return "AM_POSSBCL";
605 	    default:
606 		LIB_GETBUF(bp);
607 		snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
608 		return bp;
609 	}
610 }
611 
612 
613 /*
614  * receive - receive procedure called for each packet received
615  */
616 void
receive(struct recvbuf * rbufp)617 receive(
618 	struct recvbuf *rbufp
619 	)
620 {
621 	register struct peer *peer;	/* peer structure pointer */
622 	register struct pkt *pkt;	/* receive packet pointer */
623 	u_char	hisversion;		/* packet version */
624 	u_char	hisleap;		/* packet leap indicator */
625 	u_char	hismode;		/* packet mode */
626 	u_char	hisstratum;		/* packet stratum */
627 	r4addr	r4a;			/* address restrictions */
628 	u_short	restrict_mask;		/* restrict bits */
629 	const char *hm_str;		/* hismode string */
630 	const char *am_str;		/* association match string */
631 	int	kissCode = NOKISS;	/* Kiss Code */
632 	int	has_mac;		/* length of MAC field */
633 	int	authlen;		/* offset of MAC field */
634 	auth_code is_authentic = AUTH_UNKNOWN;	/* Was AUTH_NONE */
635 	nak_code crypto_nak_test;	/* result of crypto-NAK check */
636 	int	retcode = AM_NOMATCH;	/* match code */
637 	keyid_t	skeyid = 0;		/* key IDs */
638 	u_int32	opcode = 0;		/* extension field opcode */
639 	sockaddr_u *dstadr_sin;		/* active runway */
640 	struct peer *peer2;		/* aux peer structure pointer */
641 	endpt	*match_ep;		/* newpeer() local address */
642 	l_fp	p_org;			/* origin timestamp */
643 	l_fp	p_rec;			/* receive timestamp */
644 	l_fp	p_xmt;			/* transmit timestamp */
645 #ifdef AUTOKEY
646 	char	hostname[NTP_MAXSTRLEN + 1];
647 	char	*groupname = NULL;
648 	struct autokey *ap;		/* autokey structure pointer */
649 	int	rval;			/* cookie snatcher */
650 	keyid_t	pkeyid = 0, tkeyid = 0;	/* key IDs */
651 #endif	/* AUTOKEY */
652 #ifdef HAVE_NTP_SIGND
653 	static unsigned char zero_key[16];
654 #endif /* HAVE_NTP_SIGND */
655 
656 	/*
657 	 * Note that there are many places we do not call record_raw_stats().
658 	 *
659 	 * We only want to call it *after* we've sent a response, or perhaps
660 	 * when we've decided to drop a packet.
661 	 */
662 
663 	/*
664 	 * Monitor the packet and get restrictions. Note that the packet
665 	 * length for control and private mode packets must be checked
666 	 * by the service routines. Some restrictions have to be handled
667 	 * later in order to generate a kiss-o'-death packet.
668 	 */
669 	/*
670 	 * Bogus port check is before anything, since it probably
671 	 * reveals a clogging attack. Likewise the mimimum packet size
672 	 * of 2 bytes (for mode 6/7) must be checked first.
673 	 */
674 	sys_received++;
675 	if (0 == SRCPORT(&rbufp->recv_srcadr) || rbufp->recv_length < 2) {
676 		sys_badlength++;
677 		return;				/* bogus port / length */
678 	}
679 	restrictions(&rbufp->recv_srcadr, &r4a);
680 	restrict_mask = r4a.rflags;
681 
682 	pkt = &rbufp->recv_pkt;
683 	hisversion = PKT_VERSION(pkt->li_vn_mode);
684 	hismode = (int)PKT_MODE(pkt->li_vn_mode);
685 
686 	if (restrict_mask & RES_IGNORE) {
687 		DPRINTF(2, ("receive: drop: RES_IGNORE\n"));
688 		sys_restricted++;
689 		return;				/* ignore everything */
690 	}
691 	if (hismode == MODE_PRIVATE) {
692 		if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
693 			DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
694 			sys_restricted++;
695 			return;			/* no query private */
696 		}
697 		process_private(rbufp, ((restrict_mask &
698 		    RES_NOMODIFY) == 0));
699 		return;
700 	}
701 	if (hismode == MODE_CONTROL) {
702 		if (restrict_mask & RES_NOQUERY) {
703 			DPRINTF(2, ("receive: drop: RES_NOQUERY\n"));
704 			sys_restricted++;
705 			return;			/* no query control */
706 		}
707 		process_control(rbufp, restrict_mask);
708 		return;
709 	}
710 	if (restrict_mask & RES_DONTSERVE) {
711 		DPRINTF(2, ("receive: drop: RES_DONTSERVE\n"));
712 		sys_restricted++;
713 		return;				/* no time serve */
714 	}
715 
716 
717 	/* If we arrive here, we should have a standard NTP packet. We
718 	 * check that the minimum size is available and fetch some more
719 	 * items from the packet once we can be sure they are indeed
720 	 * there.
721 	 */
722 	if ((size_t)rbufp->recv_length < LEN_PKT_NOMAC) {
723 		sys_badlength++;
724 		return;				/* bogus length */
725 	}
726 
727 	hisleap = PKT_LEAP(pkt->li_vn_mode);
728 	hisstratum = PKT_TO_STRATUM(pkt->stratum);
729 	INSIST(0 != hisstratum); /* paranoia check PKT_TO_STRATUM result */
730 
731 	DPRINTF(1, ("receive: at %ld %s<-%s ippeerlimit %d mode %d iflags %s "
732 		    "restrict %s org %#010x.%08x xmt %#010x.%08x\n",
733 		    current_time, stoa(&rbufp->dstadr->sin),
734 		    stoa(&rbufp->recv_srcadr), r4a.ippeerlimit, hismode,
735 		    build_iflags(rbufp->dstadr->flags),
736 		    build_rflags(restrict_mask),
737 		    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
738 		    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
739 
740 	/*
741 	 * This is for testing. If restricted drop ten percent of
742 	 * surviving packets.
743 	 */
744 	if (restrict_mask & RES_FLAKE) {
745 		if ((double)ntp_random() / 0x7fffffff < .1) {
746 			DPRINTF(2, ("receive: drop: RES_FLAKE\n"));
747 			sys_restricted++;
748 			return;			/* no flakeway */
749 		}
750 	}
751 
752 	/*
753 	** Format Layer Checks
754 	**
755 	** Validate the packet format.  The packet size, packet header,
756 	** and any extension field lengths are checked.  We identify
757 	** the beginning of the MAC, to identify the upper limit of
758 	** of the hash computation.
759 	**
760 	** In case of a format layer check violation, the packet is
761 	** discarded with no further processing.
762 	*/
763 
764 	/*
765 	 * Version check must be after the query packets, since they
766 	 * intentionally use an early version.
767 	 */
768 	if (hisversion == NTP_VERSION) {
769 		sys_newversion++;		/* new version */
770 	} else if (   !(restrict_mask & RES_VERSION)
771 		   && hisversion >= NTP_OLDVERSION) {
772 		sys_oldversion++;		/* previous version */
773 	} else {
774 		DPRINTF(2, ("receive: drop: RES_VERSION\n"));
775 		sys_badlength++;
776 		return;				/* old version */
777 	}
778 
779 	/*
780 	 * Figure out his mode and validate the packet. This has some
781 	 * legacy raunch that probably should be removed. In very early
782 	 * NTP versions mode 0 was equivalent to what later versions
783 	 * would interpret as client mode.
784 	 */
785 	if (hismode == MODE_UNSPEC) {
786 		if (hisversion == NTP_OLDVERSION) {
787 			hismode = MODE_CLIENT;
788 		} else {
789 			DPRINTF(2, ("receive: drop: MODE_UNSPEC\n"));
790 			sys_badlength++;
791 			return;			/* invalid mode */
792 		}
793 	}
794 
795 	/*
796 	 * Parse the extension field if present. We figure out whether
797 	 * an extension field is present by measuring the MAC size. If
798 	 * the number of words following the packet header is 0, no MAC
799 	 * is present and the packet is not authenticated. If 1, the
800 	 * packet is a crypto-NAK; if 3, the packet is authenticated
801 	 * with DES; if 5, the packet is authenticated with MD5; if 6,
802 	 * the packet is authenticated with SHA. If 2 or * 4, the packet
803 	 * is a runt and discarded forthwith. If greater than 6, an
804 	 * extension field is present, so we subtract the length of the
805 	 * field and go around again.
806 	 *
807 	 * Note the above description is lame.  We should/could also check
808 	 * the two bytes that make up the EF type and subtype, and then
809 	 * check the two bytes that tell us the EF length.  A legacy MAC
810 	 * has a 4 byte keyID, and for conforming symmetric keys its value
811 	 * must be <= 64k, meaning the top two bytes will always be zero.
812 	 * Since the EF Type of 0 is reserved/unused, there's no way a
813 	 * conforming legacy MAC could ever be misinterpreted as an EF.
814 	 *
815 	 * There is more, but this isn't the place to document it.
816 	 */
817 
818 	authlen = LEN_PKT_NOMAC;
819 	has_mac = rbufp->recv_length - authlen;
820 	while (has_mac > 0) {
821 		u_int32	len;
822 #ifdef AUTOKEY
823 		u_int32	hostlen;
824 		struct exten *ep;
825 #endif /*AUTOKEY */
826 
827 		if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
828 			DPRINTF(2, ("receive: drop: bad post-packet length\n"));
829 			sys_badlength++;
830 			return;			/* bad length */
831 		}
832 		/*
833 		 * This next test is clearly wrong - it needlessly
834 		 * prohibits short EFs (which don't yet exist)
835 		 */
836 		if (has_mac <= (int)MAX_MAC_LEN) {
837 			skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
838 			break;
839 
840 		} else {
841 			opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
842 			len = opcode & 0xffff;
843 			if (   len % 4 != 0
844 			    || len < 4
845 			    || (int)len + authlen > rbufp->recv_length) {
846 				DPRINTF(2, ("receive: drop: bad EF length\n"));
847 				sys_badlength++;
848 				return;		/* bad length */
849 			}
850 #ifdef AUTOKEY
851 			/*
852 			 * Extract calling group name for later.  If
853 			 * sys_groupname is non-NULL, there must be
854 			 * a group name provided to elicit a response.
855 			 */
856 			if (   (opcode & 0x3fff0000) == CRYPTO_ASSOC
857 			    && sys_groupname != NULL) {
858 				ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
859 				hostlen = ntohl(ep->vallen);
860 				if (   hostlen >= sizeof(hostname)
861 				    || hostlen > len -
862 						offsetof(struct exten, pkt)) {
863 					DPRINTF(2, ("receive: drop: bad autokey hostname length\n"));
864 					sys_badlength++;
865 					return;		/* bad length */
866 				}
867 				memcpy(hostname, &ep->pkt, hostlen);
868 				hostname[hostlen] = '\0';
869 				groupname = strchr(hostname, '@');
870 				if (groupname == NULL) {
871 					DPRINTF(2, ("receive: drop: empty autokey groupname\n"));
872 					sys_declined++;
873 					return;
874 				}
875 				groupname++;
876 			}
877 #endif /* AUTOKEY */
878 			authlen += len;
879 			has_mac -= len;
880 		}
881 	}
882 
883 	/*
884 	 * If has_mac is < 0 we had a malformed packet.
885 	 */
886 	if (has_mac < 0) {
887 		DPRINTF(2, ("receive: drop: post-packet under-read\n"));
888 		sys_badlength++;
889 		return;		/* bad length */
890 	}
891 
892 	/*
893 	** Packet Data Verification Layer
894 	**
895 	** This layer verifies the packet data content.  If
896 	** authentication is required, a MAC must be present.
897 	** If a MAC is present, it must validate.
898 	** Crypto-NAK?  Look - a shiny thing!
899 	**
900 	** If authentication fails, we're done.
901 	*/
902 
903 	/*
904 	 * If authentication is explicitly required, a MAC must be present.
905 	 */
906 	if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
907 		DPRINTF(2, ("receive: drop: RES_DONTTRUST\n"));
908 		sys_restricted++;
909 		return;				/* access denied */
910 	}
911 
912 	/*
913 	 * Update the MRU list and finger the cloggers. It can be a
914 	 * little expensive, so turn it off for production use.
915 	 * RES_LIMITED and RES_KOD will be cleared in the returned
916 	 * restrict_mask unless one or both actions are warranted.
917 	 */
918 	restrict_mask = ntp_monitor(rbufp, restrict_mask);
919 	if (restrict_mask & RES_LIMITED) {
920 		sys_limitrejected++;
921 		if (   !(restrict_mask & RES_KOD)
922 		    || MODE_BROADCAST == hismode
923 		    || MODE_SERVER == hismode) {
924 			if (MODE_SERVER == hismode) {
925 				DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
926 					stoa(&rbufp->recv_srcadr)));
927 			} else {
928 				DPRINTF(2, ("receive: drop: RES_KOD\n"));
929 			}
930 			return;			/* rate exceeded */
931 		}
932 		if (hismode == MODE_CLIENT) {
933 			fast_xmit(rbufp, MODE_SERVER, skeyid,
934 			    restrict_mask);
935 		} else {
936 			fast_xmit(rbufp, MODE_ACTIVE, skeyid,
937 			    restrict_mask);
938 		}
939 		return;				/* rate exceeded */
940 	}
941 	restrict_mask &= ~RES_KOD;
942 
943 	/*
944 	 * We have tossed out as many buggy packets as possible early in
945 	 * the game to reduce the exposure to a clogging attack. Now we
946 	 * have to burn some cycles to find the association and
947 	 * authenticate the packet if required. Note that we burn only
948 	 * digest cycles, again to reduce exposure. There may be no
949 	 * matching association and that's okay.
950 	 *
951 	 * More on the autokey mambo. Normally the local interface is
952 	 * found when the association was mobilized with respect to a
953 	 * designated remote address. We assume packets arriving from
954 	 * the remote address arrive via this interface and the local
955 	 * address used to construct the autokey is the unicast address
956 	 * of the interface. However, if the sender is a broadcaster,
957 	 * the interface broadcast address is used instead.
958 	 * Notwithstanding this technobabble, if the sender is a
959 	 * multicaster, the broadcast address is null, so we use the
960 	 * unicast address anyway. Don't ask.
961 	 */
962 
963 	peer = findpeer(rbufp,  hismode, &retcode);
964 	dstadr_sin = &rbufp->dstadr->sin;
965 	NTOHL_FP(&pkt->org, &p_org);
966 	NTOHL_FP(&pkt->rec, &p_rec);
967 	NTOHL_FP(&pkt->xmt, &p_xmt);
968 	hm_str = modetoa(hismode);
969 	am_str = amtoa(retcode);
970 
971 	/*
972 	 * Authentication is conditioned by three switches:
973 	 *
974 	 * NOPEER  (RES_NOPEER) do not mobilize an association unless
975 	 *         authenticated
976 	 * NOTRUST (RES_DONTTRUST) do not allow access unless
977 	 *         authenticated (implies NOPEER)
978 	 * enable  (sys_authenticate) master NOPEER switch, by default
979 	 *         on
980 	 *
981 	 * The NOPEER and NOTRUST can be specified on a per-client basis
982 	 * using the restrict command. The enable switch if on implies
983 	 * NOPEER for all clients. There are four outcomes:
984 	 *
985 	 * NONE    The packet has no MAC.
986 	 * OK      the packet has a MAC and authentication succeeds
987 	 * ERROR   the packet has a MAC and authentication fails
988 	 * CRYPTO  crypto-NAK. The MAC has four octets only.
989 	 *
990 	 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
991 	 * is zero, acceptable outcomes of y are NONE and OK. If x is
992 	 * one, the only acceptable outcome of y is OK.
993 	 */
994 	crypto_nak_test = valid_NAK(peer, rbufp, hismode);
995 
996 	/*
997 	 * Drop any invalid crypto-NAKs
998 	 */
999 	if (crypto_nak_test == INVALIDNAK) {
1000 		report_event(PEVNT_AUTH, peer, "Invalid_NAK");
1001 		if (0 != peer) {
1002 			peer->badNAK++;
1003 		}
1004 		msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
1005 			current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
1006 		return;
1007 	}
1008 
1009 	if (has_mac == 0) {
1010 		restrict_mask &= ~RES_MSSNTP;
1011 		is_authentic = AUTH_NONE; /* not required */
1012 		DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
1013 			    current_time, stoa(dstadr_sin),
1014 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1015 			    authlen,
1016 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1017 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1018 	} else if (crypto_nak_test == VALIDNAK) {
1019 		restrict_mask &= ~RES_MSSNTP;
1020 		is_authentic = AUTH_CRYPTO; /* crypto-NAK */
1021 		DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x CRYPTONAK\n",
1022 			    current_time, stoa(dstadr_sin),
1023 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1024 			    skeyid, authlen + has_mac, is_authentic,
1025 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1026 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1027 
1028 #ifdef HAVE_NTP_SIGND
1029 		/*
1030 		 * If the signature is 20 bytes long, the last 16 of
1031 		 * which are zero, then this is a Microsoft client
1032 		 * wanting AD-style authentication of the server's
1033 		 * reply.
1034 		 *
1035 		 * This is described in Microsoft's WSPP docs, in MS-SNTP:
1036 		 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
1037 		 */
1038 	} else if (   has_mac == MAX_MD5_LEN
1039 		   && (restrict_mask & RES_MSSNTP)
1040 		   && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
1041 		   && (memcmp(zero_key, (char *)pkt + authlen + 4,
1042 			      MAX_MD5_LEN - 4) == 0)) {
1043 		is_authentic = AUTH_NONE;
1044 		DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x SIGND\n",
1045 			    current_time, stoa(dstadr_sin),
1046 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1047 			    authlen,
1048 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1049 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1050 #endif /* HAVE_NTP_SIGND */
1051 
1052 	} else {
1053 		/*
1054 		 * has_mac is not 0
1055 		 * Not a VALID_NAK
1056 		 * Not an MS-SNTP SIGND packet
1057 		 *
1058 		 * So there is a MAC here.
1059 		 */
1060 
1061 		restrict_mask &= ~RES_MSSNTP;
1062 #ifdef AUTOKEY
1063 		/*
1064 		 * For autokey modes, generate the session key
1065 		 * and install in the key cache. Use the socket
1066 		 * broadcast or unicast address as appropriate.
1067 		 */
1068 		if (crypto_flags && skeyid > NTP_MAXKEY) {
1069 
1070 			/*
1071 			 * More on the autokey dance (AKD). A cookie is
1072 			 * constructed from public and private values.
1073 			 * For broadcast packets, the cookie is public
1074 			 * (zero). For packets that match no
1075 			 * association, the cookie is hashed from the
1076 			 * addresses and private value. For server
1077 			 * packets, the cookie was previously obtained
1078 			 * from the server. For symmetric modes, the
1079 			 * cookie was previously constructed using an
1080 			 * agreement protocol; however, should PKI be
1081 			 * unavailable, we construct a fake agreement as
1082 			 * the EXOR of the peer and host cookies.
1083 			 *
1084 			 * hismode	ephemeral	persistent
1085 			 * =======================================
1086 			 * active	0		cookie#
1087 			 * passive	0%		cookie#
1088 			 * client	sys cookie	0%
1089 			 * server	0%		sys cookie
1090 			 * broadcast	0		0
1091 			 *
1092 			 * # if unsync, 0
1093 			 * % can't happen
1094 			 */
1095 			if (has_mac < (int)MAX_MD5_LEN) {
1096 				DPRINTF(2, ("receive: drop: MD5 digest too short\n"));
1097 				sys_badauth++;
1098 				return;
1099 			}
1100 			if (hismode == MODE_BROADCAST) {
1101 
1102 				/*
1103 				 * For broadcaster, use the interface
1104 				 * broadcast address when available;
1105 				 * otherwise, use the unicast address
1106 				 * found when the association was
1107 				 * mobilized. However, if this is from
1108 				 * the wildcard interface, game over.
1109 				 */
1110 				if (   crypto_flags
1111 				    && rbufp->dstadr ==
1112 				       ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
1113 					DPRINTF(2, ("receive: drop: BCAST from wildcard\n"));
1114 					sys_restricted++;
1115 					return;		/* no wildcard */
1116 				}
1117 				pkeyid = 0;
1118 				if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
1119 					dstadr_sin =
1120 					    &rbufp->dstadr->bcast;
1121 			} else if (peer == NULL) {
1122 				pkeyid = session_key(
1123 				    &rbufp->recv_srcadr, dstadr_sin, 0,
1124 				    sys_private, 0);
1125 			} else {
1126 				pkeyid = peer->pcookie;
1127 			}
1128 
1129 			/*
1130 			 * The session key includes both the public
1131 			 * values and cookie. In case of an extension
1132 			 * field, the cookie used for authentication
1133 			 * purposes is zero. Note the hash is saved for
1134 			 * use later in the autokey mambo.
1135 			 */
1136 			if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
1137 				session_key(&rbufp->recv_srcadr,
1138 				    dstadr_sin, skeyid, 0, 2);
1139 				tkeyid = session_key(
1140 				    &rbufp->recv_srcadr, dstadr_sin,
1141 				    skeyid, pkeyid, 0);
1142 			} else {
1143 				tkeyid = session_key(
1144 				    &rbufp->recv_srcadr, dstadr_sin,
1145 				    skeyid, pkeyid, 2);
1146 			}
1147 
1148 		}
1149 #endif	/* AUTOKEY */
1150 
1151 		/*
1152 		 * Compute the cryptosum. Note a clogging attack may
1153 		 * succeed in bloating the key cache. If an autokey,
1154 		 * purge it immediately, since we won't be needing it
1155 		 * again. If the packet is authentic, it can mobilize an
1156 		 * association. Note that there is no key zero.
1157 		 */
1158 		if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1159 		    has_mac))
1160 			is_authentic = AUTH_ERROR;
1161 		else
1162 			is_authentic = AUTH_OK;
1163 #ifdef AUTOKEY
1164 		if (crypto_flags && skeyid > NTP_MAXKEY)
1165 			authtrust(skeyid, 0);
1166 #endif	/* AUTOKEY */
1167 		DPRINTF(1, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC\n",
1168 			    current_time, stoa(dstadr_sin),
1169 			    stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1170 			    skeyid, authlen + has_mac, is_authentic,
1171 			    ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1172 			    ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1173 	}
1174 
1175 
1176 	/*
1177 	 * Bug 3454:
1178 	 *
1179 	 * Now come at this from a different perspective:
1180 	 * - If we expect a MAC and it's not there, we drop it.
1181 	 * - If we expect one keyID and get another, we drop it.
1182 	 * - If we have a MAC ahd it hasn't been validated yet, try.
1183 	 * - if the provided MAC doesn't validate, we drop it.
1184 	 *
1185 	 * There might be more to this.
1186 	 */
1187 	if (0 != peer && 0 != peer->keyid) {
1188 		/* Should we msyslog() any of these? */
1189 
1190 		/*
1191 		 * This should catch:
1192 		 * - no keyID where one is expected,
1193 		 * - different keyID than what we expect.
1194 		 */
1195 		if (peer->keyid != skeyid) {
1196 			DPRINTF(2, ("receive: drop: Wanted keyID %d, got %d from %s\n",
1197 				    peer->keyid, skeyid,
1198 				    stoa(&rbufp->recv_srcadr)));
1199 			sys_restricted++;
1200 			return;			/* drop: access denied */
1201 		}
1202 
1203 		/*
1204 		 * if has_mac != 0 ...
1205 		 * - If it has not yet been validated, do so.
1206 		 *   (under what circumstances might that happen?)
1207 		 * - if missing or bad MAC, log and drop.
1208 		 */
1209 		if (0 != has_mac) {
1210 			if (is_authentic == AUTH_UNKNOWN) {
1211 				/* How can this happen? */
1212 				DPRINTF(2, ("receive: 3454 check: AUTH_UNKNOWN from %s\n",
1213 				    stoa(&rbufp->recv_srcadr)));
1214 				if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
1215 				    has_mac)) {
1216 					/* MAC invalid or not found */
1217 					is_authentic = AUTH_ERROR;
1218 				} else {
1219 					is_authentic = AUTH_OK;
1220 				}
1221 			}
1222 			if (is_authentic != AUTH_OK) {
1223 				DPRINTF(2, ("receive: drop: missing or bad MAC from %s\n",
1224 					    stoa(&rbufp->recv_srcadr)));
1225 				sys_restricted++;
1226 				return;		/* drop: access denied */
1227 			}
1228 		}
1229 	}
1230 	/**/
1231 
1232 	/*
1233 	** On-Wire Protocol Layer
1234 	**
1235 	** Verify protocol operations consistent with the on-wire protocol.
1236 	** The protocol discards bogus and duplicate packets as well as
1237 	** minimizes disruptions doe to protocol restarts and dropped
1238 	** packets.  The operations are controlled by two timestamps:
1239 	** the transmit timestamp saved in the client state variables,
1240 	** and the origin timestamp in the server packet header.  The
1241 	** comparison of these two timestamps is called the loopback test.
1242 	** The transmit timestamp functions as a nonce to verify that the
1243 	** response corresponds to the original request.  The transmit
1244 	** timestamp also serves to discard replays of the most recent
1245 	** packet.  Upon failure of either test, the packet is discarded
1246 	** with no further action.
1247 	*/
1248 
1249 	/*
1250 	 * The association matching rules are implemented by a set of
1251 	 * routines and an association table. A packet matching an
1252 	 * association is processed by the peer process for that
1253 	 * association. If there are no errors, an ephemeral association
1254 	 * is mobilized: a broadcast packet mobilizes a broadcast client
1255 	 * aassociation; a manycast server packet mobilizes a manycast
1256 	 * client association; a symmetric active packet mobilizes a
1257 	 * symmetric passive association.
1258 	 */
1259 	DPRINTF(1, ("receive: MATCH_ASSOC dispatch: mode %d/%s:%s \n",
1260 		hismode, hm_str, am_str));
1261 	switch (retcode) {
1262 
1263 	/*
1264 	 * This is a client mode packet not matching any association. If
1265 	 * an ordinary client, simply toss a server mode packet back
1266 	 * over the fence. If a manycast client, we have to work a
1267 	 * little harder.
1268 	 *
1269 	 * There are cases here where we do not call record_raw_stats().
1270 	 */
1271 	case AM_FXMIT:
1272 
1273 		/*
1274 		 * If authentication OK, send a server reply; otherwise,
1275 		 * send a crypto-NAK.
1276 		 */
1277 		if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1278 			/* HMS: would be nice to log FAST_XMIT|BADAUTH|RESTRICTED */
1279 			record_raw_stats(&rbufp->recv_srcadr,
1280 			    &rbufp->dstadr->sin,
1281 			    &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1282 			    PKT_LEAP(pkt->li_vn_mode),
1283 			    PKT_VERSION(pkt->li_vn_mode),
1284 			    PKT_MODE(pkt->li_vn_mode),
1285 			    PKT_TO_STRATUM(pkt->stratum),
1286 			    pkt->ppoll,
1287 			    pkt->precision,
1288 			    FPTOD(NTOHS_FP(pkt->rootdelay)),
1289 			    FPTOD(NTOHS_FP(pkt->rootdisp)),
1290 			    pkt->refid,
1291 			    rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1292 
1293 			if (AUTH(restrict_mask & RES_DONTTRUST,
1294 			   is_authentic)) {
1295 				/* Bug 3596: Do we want to fuzz the reftime? */
1296 				fast_xmit(rbufp, MODE_SERVER, skeyid,
1297 				    restrict_mask);
1298 			} else if (is_authentic == AUTH_ERROR) {
1299 				/* Bug 3596: Do we want to fuzz the reftime? */
1300 				fast_xmit(rbufp, MODE_SERVER, 0,
1301 				    restrict_mask);
1302 				sys_badauth++;
1303 			} else {
1304 				DPRINTF(2, ("receive: AM_FXMIT drop: !mcast restricted\n"));
1305 				sys_restricted++;
1306 			}
1307 
1308 			return;			/* hooray */
1309 		}
1310 
1311 		/*
1312 		 * This must be manycast. Do not respond if not
1313 		 * configured as a manycast server.
1314 		 */
1315 		if (!sys_manycastserver) {
1316 			DPRINTF(2, ("receive: AM_FXMIT drop: Not manycastserver\n"));
1317 			sys_restricted++;
1318 			return;			/* not enabled */
1319 		}
1320 
1321 #ifdef AUTOKEY
1322 		/*
1323 		 * Do not respond if not the same group.
1324 		 */
1325 		if (group_test(groupname, NULL)) {
1326 			DPRINTF(2, ("receive: AM_FXMIT drop: empty groupname\n"));
1327 			sys_declined++;
1328 			return;
1329 		}
1330 #endif /* AUTOKEY */
1331 
1332 		/*
1333 		 * Do not respond if we are not synchronized or our
1334 		 * stratum is greater than the manycaster or the
1335 		 * manycaster has already synchronized to us.
1336 		 */
1337 		if (   sys_leap == LEAP_NOTINSYNC
1338 		    || sys_stratum > hisstratum + 1
1339 		    || (!sys_cohort && sys_stratum == hisstratum + 1)
1340 		    || rbufp->dstadr->addr_refid == pkt->refid) {
1341 			DPRINTF(2, ("receive: sys leap: %0x, sys_stratum %d > hisstratum+1 %d, !sys_cohort %d && sys_stratum == hisstratum+1, loop refid %#x == pkt refid %#x\n", sys_leap, sys_stratum, hisstratum + 1, !sys_cohort, rbufp->dstadr->addr_refid, pkt->refid));
1342 			DPRINTF(2, ("receive: AM_FXMIT drop: LEAP_NOTINSYNC || stratum || loop\n"));
1343 			sys_declined++;
1344 			return;			/* no help */
1345 		}
1346 
1347 		/*
1348 		 * Respond only if authentication succeeds. Don't do a
1349 		 * crypto-NAK, as that would not be useful.
1350 		 */
1351 		if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic)) {
1352 			record_raw_stats(&rbufp->recv_srcadr,
1353 			    &rbufp->dstadr->sin,
1354 			    &p_org, &p_rec, &p_xmt, &rbufp->recv_time,
1355 			    PKT_LEAP(pkt->li_vn_mode),
1356 			    PKT_VERSION(pkt->li_vn_mode),
1357 			    PKT_MODE(pkt->li_vn_mode),
1358 			    PKT_TO_STRATUM(pkt->stratum),
1359 			    pkt->ppoll,
1360 			    pkt->precision,
1361 			    FPTOD(NTOHS_FP(pkt->rootdelay)),
1362 			    FPTOD(NTOHS_FP(pkt->rootdisp)),
1363 			    pkt->refid,
1364 			    rbufp->recv_length - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
1365 
1366 			/* Bug 3596: Do we want to fuzz the reftime? */
1367 			fast_xmit(rbufp, MODE_SERVER, skeyid,
1368 			    restrict_mask);
1369 		}
1370 		return;				/* hooray */
1371 
1372 	/*
1373 	 * This is a server mode packet returned in response to a client
1374 	 * mode packet sent to a multicast group address (for
1375 	 * manycastclient) or to a unicast address (for pool). The
1376 	 * origin timestamp is a good nonce to reliably associate the
1377 	 * reply with what was sent. If there is no match, that's
1378 	 * curious and could be an intruder attempting to clog, so we
1379 	 * just ignore it.
1380 	 *
1381 	 * If the packet is authentic and the manycastclient or pool
1382 	 * association is found, we mobilize a client association and
1383 	 * copy pertinent variables from the manycastclient or pool
1384 	 * association to the new client association. If not, just
1385 	 * ignore the packet.
1386 	 *
1387 	 * There is an implosion hazard at the manycast client, since
1388 	 * the manycast servers send the server packet immediately. If
1389 	 * the guy is already here, don't fire up a duplicate.
1390 	 *
1391 	 * There are cases here where we do not call record_raw_stats().
1392 	 */
1393 	case AM_MANYCAST:
1394 
1395 #ifdef AUTOKEY
1396 		/*
1397 		 * Do not respond if not the same group.
1398 		 */
1399 		if (group_test(groupname, NULL)) {
1400 			DPRINTF(2, ("receive: AM_MANYCAST drop: empty groupname\n"));
1401 			sys_declined++;
1402 			return;
1403 		}
1404 #endif /* AUTOKEY */
1405 		if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1406 			DPRINTF(2, ("receive: AM_MANYCAST drop: No manycast peer\n"));
1407 			sys_restricted++;
1408 			return;			/* not enabled */
1409 		}
1410 		if (!AUTH(  (!(peer2->cast_flags & MDF_POOL)
1411 			     && sys_authenticate)
1412 			  || (restrict_mask & (RES_NOPEER |
1413 			      RES_DONTTRUST)), is_authentic)
1414 		    /* MC: RES_NOEPEER? */
1415 		   ) {
1416 			DPRINTF(2, ("receive: AM_MANYCAST drop: bad auth || (NOPEER|DONTTRUST)\n"));
1417 			sys_restricted++;
1418 			return;			/* access denied */
1419 		}
1420 
1421 		/*
1422 		 * Do not respond if unsynchronized or stratum is below
1423 		 * the floor or at or above the ceiling.
1424 		 */
1425 		if (   hisleap == LEAP_NOTINSYNC
1426 		    || hisstratum < sys_floor
1427 		    || hisstratum >= sys_ceiling) {
1428 			DPRINTF(2, ("receive: AM_MANYCAST drop: unsync/stratum\n"));
1429 			sys_declined++;
1430 			return;			/* no help */
1431 		}
1432 		peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1433 			       r4a.ippeerlimit, MODE_CLIENT, hisversion,
1434 			       peer2->minpoll, peer2->maxpoll,
1435 			       (FLAG_PREEMPT | (POOL_FLAG_PMASK & peer2->flags)),
1436 			       (MDF_UCAST | MDF_UCLNT), 0, skeyid, sys_ident);
1437 		if (NULL == peer) {
1438 			DPRINTF(2, ("receive: AM_MANYCAST drop: duplicate\n"));
1439 			sys_declined++;
1440 			return;			/* ignore duplicate */
1441 		}
1442 
1443 		/*
1444 		 * After each ephemeral pool association is spun,
1445 		 * accelerate the next poll for the pool solicitor so
1446 		 * the pool will fill promptly.
1447 		 */
1448 		if (peer2->cast_flags & MDF_POOL)
1449 			peer2->nextdate = current_time + 1;
1450 
1451 		/*
1452 		 * Further processing of the solicitation response would
1453 		 * simply detect its origin timestamp as bogus for the
1454 		 * brand-new association (it matches the prototype
1455 		 * association) and tinker with peer->nextdate delaying
1456 		 * first sync.
1457 		 */
1458 		return;		/* solicitation response handled */
1459 
1460 	/*
1461 	 * This is the first packet received from a broadcast server. If
1462 	 * the packet is authentic and we are enabled as broadcast
1463 	 * client, mobilize a broadcast client association. We don't
1464 	 * kiss any frogs here.
1465 	 *
1466 	 * There are cases here where we do not call record_raw_stats().
1467 	 */
1468 	case AM_NEWBCL:
1469 
1470 #ifdef AUTOKEY
1471 		/*
1472 		 * Do not respond if not the same group.
1473 		 */
1474 		if (group_test(groupname, sys_ident)) {
1475 			DPRINTF(2, ("receive: AM_NEWBCL drop: groupname mismatch\n"));
1476 			sys_declined++;
1477 			return;
1478 		}
1479 #endif /* AUTOKEY */
1480 		if (sys_bclient == 0) {
1481 			DPRINTF(2, ("receive: AM_NEWBCL drop: not a bclient\n"));
1482 			sys_restricted++;
1483 			return;			/* not enabled */
1484 		}
1485 		if (!AUTH(sys_authenticate | (restrict_mask &
1486 			  (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1487 		    /* NEWBCL: RES_NOEPEER? */
1488 		   ) {
1489 			DPRINTF(2, ("receive: AM_NEWBCL drop: AUTH failed\n"));
1490 			sys_restricted++;
1491 			return;			/* access denied */
1492 		}
1493 
1494 		/*
1495 		 * Do not respond if unsynchronized or stratum is below
1496 		 * the floor or at or above the ceiling.
1497 		 */
1498 		if (   hisleap == LEAP_NOTINSYNC
1499 		    || hisstratum < sys_floor
1500 		    || hisstratum >= sys_ceiling) {
1501 			DPRINTF(2, ("receive: AM_NEWBCL drop: Unsync or bad stratum\n"));
1502 			sys_declined++;
1503 			return;			/* no help */
1504 		}
1505 
1506 #ifdef AUTOKEY
1507 		/*
1508 		 * Do not respond if Autokey and the opcode is not a
1509 		 * CRYPTO_ASSOC response with association ID.
1510 		 */
1511 		if (   crypto_flags && skeyid > NTP_MAXKEY
1512 		    && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1513 			DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not CRYPTO_ASSOC\n"));
1514 			sys_declined++;
1515 			return;			/* protocol error */
1516 		}
1517 #endif	/* AUTOKEY */
1518 
1519 		/*
1520 		 * Broadcasts received via a multicast address may
1521 		 * arrive after a unicast volley has begun
1522 		 * with the same remote address.  newpeer() will not
1523 		 * find duplicate associations on other local endpoints
1524 		 * if a non-NULL endpoint is supplied.  multicastclient
1525 		 * ephemeral associations are unique across all local
1526 		 * endpoints.
1527 		 */
1528 		if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1529 			match_ep = rbufp->dstadr;
1530 		else
1531 			match_ep = NULL;
1532 
1533 		/*
1534 		 * Determine whether to execute the initial volley.
1535 		 */
1536 		if (sys_bdelay > 0.0) {
1537 #ifdef AUTOKEY
1538 			/*
1539 			 * If a two-way exchange is not possible,
1540 			 * neither is Autokey.
1541 			 */
1542 			if (crypto_flags && skeyid > NTP_MAXKEY) {
1543 				sys_restricted++;
1544 				DPRINTF(2, ("receive: AM_NEWBCL drop: Autokey but not 2-way\n"));
1545 				return;		/* no autokey */
1546 			}
1547 #endif	/* AUTOKEY */
1548 
1549 			/*
1550 			 * Do not execute the volley. Start out in
1551 			 * broadcast client mode.
1552 			 */
1553 			peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1554 			    r4a.ippeerlimit, MODE_BCLIENT, hisversion,
1555 			    pkt->ppoll, pkt->ppoll,
1556 			    FLAG_PREEMPT, MDF_BCLNT, 0, skeyid, sys_ident);
1557 			if (NULL == peer) {
1558 				DPRINTF(2, ("receive: AM_NEWBCL drop: duplicate\n"));
1559 				sys_restricted++;
1560 				return;		/* ignore duplicate */
1561 
1562 			} else {
1563 				peer->delay = sys_bdelay;
1564 				peer->bxmt = p_xmt;
1565 			}
1566 			break;
1567 		}
1568 
1569 		/*
1570 		 * Execute the initial volley in order to calibrate the
1571 		 * propagation delay and run the Autokey protocol.
1572 		 *
1573 		 * Note that the minpoll is taken from the broadcast
1574 		 * packet, normally 6 (64 s) and that the poll interval
1575 		 * is fixed at this value.
1576 		 */
1577 		peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1578 			       r4a.ippeerlimit, MODE_CLIENT, hisversion,
1579 			       pkt->ppoll, pkt->ppoll,
1580 			       FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1581 			       0, skeyid, sys_ident);
1582 		if (NULL == peer) {
1583 			DPRINTF(2, ("receive: AM_NEWBCL drop: empty newpeer() failed\n"));
1584 			sys_restricted++;
1585 			return;			/* ignore duplicate */
1586 		}
1587 		peer->bxmt = p_xmt;
1588 #ifdef AUTOKEY
1589 		if (skeyid > NTP_MAXKEY)
1590 			crypto_recv(peer, rbufp);
1591 #endif	/* AUTOKEY */
1592 
1593 		return;				/* hooray */
1594 
1595 	/*
1596 	 * This is the first packet received from a potential ephemeral
1597 	 * symmetric active peer.  First, deal with broken Windows clients.
1598 	 * Then, if NOEPEER is enabled, drop it.  If the packet meets our
1599 	 * authenticty requirements and is the first he sent, mobilize
1600 	 * a passive association.
1601 	 * Otherwise, kiss the frog.
1602 	 *
1603 	 * There are cases here where we do not call record_raw_stats().
1604 	 */
1605 	case AM_NEWPASS:
1606 
1607 		DEBUG_REQUIRE(MODE_ACTIVE == hismode);
1608 
1609 #ifdef AUTOKEY
1610 		/*
1611 		 * Do not respond if not the same group.
1612 		 */
1613 		if (group_test(groupname, sys_ident)) {
1614 			DPRINTF(2, ("receive: AM_NEWPASS drop: Autokey group mismatch\n"));
1615 			sys_declined++;
1616 			return;
1617 		}
1618 #endif /* AUTOKEY */
1619 		if (!AUTH(sys_authenticate | (restrict_mask &
1620 			  (RES_NOPEER | RES_DONTTRUST)), is_authentic)
1621 		   ) {
1622 			/*
1623 			 * If authenticated but cannot mobilize an
1624 			 * association, send a symmetric passive
1625 			 * response without mobilizing an association.
1626 			 * This is for drat broken Windows clients. See
1627 			 * Microsoft KB 875424 for preferred workaround.
1628 			 */
1629 			if (AUTH(restrict_mask & RES_DONTTRUST,
1630 				 is_authentic)) {
1631 				fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1632 				    restrict_mask);
1633 				return;			/* hooray */
1634 			}
1635 			/* HMS: Why is this next set of lines a feature? */
1636 			if (is_authentic == AUTH_ERROR) {
1637 				fast_xmit(rbufp, MODE_PASSIVE, 0,
1638 				    restrict_mask);
1639 				sys_restricted++;
1640 				return;
1641 			}
1642 
1643 			if (restrict_mask & RES_NOEPEER) {
1644 				DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n"));
1645 				sys_declined++;
1646 				return;
1647 			}
1648 
1649 			/* [Bug 2941]
1650 			 * If we got here, the packet isn't part of an
1651 			 * existing association, either isn't correctly
1652 			 * authenticated or it is but we are refusing
1653 			 * ephemeral peer requests, and it didn't meet
1654 			 * either of the previous two special cases so we
1655 			 * should just drop it on the floor.  For example,
1656 			 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1657 			 * will make it this far.  This is just
1658 			 * debug-printed and not logged to avoid log
1659 			 * flooding.
1660 			 */
1661 			DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1662 				    " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1663 				    current_time, stoa(&rbufp->recv_srcadr),
1664 				    hismode, hm_str, am_str, skeyid,
1665 				    (authlen + has_mac), is_authentic));
1666 			sys_declined++;
1667 			return;
1668 		}
1669 
1670 		if (restrict_mask & RES_NOEPEER) {
1671 			DPRINTF(2, ("receive: AM_NEWPASS drop: NOEPEER\n"));
1672 			sys_declined++;
1673 			return;
1674 		}
1675 
1676 		/*
1677 		 * Do not respond if synchronized and if stratum is
1678 		 * below the floor or at or above the ceiling. Note,
1679 		 * this allows an unsynchronized peer to synchronize to
1680 		 * us. It would be very strange if he did and then was
1681 		 * nipped, but that could only happen if we were
1682 		 * operating at the top end of the range.  It also means
1683 		 * we will spin an ephemeral association in response to
1684 		 * MODE_ACTIVE KoDs, which will time out eventually.
1685 		 */
1686 		if (   hisleap != LEAP_NOTINSYNC
1687 		       && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1688 			DPRINTF(2, ("receive: AM_NEWPASS drop: Remote stratum (%d) out of range\n",
1689 					hisstratum));
1690 			sys_declined++;
1691 			return;			/* no help */
1692 		}
1693 
1694 		/*
1695 		 * The message is correctly authenticated and allowed.
1696 		 * Mobilize a symmetric passive association, if we won't
1697 		 * exceed the ippeerlimit.
1698 		 */
1699 		if ((peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1700 				    r4a.ippeerlimit, MODE_PASSIVE, hisversion,
1701 				    pkt->ppoll, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
1702 				    skeyid, sys_ident)) == NULL) {
1703 			DPRINTF(2, ("receive: AM_NEWPASS drop: newpeer() failed\n"));
1704 			sys_declined++;
1705 			return;			/* ignore duplicate */
1706 		}
1707 		break;
1708 
1709 
1710 	/*
1711 	 * Process regular packet. Nothing special.
1712 	 *
1713 	 * There are cases here where we do not call record_raw_stats().
1714 	 */
1715 	case AM_PROCPKT:
1716 
1717 #ifdef AUTOKEY
1718 		/*
1719 		 * Do not respond if not the same group.
1720 		 */
1721 		if (group_test(groupname, peer->ident)) {
1722 			DPRINTF(2, ("receive: AM_PROCPKT drop: Autokey group mismatch\n"));
1723 			sys_declined++;
1724 			return;
1725 		}
1726 #endif /* AUTOKEY */
1727 
1728 		if (MODE_BROADCAST == hismode) {
1729 			int	bail = 0;
1730 			l_fp	tdiff;
1731 			u_long	deadband;
1732 
1733 			DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1734 				    (current_time - peer->timelastrec),
1735 				    peer->ppoll, (1 << peer->ppoll)
1736 				    ));
1737 			/* Things we can check:
1738 			 *
1739 			 * Did the poll interval change?
1740 			 * Is the poll interval in the packet in-range?
1741 			 * Did this packet arrive too soon?
1742 			 * Is the timestamp in this packet monotonic
1743 			 *  with respect to the previous packet?
1744 			 */
1745 
1746 			/* This is noteworthy, not error-worthy */
1747 			if (pkt->ppoll != peer->ppoll) {
1748 				msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %u to %u",
1749 					stoa(&rbufp->recv_srcadr),
1750 					peer->ppoll, pkt->ppoll);
1751 			}
1752 
1753 			/* This is error-worthy */
1754 			if (   pkt->ppoll < peer->minpoll
1755 			    || pkt->ppoll > peer->maxpoll) {
1756 				msyslog(LOG_INFO, "receive: broadcast poll of %u from %s is out-of-range (%d to %d)!",
1757 					pkt->ppoll, stoa(&rbufp->recv_srcadr),
1758 					peer->minpoll, peer->maxpoll);
1759 				++bail;
1760 			}
1761 
1762 			/* too early? worth an error, too!
1763 			 *
1764 			 * [Bug 3113] Ensure that at least one poll
1765 			 * interval has elapsed since the last **clean**
1766 			 * packet was received.  We limit the check to
1767 			 * **clean** packets to prevent replayed packets
1768 			 * and incorrectly authenticated packets, which
1769 			 * we'll discard, from being used to create a
1770 			 * denial of service condition.
1771 			 */
1772 			deadband = (1u << pkt->ppoll);
1773 			if (FLAG_BC_VOL & peer->flags)
1774 				deadband -= 3;	/* allow greater fuzz after volley */
1775 			if ((current_time - peer->timereceived) < deadband) {
1776 				msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1777 					stoa(&rbufp->recv_srcadr),
1778 					(current_time - peer->timereceived),
1779 					deadband);
1780 				++bail;
1781 			}
1782 
1783 			/* Alert if time from the server is non-monotonic.
1784 			 *
1785 			 * [Bug 3114] is about Broadcast mode replay DoS.
1786 			 *
1787 			 * Broadcast mode *assumes* a trusted network.
1788 			 * Even so, it's nice to be robust in the face
1789 			 * of attacks.
1790 			 *
1791 			 * If we get an authenticated broadcast packet
1792 			 * with an "earlier" timestamp, it means one of
1793 			 * two things:
1794 			 *
1795 			 * - the broadcast server had a backward step.
1796 			 *
1797 			 * - somebody is trying a replay attack.
1798 			 *
1799 			 * deadband: By default, we assume the broadcast
1800 			 * network is trustable, so we take our accepted
1801 			 * broadcast packets as we receive them.  But
1802 			 * some folks might want to take additional poll
1803 			 * delays before believing a backward step.
1804 			 */
1805 			if (sys_bcpollbstep) {
1806 				/* pkt->ppoll or peer->ppoll ? */
1807 				deadband = (1u << pkt->ppoll)
1808 					   * sys_bcpollbstep + 2;
1809 			} else {
1810 				deadband = 0;
1811 			}
1812 
1813 			if (L_ISZERO(&peer->bxmt)) {
1814 				tdiff.l_ui = tdiff.l_uf = 0;
1815 			} else {
1816 				tdiff = p_xmt;
1817 				L_SUB(&tdiff, &peer->bxmt);
1818 			}
1819 			if (   tdiff.l_i < 0
1820 			    && (current_time - peer->timereceived) < deadband)
1821 			{
1822 				msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1823 					stoa(&rbufp->recv_srcadr),
1824 					peer->bxmt.l_ui, peer->bxmt.l_uf,
1825 					p_xmt.l_ui, p_xmt.l_uf
1826 					);
1827 				++bail;
1828 			}
1829 
1830 			if (bail) {
1831 				DPRINTF(2, ("receive: AM_PROCPKT drop: bail\n"));
1832 				peer->timelastrec = current_time;
1833 				sys_declined++;
1834 				return;
1835 			}
1836 		}
1837 
1838 		break;
1839 
1840 	/*
1841 	 * A passive packet matches a passive association. This is
1842 	 * usually the result of reconfiguring a client on the fly. As
1843 	 * this association might be legitimate and this packet an
1844 	 * attempt to deny service, just ignore it.
1845 	 */
1846 	case AM_ERR:
1847 		DPRINTF(2, ("receive: AM_ERR drop.\n"));
1848 		sys_declined++;
1849 		return;
1850 
1851 	/*
1852 	 * For everything else there is the bit bucket.
1853 	 */
1854 	default:
1855 		DPRINTF(2, ("receive: default drop.\n"));
1856 		sys_declined++;
1857 		return;
1858 	}
1859 
1860 #ifdef AUTOKEY
1861 	/*
1862 	 * If the association is configured for Autokey, the packet must
1863 	 * have a public key ID; if not, the packet must have a
1864 	 * symmetric key ID.
1865 	 */
1866 	if (   is_authentic != AUTH_CRYPTO
1867 	    && (   ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1868 	        || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1869 		DPRINTF(2, ("receive: drop: Autokey but wrong/bad auth\n"));
1870 		sys_badauth++;
1871 		return;
1872 	}
1873 #endif	/* AUTOKEY */
1874 
1875 	peer->received++;
1876 	peer->flash &= ~PKT_TEST_MASK;
1877 	if (peer->flags & FLAG_XBOGUS) {
1878 		peer->flags &= ~FLAG_XBOGUS;
1879 		peer->flash |= TEST3;
1880 	}
1881 
1882 	/*
1883 	 * Next comes a rigorous schedule of timestamp checking. If the
1884 	 * transmit timestamp is zero, the server has not initialized in
1885 	 * interleaved modes or is horribly broken.
1886 	 *
1887 	 * A KoD packet we pay attention to cannot have a 0 transmit
1888 	 * timestamp.
1889 	 */
1890 
1891 	kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1892 
1893 	if (L_ISZERO(&p_xmt)) {
1894 		peer->flash |= TEST3;			/* unsynch */
1895 		if (kissCode != NOKISS) {		/* KoD packet */
1896 			peer->bogusorg++;		/* for TEST2 or TEST3 */
1897 			msyslog(LOG_INFO,
1898 				"receive: Unexpected zero transmit timestamp in KoD from %s",
1899 				ntoa(&peer->srcadr));
1900 			return;
1901 		}
1902 
1903 	/*
1904 	 * If the transmit timestamp duplicates our previous one, the
1905 	 * packet is a replay. This prevents the bad guys from replaying
1906 	 * the most recent packet, authenticated or not.
1907 	 */
1908 	} else if (   ((FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->nonce, &p_xmt))
1909 		   || (!(FLAG_LOOPNONCE & peer->flags) && L_ISEQU(&peer->xmt, &p_xmt))
1910 	) {
1911 		DPRINTF(2, ("receive: drop: Duplicate xmit\n"));
1912 		peer->flash |= TEST1;			/* duplicate */
1913 		peer->oldpkt++;
1914 		return;
1915 
1916 	/*
1917 	 * If this is a broadcast mode packet, make sure hisstratum
1918 	 * is appropriate.  Don't do anything else here - we wait to
1919 	 * see if this is an interleave broadcast packet until after
1920 	 * we've validated the MAC that SHOULD be provided.
1921 	 *
1922 	 * hisstratum cannot be 0 - see assertion above.
1923 	 * If hisstratum is 15, then we'll advertise as UNSPEC but
1924 	 * at least we'll be able to sync with the broadcast server.
1925 	 */
1926 	} else if (hismode == MODE_BROADCAST) {
1927 		/* 0 is unexpected too, and impossible */
1928 		if (STRATUM_UNSPEC <= hisstratum) {
1929 			/* Is this a ++sys_declined or ??? */
1930 			msyslog(LOG_INFO,
1931 				"receive: Unexpected stratum (%d) in broadcast from %s",
1932 				hisstratum, ntoa(&peer->srcadr));
1933 			return;
1934 		}
1935 
1936 	/*
1937 	 * Basic KoD validation checking:
1938 	 *
1939 	 * KoD packets are a mixed-blessing.  Forged KoD packets
1940 	 * are DoS attacks.  There are rare situations where we might
1941 	 * get a valid KoD response, though.  Since KoD packets are
1942 	 * a special case that complicate the checks we do next, we
1943 	 * handle the basic KoD checks here.
1944 	 *
1945 	 * Note that we expect the incoming KoD packet to have its
1946 	 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1947 	 * that we have previously sent out.  Watch interleave mode.
1948 	 */
1949 	} else if (kissCode != NOKISS) {
1950 		DEBUG_INSIST(!L_ISZERO(&p_xmt));
1951 		if (   L_ISZERO(&p_org)		/* We checked p_xmt above */
1952 		    || L_ISZERO(&p_rec)) {
1953 			peer->bogusorg++;
1954 			msyslog(LOG_INFO,
1955 				"receive: KoD packet from %s has a zero org or rec timestamp.  Ignoring.",
1956 				ntoa(&peer->srcadr));
1957 			return;
1958 		}
1959 
1960 		if (   !L_ISEQU(&p_xmt, &p_org)
1961 		    || !L_ISEQU(&p_xmt, &p_rec)) {
1962 			peer->bogusorg++;
1963 			msyslog(LOG_INFO,
1964 				"receive: KoD packet from %s has inconsistent xmt/org/rec timestamps.  Ignoring.",
1965 				ntoa(&peer->srcadr));
1966 			return;
1967 		}
1968 
1969 		/* Be conservative */
1970 		if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1971 			peer->bogusorg++;
1972 			msyslog(LOG_INFO,
1973 				"receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1974 				p_org.l_ui, p_org.l_uf,
1975 				ntoa(&peer->srcadr),
1976 				peer->aorg.l_ui, peer->aorg.l_uf);
1977 			return;
1978 		} else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1979 			peer->bogusorg++;
1980 			msyslog(LOG_INFO,
1981 				"receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1982 				p_org.l_ui, p_org.l_uf,
1983 				ntoa(&peer->srcadr),
1984 				peer->borg.l_ui, peer->borg.l_uf);
1985 			return;
1986 		}
1987 
1988 	/*
1989 	 * Basic mode checks:
1990 	 *
1991 	 * If there is no origin timestamp, it's either an initial packet
1992 	 * or we've already received a response to our query.  Of course,
1993 	 * should 'aorg' be all-zero because this really was the original
1994 	 * transmit timestamp, we'll ignore this reply.  There is a window
1995 	 * of one nanosecond once every 136 years' time where this is
1996 	 * possible.  We currently ignore this situation, as a completely
1997 	 * zero timestamp is (quietly?) disallowed.
1998 	 *
1999 	 * Otherwise, check for bogus packet in basic mode.
2000 	 * If it is bogus, switch to interleaved mode and resynchronize,
2001 	 * but only after confirming the packet is not bogus in
2002 	 * symmetric interleaved mode.
2003 	 *
2004 	 * This could also mean somebody is forging packets claiming to
2005 	 * be from us, attempting to cause our server to KoD us.
2006 	 *
2007 	 * We have earlier asserted that hisstratum cannot be 0.
2008 	 * If hisstratum is STRATUM_UNSPEC, it means he's not sync'd.
2009 	 */
2010 
2011 	/* XXX: FLAG_LOOPNONCE */
2012 	DEBUG_INSIST(0 == (FLAG_LOOPNONCE & peer->flags));
2013 
2014 	} else if (peer->flip == 0) {
2015 		if (0) {
2016 		} else if (L_ISZERO(&p_org)) {
2017 			const char *action;
2018 
2019 #ifdef BUG3361
2020 			msyslog(LOG_INFO,
2021 				"receive: BUG 3361: Clearing peer->aorg ");
2022 			L_CLR(&peer->aorg);
2023 			/* Clear peer->nonce, too? */
2024 #endif
2025 			/**/
2026 			switch (hismode) {
2027 			/* We allow 0org for: */
2028 			    case UCHAR_MAX:
2029 				action = "Allow";
2030 				break;
2031 			/* We disallow 0org for: */
2032 			    case MODE_UNSPEC:
2033 			    case MODE_ACTIVE:
2034 			    case MODE_PASSIVE:
2035 			    case MODE_CLIENT:
2036 			    case MODE_SERVER:
2037 			    case MODE_BROADCAST:
2038 				action = "Drop";
2039 				peer->bogusorg++;
2040 				peer->flash |= TEST2;	/* bogus */
2041 				break;
2042 			    default:
2043 				action = "";	/* for cranky compilers / MSVC */
2044 				INSIST(!"receive(): impossible hismode");
2045 				break;
2046 			}
2047 			/**/
2048 			msyslog(LOG_INFO,
2049 				"receive: %s 0 origin timestamp from %s@%s xmt %#010x.%08x",
2050 				action, hm_str, ntoa(&peer->srcadr),
2051 				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
2052 		} else if (!L_ISEQU(&p_org, &peer->aorg)) {
2053 			/* are there cases here where we should bail? */
2054 			/* Should we set TEST2 if we decide to try xleave? */
2055 			peer->bogusorg++;
2056 			peer->flash |= TEST2;	/* bogus */
2057 			msyslog(LOG_INFO,
2058 				"receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
2059 				ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
2060 				peer->aorg.l_ui, peer->aorg.l_uf,
2061 				hm_str, ntoa(&peer->srcadr),
2062 				ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
2063 			if (  !L_ISZERO(&peer->dst)
2064 			    && L_ISEQU(&p_org, &peer->dst)) {
2065 				/* Might be the start of an interleave */
2066 				if (dynamic_interleave) {
2067 					peer->flip = 1;
2068 					report_event(PEVNT_XLEAVE, peer, NULL);
2069 				} else {
2070 					msyslog(LOG_INFO,
2071 						"receive: Dynamic interleave from %s@%s denied",
2072 						hm_str, ntoa(&peer->srcadr));
2073 				}
2074 			}
2075 		} else {
2076 			L_CLR(&peer->aorg);
2077 			/* XXX: FLAG_LOOPNONCE */
2078 		}
2079 
2080 	/*
2081 	 * Check for valid nonzero timestamp fields.
2082 	 */
2083 	} else if (   L_ISZERO(&p_org)
2084 		   || L_ISZERO(&p_rec)
2085 		   || L_ISZERO(&peer->dst)) {
2086 		peer->flash |= TEST3;		/* unsynch */
2087 
2088 	/*
2089 	 * Check for bogus packet in interleaved symmetric mode. This
2090 	 * can happen if a packet is lost, duplicated or crossed. If
2091 	 * found, flip and resynchronize.
2092 	 */
2093 	} else if (   !L_ISZERO(&peer->dst)
2094 		   && !L_ISEQU(&p_org, &peer->dst)) {
2095 		DPRINTF(2, ("receive: drop: Bogus packet in interleaved symmetric mode\n"));
2096 		peer->bogusorg++;
2097 		peer->flags |= FLAG_XBOGUS;
2098 		peer->flash |= TEST2;		/* bogus */
2099 #ifdef BUG3453
2100 		return; /* Bogus packet, we are done */
2101 #endif
2102 	}
2103 
2104 	/**/
2105 
2106 	/*
2107 	 * If this is a crypto_NAK, the server cannot authenticate a
2108 	 * client packet. The server might have just changed keys. Clear
2109 	 * the association and restart the protocol.
2110 	 */
2111 	if (crypto_nak_test == VALIDNAK) {
2112 		report_event(PEVNT_AUTH, peer, "crypto_NAK");
2113 		peer->flash |= TEST5;		/* bad auth */
2114 		peer->badauth++;
2115 		if (peer->flags & FLAG_PREEMPT) {
2116 			if (unpeer_crypto_nak_early) {
2117 				unpeer(peer);
2118 			}
2119 			DPRINTF(2, ("receive: drop: PREEMPT crypto_NAK\n"));
2120 			return;
2121 		}
2122 #ifdef AUTOKEY
2123 		if (peer->crypto) {
2124 			peer_clear(peer, "AUTH");
2125 		}
2126 #endif	/* AUTOKEY */
2127 		DPRINTF(2, ("receive: drop: crypto_NAK\n"));
2128 		return;
2129 
2130 	/*
2131 	 * If the digest fails or it's missing for authenticated
2132 	 * associations, the client cannot authenticate a server
2133 	 * reply to a client packet previously sent. The loopback check
2134 	 * is designed to avoid a bait-and-switch attack, which was
2135 	 * possible in past versions. If symmetric modes, return a
2136 	 * crypto-NAK. The peer should restart the protocol.
2137 	 */
2138 	} else if (!AUTH(peer->keyid || has_mac ||
2139 			 (restrict_mask & RES_DONTTRUST), is_authentic)) {
2140 
2141 		if (peer->flash & PKT_TEST_MASK) {
2142 			msyslog(LOG_INFO,
2143 				"receive: Bad auth in packet with bad timestamps from %s denied - spoof?",
2144 				ntoa(&peer->srcadr));
2145 			return;
2146 		}
2147 
2148 		report_event(PEVNT_AUTH, peer, "digest");
2149 		peer->flash |= TEST5;		/* bad auth */
2150 		peer->badauth++;
2151 		if (   has_mac
2152 		    && (   hismode == MODE_ACTIVE
2153 			|| hismode == MODE_PASSIVE))
2154 			fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
2155 		if (peer->flags & FLAG_PREEMPT) {
2156 			if (unpeer_digest_early) {
2157 				unpeer(peer);
2158 			}
2159 		}
2160 #ifdef AUTOKEY
2161 		else if (peer_clear_digest_early && peer->crypto) {
2162 			peer_clear(peer, "AUTH");
2163 		}
2164 #endif	/* AUTOKEY */
2165 		DPRINTF(2, ("receive: drop: Bad or missing AUTH\n"));
2166 		return;
2167 	}
2168 
2169 	/*
2170 	 * For broadcast packets:
2171 	 *
2172 	 * HMS: This next line never made much sense to me, even
2173 	 * when it was up higher:
2174 	 *   If an initial volley, bail out now and let the
2175 	 *   client do its stuff.
2176 	 *
2177 	 * If the packet has not failed authentication, then
2178 	 * - if the origin timestamp is nonzero this is an
2179 	 *   interleaved broadcast, so restart the protocol.
2180 	 * - else, this is not an interleaved broadcast packet.
2181 	 */
2182 	if (hismode == MODE_BROADCAST) {
2183 		if (   is_authentic == AUTH_OK
2184 		    || is_authentic == AUTH_NONE) {
2185 			if (!L_ISZERO(&p_org)) {
2186 				if (!(peer->flags & FLAG_XB)) {
2187 					msyslog(LOG_INFO,
2188 						"receive: Broadcast server at %s is in interleave mode",
2189 						ntoa(&peer->srcadr));
2190 					peer->flags |= FLAG_XB;
2191 					peer->aorg = p_xmt;
2192 					peer->borg = rbufp->recv_time;
2193 					report_event(PEVNT_XLEAVE, peer, NULL);
2194 					return;
2195 				}
2196 			} else if (peer->flags & FLAG_XB) {
2197 				msyslog(LOG_INFO,
2198 					"receive: Broadcast server at %s is no longer in interleave mode",
2199 					ntoa(&peer->srcadr));
2200 				peer->flags &= ~FLAG_XB;
2201 			}
2202 		} else {
2203 			msyslog(LOG_INFO,
2204 				"receive: Bad broadcast auth (%d) from %s",
2205 				is_authentic, ntoa(&peer->srcadr));
2206 		}
2207 
2208 		/*
2209 		 * Now that we know the packet is correctly authenticated,
2210 		 * update peer->bxmt.
2211 		 */
2212 		peer->bxmt = p_xmt;
2213 	}
2214 
2215 
2216 	/*
2217 	** Update the state variables.
2218 	*/
2219 	if (peer->flip == 0) {
2220 		if (hismode != MODE_BROADCAST)
2221 			peer->rec = p_xmt;
2222 		peer->dst = rbufp->recv_time;
2223 	}
2224 	peer->xmt = p_xmt;
2225 
2226 	/*
2227 	 * Set the peer ppoll to the maximum of the packet ppoll and the
2228 	 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
2229 	 * this maximum and advance the headway to give the sender some
2230 	 * headroom. Very intricate.
2231 	 */
2232 
2233 	/*
2234 	 * Check for any kiss codes. Note this is only used when a server
2235 	 * responds to a packet request.
2236 	 */
2237 
2238 	/*
2239 	 * Check to see if this is a RATE Kiss Code
2240 	 * Currently this kiss code will accept whatever poll
2241 	 * rate that the server sends
2242 	 */
2243 	peer->ppoll = max(peer->minpoll, pkt->ppoll);
2244 	if (kissCode == RATEKISS) {
2245 		peer->selbroken++;	/* Increment the KoD count */
2246 		report_event(PEVNT_RATE, peer, NULL);
2247 		if (pkt->ppoll > peer->minpoll)
2248 			peer->minpoll = peer->ppoll;
2249 		peer->burst = peer->retry = 0;
2250 		peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
2251 		poll_update(peer, pkt->ppoll, 0);
2252 		return;				/* kiss-o'-death */
2253 	}
2254 	if (kissCode != NOKISS) {
2255 		peer->selbroken++;	/* Increment the KoD count */
2256 		return;		/* Drop any other kiss code packets */
2257 	}
2258 
2259 
2260 	/*
2261 	 * XXX
2262 	 */
2263 
2264 
2265 	/*
2266 	 * If:
2267 	 *	- this is a *cast (uni-, broad-, or m-) server packet
2268 	 *	- and it's symmetric-key authenticated
2269 	 * then see if the sender's IP is trusted for this keyid.
2270 	 * If it is, great - nothing special to do here.
2271 	 * Otherwise, we should report and bail.
2272 	 *
2273 	 * Autokey-authenticated packets are accepted.
2274 	 */
2275 
2276 	switch (hismode) {
2277 	    case MODE_SERVER:		/* server mode */
2278 	    case MODE_BROADCAST:	/* broadcast mode */
2279 	    case MODE_ACTIVE:		/* symmetric active mode */
2280 	    case MODE_PASSIVE:		/* symmetric passive mode */
2281 		if (   is_authentic == AUTH_OK
2282 		    && skeyid
2283 		    && skeyid <= NTP_MAXKEY
2284 		    && !authistrustedip(skeyid, &peer->srcadr)) {
2285 			report_event(PEVNT_AUTH, peer, "authIP");
2286 			peer->badauth++;
2287 			return;
2288 		}
2289 		break;
2290 
2291 	    case MODE_CLIENT:		/* client mode */
2292 #if 0		/* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
2293 	    case MODE_CONTROL:		/* control mode */
2294 #endif
2295 	    case MODE_PRIVATE:		/* private mode */
2296 	    case MODE_BCLIENT:		/* broadcast client mode */
2297 		break;
2298 
2299 	    case MODE_UNSPEC:		/* unspecified (old version) */
2300 	    default:
2301 		msyslog(LOG_INFO,
2302 			"receive: Unexpected mode (%d) in packet from %s",
2303 			hismode, ntoa(&peer->srcadr));
2304 		break;
2305 	}
2306 
2307 
2308 	/*
2309 	 * That was hard and I am sweaty, but the packet is squeaky
2310 	 * clean. Get on with real work.
2311 	 */
2312 	peer->timereceived = current_time;
2313 	peer->timelastrec = current_time;
2314 	if (is_authentic == AUTH_OK)
2315 		peer->flags |= FLAG_AUTHENTIC;
2316 	else
2317 		peer->flags &= ~FLAG_AUTHENTIC;
2318 
2319 #ifdef AUTOKEY
2320 	/*
2321 	 * More autokey dance. The rules of the cha-cha are as follows:
2322 	 *
2323 	 * 1. If there is no key or the key is not auto, do nothing.
2324 	 *
2325 	 * 2. If this packet is in response to the one just previously
2326 	 *    sent or from a broadcast server, do the extension fields.
2327 	 *    Otherwise, assume bogosity and bail out.
2328 	 *
2329 	 * 3. If an extension field contains a verified signature, it is
2330 	 *    self-authenticated and we sit the dance.
2331 	 *
2332 	 * 4. If this is a server reply, check only to see that the
2333 	 *    transmitted key ID matches the received key ID.
2334 	 *
2335 	 * 5. Check to see that one or more hashes of the current key ID
2336 	 *    matches the previous key ID or ultimate original key ID
2337 	 *    obtained from the broadcaster or symmetric peer. If no
2338 	 *    match, sit the dance and call for new autokey values.
2339 	 *
2340 	 * In case of crypto error, fire the orchestra, stop dancing and
2341 	 * restart the protocol.
2342 	 */
2343 	if (peer->flags & FLAG_SKEY) {
2344 		/*
2345 		 * Decrement remaining autokey hashes. This isn't
2346 		 * perfect if a packet is lost, but results in no harm.
2347 		 */
2348 		ap = (struct autokey *)peer->recval.ptr;
2349 		if (ap != NULL) {
2350 			if (ap->seq > 0)
2351 				ap->seq--;
2352 		}
2353 		peer->flash |= TEST8;
2354 		rval = crypto_recv(peer, rbufp);
2355 		if (rval == XEVNT_OK) {
2356 			peer->unreach = 0;
2357 		} else {
2358 			if (rval == XEVNT_ERR) {
2359 				report_event(PEVNT_RESTART, peer,
2360 				    "crypto error");
2361 				peer_clear(peer, "CRYP");
2362 				peer->flash |= TEST9;	/* bad crypt */
2363 				if (peer->flags & FLAG_PREEMPT) {
2364 					if (unpeer_crypto_early) {
2365 						unpeer(peer);
2366 					}
2367 				}
2368 			}
2369 			return;
2370 		}
2371 
2372 		/*
2373 		 * If server mode, verify the receive key ID matches
2374 		 * the transmit key ID.
2375 		 */
2376 		if (hismode == MODE_SERVER) {
2377 			if (skeyid == peer->keyid)
2378 				peer->flash &= ~TEST8;
2379 
2380 		/*
2381 		 * If an extension field is present, verify only that it
2382 		 * has been correctly signed. We don't need a sequence
2383 		 * check here, but the sequence continues.
2384 		 */
2385 		} else if (!(peer->flash & TEST8)) {
2386 			peer->pkeyid = skeyid;
2387 
2388 		/*
2389 		 * Now the fun part. Here, skeyid is the current ID in
2390 		 * the packet, pkeyid is the ID in the last packet and
2391 		 * tkeyid is the hash of skeyid. If the autokey values
2392 		 * have not been received, this is an automatic error.
2393 		 * If so, check that the tkeyid matches pkeyid. If not,
2394 		 * hash tkeyid and try again. If the number of hashes
2395 		 * exceeds the number remaining in the sequence, declare
2396 		 * a successful failure and refresh the autokey values.
2397 		 */
2398 		} else if (ap != NULL) {
2399 			int i;
2400 
2401 			for (i = 0; ; i++) {
2402 				if (   tkeyid == peer->pkeyid
2403 				    || tkeyid == ap->key) {
2404 					peer->flash &= ~TEST8;
2405 					peer->pkeyid = skeyid;
2406 					ap->seq -= i;
2407 					break;
2408 				}
2409 				if (i > ap->seq) {
2410 					peer->crypto &=
2411 					    ~CRYPTO_FLAG_AUTO;
2412 					break;
2413 				}
2414 				tkeyid = session_key(
2415 				    &rbufp->recv_srcadr, dstadr_sin,
2416 				    tkeyid, pkeyid, 0);
2417 			}
2418 			if (peer->flash & TEST8)
2419 				report_event(PEVNT_AUTH, peer, "keylist");
2420 		}
2421 		if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
2422 			peer->flash |= TEST8;	/* bad autokey */
2423 
2424 		/*
2425 		 * The maximum lifetime of the protocol is about one
2426 		 * week before restarting the Autokey protocol to
2427 		 * refresh certificates and leapseconds values.
2428 		 */
2429 		if (current_time > peer->refresh) {
2430 			report_event(PEVNT_RESTART, peer,
2431 			    "crypto refresh");
2432 			peer_clear(peer, "TIME");
2433 			return;
2434 		}
2435 	}
2436 #endif	/* AUTOKEY */
2437 
2438 	/*
2439 	 * The dance is complete and the flash bits have been lit. Toss
2440 	 * the packet over the fence for processing, which may light up
2441 	 * more flashers. Leave if the packet is not good.
2442 	 */
2443 	process_packet(peer, pkt, rbufp->recv_length);
2444 	if (peer->flash & PKT_TEST_MASK)
2445 		return;
2446 
2447 	/* [bug 3592] Update poll. Ideally this should not happen in a
2448 	 * receive branch, but too much is going on here... at least we
2449 	 * do it only if the packet was good!
2450 	 */
2451 	poll_update(peer, peer->hpoll, (peer->hmode == MODE_CLIENT));
2452 
2453 	/*
2454 	 * In interleaved mode update the state variables. Also adjust the
2455 	 * transmit phase to avoid crossover.
2456 	 */
2457 	if (peer->flip != 0) {
2458 		peer->rec = p_rec;
2459 		peer->dst = rbufp->recv_time;
2460 		if (peer->nextdate - current_time < (1U << min(peer->ppoll,
2461 		    peer->hpoll)) / 2)
2462 			peer->nextdate++;
2463 		else
2464 			peer->nextdate--;
2465 	}
2466 }
2467 
2468 
2469 /*
2470  * process_packet - Packet Procedure, a la Section 3.4.4 of RFC-1305
2471  *	Or almost, at least.  If we're in here we have a reasonable
2472  *	expectation that we will be having a long term
2473  *	relationship with this host.
2474  */
2475 void
process_packet(register struct peer * peer,register struct pkt * pkt,u_int len)2476 process_packet(
2477 	register struct peer *peer,
2478 	register struct pkt *pkt,
2479 	u_int	len
2480 	)
2481 {
2482 	double	t34, t21;
2483 	double	p_offset, p_del, p_disp;
2484 	l_fp	p_rec, p_xmt, p_org, p_reftime, ci;
2485 	u_char	pmode, pleap, pversion, pstratum;
2486 	char	statstr[NTP_MAXSTRLEN];
2487 #ifdef ASSYM
2488 	int	itemp;
2489 	double	etemp, ftemp, td;
2490 #endif /* ASSYM */
2491 
2492 	p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
2493 	p_offset = 0;
2494 	p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
2495 	NTOHL_FP(&pkt->reftime, &p_reftime);
2496 	NTOHL_FP(&pkt->org, &p_org);
2497 	NTOHL_FP(&pkt->rec, &p_rec);
2498 	NTOHL_FP(&pkt->xmt, &p_xmt);
2499 	pmode = PKT_MODE(pkt->li_vn_mode);
2500 	pleap = PKT_LEAP(pkt->li_vn_mode);
2501 	pversion = PKT_VERSION(pkt->li_vn_mode);
2502 	pstratum = PKT_TO_STRATUM(pkt->stratum);
2503 
2504 	/*
2505 	 * Verify the server is synchronized; that is, the leap bits,
2506 	 * stratum and root distance are valid.
2507 	 */
2508 	if (   pleap == LEAP_NOTINSYNC		/* test 6 */
2509 	    || pstratum < sys_floor || pstratum >= sys_ceiling)
2510 		peer->flash |= TEST6;		/* bad synch or strat */
2511 	if (p_del / 2 + p_disp >= MAXDISPERSE)	/* test 7 */
2512 		peer->flash |= TEST7;		/* bad header */
2513 
2514 	/*
2515 	 * If any tests fail at this point, the packet is discarded.
2516 	 * Note that some flashers may have already been set in the
2517 	 * receive() routine.
2518 	 */
2519 	if (peer->flash & PKT_TEST_MASK) {
2520 		peer->seldisptoolarge++;
2521 		DPRINTF(1, ("packet: flash header %04x\n",
2522 			    peer->flash));
2523 		/* [Bug 3592] do *not* update poll on bad packets! */
2524 		return;
2525 	}
2526 
2527 	/*
2528 	 * update stats, now that we really handle this packet:
2529 	 */
2530 	sys_processed++;
2531 	peer->processed++;
2532 
2533 	/*
2534 	 * Capture the header values in the client/peer association..
2535 	 */
2536 	record_raw_stats(&peer->srcadr,
2537 	    peer->dstadr ? &peer->dstadr->sin : NULL,
2538 	    &p_org, &p_rec, &p_xmt, &peer->dst,
2539 	    pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2540 	    p_del, p_disp, pkt->refid,
2541 	    len - MIN_V4_PKT_LEN, (u_char *)&pkt->exten);
2542 	peer->leap = pleap;
2543 	peer->stratum = min(pstratum, STRATUM_UNSPEC);
2544 	peer->pmode = pmode;
2545 	peer->precision = pkt->precision;
2546 	peer->rootdelay = p_del;
2547 	peer->rootdisp = p_disp;
2548 	peer->refid = pkt->refid;		/* network byte order */
2549 	peer->reftime = p_reftime;
2550 
2551 	/*
2552 	 * First, if either burst mode is armed, enable the burst.
2553 	 * Compute the headway for the next packet and delay if
2554 	 * necessary to avoid exceeding the threshold.
2555 	 */
2556 	if (peer->retry > 0) {
2557 		peer->retry = 0;
2558 		if (peer->reach)
2559 			peer->burst = min(1 << (peer->hpoll -
2560 			    peer->minpoll), NTP_SHIFT) - 1;
2561 		else
2562 			peer->burst = NTP_IBURST - 1;
2563 		if (peer->burst > 0)
2564 			peer->nextdate = current_time;
2565 	}
2566 
2567 	/*
2568 	 * If the peer was previously unreachable, raise a trap. In any
2569 	 * case, mark it reachable.
2570 	 */
2571 	if (!peer->reach) {
2572 		report_event(PEVNT_REACH, peer, NULL);
2573 		peer->timereachable = current_time;
2574 	}
2575 	peer->reach |= 1;
2576 
2577 	/*
2578 	 * For a client/server association, calculate the clock offset,
2579 	 * roundtrip delay and dispersion. The equations are reordered
2580 	 * from the spec for more efficient use of temporaries. For a
2581 	 * broadcast association, offset the last measurement by the
2582 	 * computed delay during the client/server volley. Note the
2583 	 * computation of dispersion includes the system precision plus
2584 	 * that due to the frequency error since the origin time.
2585 	 *
2586 	 * It is very important to respect the hazards of overflow. The
2587 	 * only permitted operation on raw timestamps is subtraction,
2588 	 * where the result is a signed quantity spanning from 68 years
2589 	 * in the past to 68 years in the future. To avoid loss of
2590 	 * precision, these calculations are done using 64-bit integer
2591 	 * arithmetic. However, the offset and delay calculations are
2592 	 * sums and differences of these first-order differences, which
2593 	 * if done using 64-bit integer arithmetic, would be valid over
2594 	 * only half that span. Since the typical first-order
2595 	 * differences are usually very small, they are converted to 64-
2596 	 * bit doubles and all remaining calculations done in floating-
2597 	 * double arithmetic. This preserves the accuracy while
2598 	 * retaining the 68-year span.
2599 	 *
2600 	 * There are three interleaving schemes, basic, interleaved
2601 	 * symmetric and interleaved broadcast. The timestamps are
2602 	 * idioscyncratically different. See the onwire briefing/white
2603 	 * paper at www.eecis.udel.edu/~mills for details.
2604 	 *
2605 	 * Interleaved symmetric mode
2606 	 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2607 	 * t4 = peer->dst
2608 	 */
2609 	if (peer->flip != 0) {
2610 		ci = p_xmt;				/* t3 - t4 */
2611 		L_SUB(&ci, &peer->dst);
2612 		LFPTOD(&ci, t34);
2613 		ci = p_rec;				/* t2 - t1 */
2614 		if (peer->flip > 0)
2615 			L_SUB(&ci, &peer->borg);
2616 		else
2617 			L_SUB(&ci, &peer->aorg);
2618 		LFPTOD(&ci, t21);
2619 		p_del = t21 - t34;
2620 		p_offset = (t21 + t34) / 2.;
2621 		if (p_del < 0 || p_del > 1.) {
2622 			snprintf(statstr, sizeof(statstr),
2623 			    "t21 %.6f t34 %.6f", t21, t34);
2624 			report_event(PEVNT_XERR, peer, statstr);
2625 			return;
2626 		}
2627 
2628 	/*
2629 	 * Broadcast modes
2630 	 */
2631 	} else if (peer->pmode == MODE_BROADCAST) {
2632 
2633 		/*
2634 		 * Interleaved broadcast mode. Use interleaved timestamps.
2635 		 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2636 		 */
2637 		if (peer->flags & FLAG_XB) {
2638 			ci = p_org;			/* delay */
2639 			L_SUB(&ci, &peer->aorg);
2640 			LFPTOD(&ci, t34);
2641 			ci = p_org;			/* t2 - t1 */
2642 			L_SUB(&ci, &peer->borg);
2643 			LFPTOD(&ci, t21);
2644 			peer->aorg = p_xmt;
2645 			peer->borg = peer->dst;
2646 			if (t34 < 0 || t34 > 1.) {
2647 				/* drop all if in the initial volley */
2648 				if (FLAG_BC_VOL & peer->flags)
2649 					goto bcc_init_volley_fail;
2650 				snprintf(statstr, sizeof(statstr),
2651 				    "offset %.6f delay %.6f", t21, t34);
2652 				report_event(PEVNT_XERR, peer, statstr);
2653 				return;
2654 			}
2655 			p_offset = t21;
2656 			peer->xleave = t34;
2657 
2658 		/*
2659 		 * Basic broadcast - use direct timestamps.
2660 		 * t3 = p_xmt, t4 = peer->dst
2661 		 */
2662 		} else {
2663 			ci = p_xmt;		/* t3 - t4 */
2664 			L_SUB(&ci, &peer->dst);
2665 			LFPTOD(&ci, t34);
2666 			p_offset = t34;
2667 		}
2668 
2669 		/*
2670 		 * When calibration is complete and the clock is
2671 		 * synchronized, the bias is calculated as the difference
2672 		 * between the unicast timestamp and the broadcast
2673 		 * timestamp. This works for both basic and interleaved
2674 		 * modes.
2675 		 * [Bug 3031] Don't keep this peer when the delay
2676 		 * calculation gives reason to suspect clock steps.
2677 		 * This is assumed for delays > 50ms.
2678 		 */
2679 		if (FLAG_BC_VOL & peer->flags) {
2680 			peer->flags &= ~FLAG_BC_VOL;
2681 			peer->delay = fabs(peer->offset - p_offset) * 2;
2682 			DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2683 				peer->delay));
2684 			if (peer->delay > fabs(sys_bdelay)) {
2685 		bcc_init_volley_fail:
2686 				DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2687 				unpeer(peer);
2688 				return;
2689 			}
2690 		}
2691 		peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2692 		p_del = peer->delay;
2693 		p_offset += p_del / 2;
2694 
2695 
2696 	/*
2697 	 * Basic mode, otherwise known as the old fashioned way.
2698 	 *
2699 	 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2700 	 */
2701 	} else {
2702 		ci = p_xmt;				/* t3 - t4 */
2703 		L_SUB(&ci, &peer->dst);
2704 		LFPTOD(&ci, t34);
2705 		ci = p_rec;				/* t2 - t1 */
2706 		L_SUB(&ci, &p_org);
2707 		LFPTOD(&ci, t21);
2708 		p_del = fabs(t21 - t34);
2709 		p_offset = (t21 + t34) / 2.;
2710 	}
2711 	p_del = max(p_del, LOGTOD(sys_precision));
2712 	p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2713 	    clock_phi * p_del;
2714 
2715 #if ASSYM
2716 	/*
2717 	 * This code calculates the outbound and inbound data rates by
2718 	 * measuring the differences between timestamps at different
2719 	 * packet lengths. This is helpful in cases of large asymmetric
2720 	 * delays commonly experienced on deep space communication
2721 	 * links.
2722 	 */
2723 	if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2724 		itemp = peer->t21_bytes - peer->t21_last;
2725 		if (itemp > 25) {
2726 			etemp = t21 - peer->t21;
2727 			if (fabs(etemp) > 1e-6) {
2728 				ftemp = itemp / etemp;
2729 				if (ftemp > 1000.)
2730 					peer->r21 = ftemp;
2731 			}
2732 		}
2733 		itemp = len - peer->t34_bytes;
2734 		if (itemp > 25) {
2735 			etemp = -t34 - peer->t34;
2736 			if (fabs(etemp) > 1e-6) {
2737 				ftemp = itemp / etemp;
2738 				if (ftemp > 1000.)
2739 					peer->r34 = ftemp;
2740 			}
2741 		}
2742 	}
2743 
2744 	/*
2745 	 * The following section compensates for different data rates on
2746 	 * the outbound (d21) and inbound (t34) directions. To do this,
2747 	 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2748 	 * the roundtrip delay. Then it calculates the correction as a
2749 	 * fraction of d.
2750 	 */
2751 	peer->t21 = t21;
2752 	peer->t21_last = peer->t21_bytes;
2753 	peer->t34 = -t34;
2754 	peer->t34_bytes = len;
2755 	DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2756 		    peer->t21_bytes, peer->t34, peer->t34_bytes));
2757 	if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2758 		if (peer->pmode != MODE_BROADCAST)
2759 			td = (peer->r34 / (peer->r21 + peer->r34) -
2760 			    .5) * p_del;
2761 		else
2762 			td = 0;
2763 
2764 		/*
2765 		 * Unfortunately, in many cases the errors are
2766 		 * unacceptable, so for the present the rates are not
2767 		 * used. In future, we might find conditions where the
2768 		 * calculations are useful, so this should be considered
2769 		 * a work in progress.
2770 		 */
2771 		t21 -= td;
2772 		t34 -= td;
2773 		DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2774 			    p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2775 			    td));
2776 	}
2777 #endif /* ASSYM */
2778 
2779 	/*
2780 	 * That was awesome. Now hand off to the clock filter.
2781 	 */
2782 	clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2783 
2784 	/*
2785 	 * If we are in broadcast calibrate mode, return to broadcast
2786 	 * client mode when the client is fit and the autokey dance is
2787 	 * complete.
2788 	 */
2789 	if (   (FLAG_BC_VOL & peer->flags)
2790 	    && MODE_CLIENT == peer->hmode
2791 	    && !(TEST11 & peer_unfit(peer))) {	/* distance exceeded */
2792 #ifdef AUTOKEY
2793 		if (peer->flags & FLAG_SKEY) {
2794 			if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2795 				peer->hmode = MODE_BCLIENT;
2796 		} else {
2797 			peer->hmode = MODE_BCLIENT;
2798 		}
2799 #else	/* !AUTOKEY follows */
2800 		peer->hmode = MODE_BCLIENT;
2801 #endif	/* !AUTOKEY */
2802 	}
2803 }
2804 
2805 
2806 /*
2807  * clock_update - Called at system process update intervals.
2808  */
2809 static void
clock_update(struct peer * peer)2810 clock_update(
2811 	struct peer *peer	/* peer structure pointer */
2812 	)
2813 {
2814 	double	dtemp;
2815 	l_fp	now;
2816 #ifdef HAVE_LIBSCF_H
2817 	char	*fmri;
2818 #endif /* HAVE_LIBSCF_H */
2819 
2820 	/*
2821 	 * Update the system state variables. We do this very carefully,
2822 	 * as the poll interval might need to be clamped differently.
2823 	 */
2824 	sys_peer = peer;
2825 	sys_epoch = peer->epoch;
2826 	if (sys_poll < peer->minpoll)
2827 		sys_poll = peer->minpoll;
2828 	if (sys_poll > peer->maxpoll)
2829 		sys_poll = peer->maxpoll;
2830 	poll_update(peer, sys_poll, 0);
2831 	sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2832 	if (   peer->stratum == STRATUM_REFCLOCK
2833 	    || peer->stratum == STRATUM_UNSPEC)
2834 		sys_refid = peer->refid;
2835 	else
2836 		sys_refid = addr2refid(&peer->srcadr);
2837 	/*
2838 	 * Root Dispersion (E) is defined (in RFC 5905) as:
2839 	 *
2840 	 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2841 	 *
2842 	 * where:
2843 	 *  p.epsilon_r is the PollProc's root dispersion
2844 	 *  p.epsilon   is the PollProc's dispersion
2845 	 *  p.psi       is the PollProc's jitter
2846 	 *  THETA       is the combined offset
2847 	 *
2848 	 * NB: Think Hard about where these numbers come from and
2849 	 * what they mean.  When did peer->update happen?  Has anything
2850 	 * interesting happened since then?  What values are the most
2851 	 * defensible?  Why?
2852 	 *
2853 	 * DLM thinks this equation is probably the best of all worse choices.
2854 	 */
2855 	dtemp	= peer->rootdisp
2856 		+ peer->disp
2857 		+ sys_jitter
2858 		+ clock_phi * (current_time - peer->update)
2859 		+ fabs(sys_offset);
2860 
2861 	p2_rootdisp = prev_rootdisp;
2862 	prev_rootdisp = sys_rootdisp;
2863 	if (dtemp > sys_mindisp)
2864 		sys_rootdisp = dtemp;
2865 	else
2866 		sys_rootdisp = sys_mindisp;
2867 
2868 	sys_rootdelay = peer->delay + peer->rootdelay;
2869 
2870 	p2_reftime = prev_reftime;
2871 	p2_time = prev_time;
2872 
2873 	prev_reftime = sys_reftime;
2874 	prev_time = current_time + 64 + (rand() & 0x3f);	/* 64-127 s */
2875 
2876 	sys_reftime = peer->dst;
2877 
2878 	DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2879 		    current_time, peer->epoch, peer->associd));
2880 
2881 	/*
2882 	 * Comes now the moment of truth. Crank the clock discipline and
2883 	 * see what comes out.
2884 	 */
2885 	switch (local_clock(peer, sys_offset)) {
2886 
2887 	/*
2888 	 * Clock exceeds panic threshold. Life as we know it ends.
2889 	 */
2890 	case -1:
2891 #ifdef HAVE_LIBSCF_H
2892 		/*
2893 		 * For Solaris enter the maintenance mode.
2894 		 */
2895 		if ((fmri = getenv("SMF_FMRI")) != NULL) {
2896 			if (smf_maintain_instance(fmri, 0) < 0) {
2897 				printf("smf_maintain_instance: %s\n",
2898 				    scf_strerror(scf_error()));
2899 				exit(1);
2900 			}
2901 			/*
2902 			 * Sleep until SMF kills us.
2903 			 */
2904 			for (;;)
2905 				pause();
2906 		}
2907 #endif /* HAVE_LIBSCF_H */
2908 		exit (-1);
2909 		/* not reached */
2910 
2911 	/*
2912 	 * Clock was stepped. Flush all time values of all peers.
2913 	 */
2914 	case 2:
2915 		clear_all();
2916 		set_sys_leap(LEAP_NOTINSYNC);
2917 		sys_stratum = STRATUM_UNSPEC;
2918 		memcpy(&sys_refid, "STEP", 4);
2919 		sys_rootdelay = 0;
2920 		p2_rootdisp = 0;
2921 		prev_rootdisp = 0;
2922 		sys_rootdisp = 0;
2923 		L_CLR(&p2_reftime);	/* Should we clear p2_reftime? */
2924 		L_CLR(&prev_reftime);	/* Should we clear prev_reftime? */
2925 		L_CLR(&sys_reftime);
2926 		sys_jitter = LOGTOD(sys_precision);
2927 		leapsec_reset_frame();
2928 		break;
2929 
2930 	/*
2931 	 * Clock was slewed. Handle the leapsecond stuff.
2932 	 */
2933 	case 1:
2934 
2935 		/*
2936 		 * If this is the first time the clock is set, reset the
2937 		 * leap bits. If crypto, the timer will goose the setup
2938 		 * process.
2939 		 */
2940 		if (sys_leap == LEAP_NOTINSYNC) {
2941 			set_sys_leap(LEAP_NOWARNING);
2942 #ifdef AUTOKEY
2943 			if (crypto_flags)
2944 				crypto_update();
2945 #endif	/* AUTOKEY */
2946 			/*
2947 			 * If our parent process is waiting for the
2948 			 * first clock sync, send them home satisfied.
2949 			 */
2950 #ifdef HAVE_WORKING_FORK
2951 			if (daemon_pipe[1] != -1) {
2952 				write(daemon_pipe[1], "S\n", 2);
2953 				close(daemon_pipe[1]);
2954 				daemon_pipe[1] = -1;
2955 				DPRINTF(1, ("notified parent --wait-sync is done\n"));
2956 			}
2957 #endif /* HAVE_WORKING_FORK */
2958 
2959 		}
2960 
2961 		/*
2962 		 * If there is no leap second pending and the number of
2963 		 * survivor leap bits is greater than half the number of
2964 		 * survivors, try to schedule a leap for the end of the
2965 		 * current month. (This only works if no leap second for
2966 		 * that range is in the table, so doing this more than
2967 		 * once is mostly harmless.)
2968 		 */
2969 		if (leapsec == LSPROX_NOWARN) {
2970 			if (   leap_vote_ins > leap_vote_del
2971 			    && leap_vote_ins > sys_survivors / 2) {
2972 				get_systime(&now);
2973 				leapsec_add_dyn(TRUE, now.l_ui, NULL);
2974 			}
2975 			if (   leap_vote_del > leap_vote_ins
2976 			    && leap_vote_del > sys_survivors / 2) {
2977 				get_systime(&now);
2978 				leapsec_add_dyn(FALSE, now.l_ui, NULL);
2979 			}
2980 		}
2981 		break;
2982 
2983 	/*
2984 	 * Popcorn spike or step threshold exceeded. Pretend it never
2985 	 * happened.
2986 	 */
2987 	default:
2988 		break;
2989 	}
2990 }
2991 
2992 
2993 /*
2994  * poll_update - update peer poll interval
2995  */
2996 void
poll_update(struct peer * peer,u_char mpoll,u_char skewpoll)2997 poll_update(
2998 	struct peer *peer,	/* peer structure pointer */
2999 	u_char	mpoll,
3000 	u_char  skewpoll
3001 	)
3002 {
3003 	u_long	next, utemp, limit;
3004 	u_char	hpoll;
3005 
3006 	/*
3007 	 * This routine figures out when the next poll should be sent.
3008 	 * That turns out to be wickedly complicated. One problem is
3009 	 * that sometimes the time for the next poll is in the past when
3010 	 * the poll interval is reduced. We watch out for races here
3011 	 * between the receive process and the poll process.
3012 	 *
3013 	 * Clamp the poll interval between minpoll and maxpoll.
3014 	 */
3015 	hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
3016 
3017 #ifdef AUTOKEY
3018 	/*
3019 	 * If during the crypto protocol the poll interval has changed,
3020 	 * the lifetimes in the key list are probably bogus. Purge the
3021 	 * the key list and regenerate it later.
3022 	 */
3023 	if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
3024 		key_expire(peer);
3025 #endif	/* AUTOKEY */
3026 	peer->hpoll = hpoll;
3027 
3028 	/*
3029 	 * There are three variables important for poll scheduling, the
3030 	 * current time (current_time), next scheduled time (nextdate)
3031 	 * and the earliest time (utemp). The earliest time is 2 s
3032 	 * seconds, but could be more due to rate management. When
3033 	 * sending in a burst, use the earliest time. When not in a
3034 	 * burst but with a reply pending, send at the earliest time
3035 	 * unless the next scheduled time has not advanced. This can
3036 	 * only happen if multiple replies are pending in the same
3037 	 * response interval. Otherwise, send at the later of the next
3038 	 * scheduled time and the earliest time.
3039 	 *
3040 	 * Now we figure out if there is an override. If a burst is in
3041 	 * progress and we get called from the receive process, just
3042 	 * slink away. If called from the poll process, delay 1 s for a
3043 	 * reference clock, otherwise 2 s.
3044 	 */
3045 	utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
3046 	    (1 << peer->minpoll), ntp_minpkt);
3047 
3048  	/*[Bug 3592] avoid unlimited postpone of next poll */
3049 	limit = (2u << hpoll);
3050 	if (limit > 64)
3051 		limit -= (limit >> 2);
3052 	limit += peer->outdate;
3053 	if (limit < current_time)
3054 		limit = current_time;
3055 
3056 	if (peer->burst > 0) {
3057 		if (peer->nextdate > current_time)
3058 			return;
3059 #ifdef REFCLOCK
3060 		else if (peer->flags & FLAG_REFCLOCK)
3061 			peer->nextdate = current_time + RESP_DELAY;
3062 #endif /* REFCLOCK */
3063 		else
3064 			peer->nextdate = utemp;
3065 
3066 #ifdef AUTOKEY
3067 	/*
3068 	 * If a burst is not in progress and a crypto response message
3069 	 * is pending, delay 2 s, but only if this is a new interval.
3070 	 */
3071 	} else if (peer->cmmd != NULL) {
3072 		if (peer->nextdate > current_time) {
3073 			if (peer->nextdate + ntp_minpkt != utemp)
3074 				peer->nextdate = utemp;
3075 		} else {
3076 			peer->nextdate = utemp;
3077 		}
3078 #endif	/* AUTOKEY */
3079 
3080 	/*
3081 	 * The ordinary case. If a retry, use minpoll; if unreachable,
3082 	 * use host poll; otherwise, use the minimum of host and peer
3083 	 * polls; In other words, oversampling is okay but
3084 	 * understampling is evil. Use the maximum of this value and the
3085 	 * headway. If the average headway is greater than the headway
3086 	 * threshold, increase the headway by the minimum interval.
3087 	 */
3088 	} else {
3089 		if (peer->retry > 0)
3090 			hpoll = peer->minpoll;
3091 		else
3092 			hpoll = min(peer->ppoll, peer->hpoll);
3093 #ifdef REFCLOCK
3094 		if (peer->flags & FLAG_REFCLOCK)
3095 			next = 1 << hpoll;
3096 		else
3097 #endif /* REFCLOCK */
3098 			next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
3099 			    hpoll) >> 12;
3100 		next += peer->outdate;
3101 		/* XXX: bug3596: Deal with poll skew list? */
3102 		if (skewpoll) {
3103 			psl_item psi;
3104 
3105 			if (0 == get_pollskew(hpoll, &psi)) {
3106 				int sub = psi.sub;
3107 				int qty = psi.qty;
3108 				int msk = psi.msk;
3109 				int val;
3110 
3111 				if (   0 != sub
3112 				    || 0 != qty) {
3113 				    	do {
3114 						val = ntp_random() & msk;
3115 					} while (val > qty);
3116 
3117 					next -= sub;
3118 					next += val;
3119 				}
3120 			} else {
3121 				/* get_pollskew() already logged this */
3122 			}
3123 		}
3124 		if (next > utemp)
3125 			peer->nextdate = next;
3126 		else
3127 			peer->nextdate = utemp;
3128 		if (peer->throttle > (1 << peer->minpoll))
3129 			peer->nextdate += ntp_minpkt;
3130 	}
3131 
3132  	/*[Bug 3592] avoid unlimited postpone of next poll */
3133 	if (peer->nextdate > limit) {
3134 		DPRINTF(1, ("poll_update: clamp reached; limit %lu next %lu\n",
3135 			    limit, peer->nextdate));
3136 		peer->nextdate = limit;
3137 	}
3138 	DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
3139 		    current_time, ntoa(&peer->srcadr), peer->hpoll,
3140 		    peer->burst, peer->retry, peer->throttle,
3141 		    utemp - current_time, peer->nextdate -
3142 		    current_time));
3143 }
3144 
3145 
3146 /*
3147  * peer_clear - clear peer filter registers.  See Section 3.4.8 of the
3148  * spec.
3149  */
3150 void
peer_clear(struct peer * peer,const char * ident)3151 peer_clear(
3152 	struct peer *peer,		/* peer structure */
3153 	const char *ident		/* tally lights */
3154 	)
3155 {
3156 	u_char	u;
3157 	l_fp	bxmt = peer->bxmt;	/* bcast clients retain this! */
3158 
3159 #ifdef AUTOKEY
3160 	/*
3161 	 * If cryptographic credentials have been acquired, toss them to
3162 	 * Valhalla. Note that autokeys are ephemeral, in that they are
3163 	 * tossed immediately upon use. Therefore, the keylist can be
3164 	 * purged anytime without needing to preserve random keys. Note
3165 	 * that, if the peer is purged, the cryptographic variables are
3166 	 * purged, too. This makes it much harder to sneak in some
3167 	 * unauthenticated data in the clock filter.
3168 	 */
3169 	key_expire(peer);
3170 	if (peer->iffval != NULL)
3171 		BN_free(peer->iffval);
3172 	value_free(&peer->cookval);
3173 	value_free(&peer->recval);
3174 	value_free(&peer->encrypt);
3175 	value_free(&peer->sndval);
3176 	if (peer->cmmd != NULL)
3177 		free(peer->cmmd);
3178 	if (peer->subject != NULL)
3179 		free(peer->subject);
3180 	if (peer->issuer != NULL)
3181 		free(peer->issuer);
3182 #endif /* AUTOKEY */
3183 
3184 	/*
3185 	 * Clear all values, including the optional crypto values above.
3186 	 */
3187 	memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
3188 	peer->ppoll = peer->maxpoll;
3189 	peer->hpoll = peer->minpoll;
3190 	peer->disp = MAXDISPERSE;
3191 	peer->flash = peer_unfit(peer);
3192 	peer->jitter = LOGTOD(sys_precision);
3193 
3194 	/* Don't throw away our broadcast replay protection */
3195 	if (peer->hmode == MODE_BCLIENT)
3196 		peer->bxmt = bxmt;
3197 
3198 	/*
3199 	 * If interleave mode, initialize the alternate origin switch.
3200 	 */
3201 	if (peer->flags & FLAG_XLEAVE)
3202 		peer->flip = 1;
3203 	for (u = 0; u < NTP_SHIFT; u++) {
3204 		peer->filter_order[u] = u;
3205 		peer->filter_disp[u] = MAXDISPERSE;
3206 	}
3207 #ifdef REFCLOCK
3208 	if (!(peer->flags & FLAG_REFCLOCK)) {
3209 #endif
3210 		peer->leap = LEAP_NOTINSYNC;
3211 		peer->stratum = STRATUM_UNSPEC;
3212 		memcpy(&peer->refid, ident, 4);
3213 #ifdef REFCLOCK
3214 	} else {
3215 		/* Clear refclock sample filter */
3216 		peer->procptr->codeproc = 0;
3217 		peer->procptr->coderecv = 0;
3218 	}
3219 #endif
3220 
3221 	/*
3222 	 * During initialization use the association count to spread out
3223 	 * the polls at one-second intervals. Passive associations'
3224 	 * first poll is delayed by the "discard minimum" to avoid rate
3225 	 * limiting. Other post-startup new or cleared associations
3226 	 * randomize the first poll over the minimum poll interval to
3227 	 * avoid implosion.
3228 	 */
3229 	peer->nextdate = peer->update = peer->outdate = current_time;
3230 	if (initializing) {
3231 		peer->nextdate += peer_associations;
3232 	} else if (MODE_PASSIVE == peer->hmode) {
3233 		peer->nextdate += ntp_minpkt;
3234 	} else {
3235 		peer->nextdate += ntp_random() % peer->minpoll;
3236 	}
3237 #ifdef AUTOKEY
3238 	peer->refresh = current_time + (1 << NTP_REFRESH);
3239 #endif	/* AUTOKEY */
3240 	DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
3241 		    current_time, peer->nextdate, peer->associd,
3242 		    ident));
3243 }
3244 
3245 
3246 /*
3247  * clock_filter - add incoming clock sample to filter register and run
3248  *		  the filter procedure to find the best sample.
3249  */
3250 void
clock_filter(struct peer * peer,double sample_offset,double sample_delay,double sample_disp)3251 clock_filter(
3252 	struct peer *peer,		/* peer structure pointer */
3253 	double	sample_offset,		/* clock offset */
3254 	double	sample_delay,		/* roundtrip delay */
3255 	double	sample_disp		/* dispersion */
3256 	)
3257 {
3258 	double	dst[NTP_SHIFT];		/* distance vector */
3259 	int	ord[NTP_SHIFT];		/* index vector */
3260 	int	i, j, k, m;
3261 	double	dtemp, etemp;
3262 	char	tbuf[80];
3263 
3264 	/*
3265 	 * A sample consists of the offset, delay, dispersion and epoch
3266 	 * of arrival. The offset and delay are determined by the on-
3267 	 * wire protocol. The dispersion grows from the last outbound
3268 	 * packet to the arrival of this one increased by the sum of the
3269 	 * peer precision and the system precision as required by the
3270 	 * error budget. First, shift the new arrival into the shift
3271 	 * register discarding the oldest one.
3272 	 */
3273 	j = peer->filter_nextpt;
3274 	peer->filter_offset[j] = sample_offset;
3275 	peer->filter_delay[j] = sample_delay;
3276 	peer->filter_disp[j] = sample_disp;
3277 	peer->filter_epoch[j] = current_time;
3278 	j = (j + 1) % NTP_SHIFT;
3279 	peer->filter_nextpt = j;
3280 
3281 	/*
3282 	 * Update dispersions since the last update and at the same
3283 	 * time initialize the distance and index lists. Since samples
3284 	 * become increasingly uncorrelated beyond the Allan intercept,
3285 	 * only under exceptional cases will an older sample be used.
3286 	 * Therefore, the distance list uses a compound metric. If the
3287 	 * dispersion is greater than the maximum dispersion, clamp the
3288 	 * distance at that value. If the time since the last update is
3289 	 * less than the Allan intercept use the delay; otherwise, use
3290 	 * the sum of the delay and dispersion.
3291 	 */
3292 	dtemp = clock_phi * (current_time - peer->update);
3293 	peer->update = current_time;
3294 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
3295 		if (i != 0)
3296 			peer->filter_disp[j] += dtemp;
3297 		if (peer->filter_disp[j] >= MAXDISPERSE) {
3298 			peer->filter_disp[j] = MAXDISPERSE;
3299 			dst[i] = MAXDISPERSE;
3300 		} else if (peer->update - peer->filter_epoch[j] >
3301 		    (u_long)ULOGTOD(allan_xpt)) {
3302 			dst[i] = peer->filter_delay[j] +
3303 			    peer->filter_disp[j];
3304 		} else {
3305 			dst[i] = peer->filter_delay[j];
3306 		}
3307 		ord[i] = j;
3308 		j = (j + 1) % NTP_SHIFT;
3309 	}
3310 
3311 	/*
3312 	 * If the clock has stabilized, sort the samples by distance.
3313 	 */
3314 	if (freq_cnt == 0) {
3315 		for (i = 1; i < NTP_SHIFT; i++) {
3316 			for (j = 0; j < i; j++) {
3317 				if (dst[j] > dst[i]) {
3318 					k = ord[j];
3319 					ord[j] = ord[i];
3320 					ord[i] = k;
3321 					etemp = dst[j];
3322 					dst[j] = dst[i];
3323 					dst[i] = etemp;
3324 				}
3325 			}
3326 		}
3327 	}
3328 
3329 	/*
3330 	 * Copy the index list to the association structure so ntpq
3331 	 * can see it later. Prune the distance list to leave only
3332 	 * samples less than the maximum dispersion, which disfavors
3333 	 * uncorrelated samples older than the Allan intercept. To
3334 	 * further improve the jitter estimate, of the remainder leave
3335 	 * only samples less than the maximum distance, but keep at
3336 	 * least two samples for jitter calculation.
3337 	 */
3338 	m = 0;
3339 	for (i = 0; i < NTP_SHIFT; i++) {
3340 		peer->filter_order[i] = (u_char) ord[i];
3341 		if (   dst[i] >= MAXDISPERSE
3342 		    || (m >= 2 && dst[i] >= sys_maxdist))
3343 			continue;
3344 		m++;
3345 	}
3346 
3347 	/*
3348 	 * Compute the dispersion and jitter. The dispersion is weighted
3349 	 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
3350 	 * to 1.0. The jitter is the RMS differences relative to the
3351 	 * lowest delay sample.
3352 	 */
3353 	peer->disp = peer->jitter = 0;
3354 	k = ord[0];
3355 	for (i = NTP_SHIFT - 1; i >= 0; i--) {
3356 		j = ord[i];
3357 		peer->disp = NTP_FWEIGHT * (peer->disp +
3358 		    peer->filter_disp[j]);
3359 		if (i < m)
3360 			peer->jitter += DIFF(peer->filter_offset[j],
3361 			    peer->filter_offset[k]);
3362 	}
3363 
3364 	/*
3365 	 * If no acceptable samples remain in the shift register,
3366 	 * quietly tiptoe home leaving only the dispersion. Otherwise,
3367 	 * save the offset, delay and jitter. Note the jitter must not
3368 	 * be less than the precision.
3369 	 */
3370 	if (m == 0) {
3371 		clock_select();
3372 		return;
3373 	}
3374 	etemp = fabs(peer->offset - peer->filter_offset[k]);
3375 	peer->offset = peer->filter_offset[k];
3376 	peer->delay = peer->filter_delay[k];
3377 	if (m > 1)
3378 		peer->jitter /= m - 1;
3379 	peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
3380 
3381 	/*
3382 	 * If the the new sample and the current sample are both valid
3383 	 * and the difference between their offsets exceeds CLOCK_SGATE
3384 	 * (3) times the jitter and the interval between them is less
3385 	 * than twice the host poll interval, consider the new sample
3386 	 * a popcorn spike and ignore it.
3387 	 */
3388 	if (   peer->disp < sys_maxdist
3389 	    && peer->filter_disp[k] < sys_maxdist
3390 	    && etemp > CLOCK_SGATE * peer->jitter
3391 	    && peer->filter_epoch[k] - peer->epoch
3392 	       < 2. * ULOGTOD(peer->hpoll)) {
3393 		snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
3394 		report_event(PEVNT_POPCORN, peer, tbuf);
3395 		return;
3396 	}
3397 
3398 	/*
3399 	 * A new minimum sample is useful only if it is later than the
3400 	 * last one used. In this design the maximum lifetime of any
3401 	 * sample is not greater than eight times the poll interval, so
3402 	 * the maximum interval between minimum samples is eight
3403 	 * packets.
3404 	 */
3405 	if (peer->filter_epoch[k] <= peer->epoch) {
3406 	DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
3407 		    peer->filter_epoch[k]));
3408 		return;
3409 	}
3410 	peer->epoch = peer->filter_epoch[k];
3411 
3412 	/*
3413 	 * The mitigated sample statistics are saved for later
3414 	 * processing. If not synchronized or not in a burst, tickle the
3415 	 * clock select algorithm.
3416 	 */
3417 	record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
3418 	    peer->offset, peer->delay, peer->disp, peer->jitter);
3419 	DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
3420 		    m, peer->offset, peer->delay, peer->disp,
3421 		    peer->jitter));
3422 	if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
3423 		clock_select();
3424 }
3425 
3426 
3427 /*
3428  * clock_select - find the pick-of-the-litter clock
3429  *
3430  * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
3431  * be enabled, even if declared falseticker, (2) only the prefer peer
3432  * can be selected as the system peer, (3) if the external source is
3433  * down, the system leap bits are set to 11 and the stratum set to
3434  * infinity.
3435  */
3436 void
clock_select(void)3437 clock_select(void)
3438 {
3439 	struct peer *peer;
3440 	int	i, j, k, n;
3441 	int	nlist, nl2;
3442 	int	allow;
3443 	int	speer;
3444 	double	d, e, f, g;
3445 	double	high, low;
3446 	double	speermet;
3447 	double	lastresort_dist = MAXDISPERSE;
3448 	double	orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
3449 	struct endpoint endp;
3450 	struct peer *osys_peer;
3451 	struct peer *sys_prefer = NULL;	/* prefer peer */
3452 	struct peer *typesystem = NULL;
3453 	struct peer *typelastresort = NULL;
3454 	struct peer *typeorphan = NULL;
3455 #ifdef REFCLOCK
3456 	struct peer *typeacts = NULL;
3457 	struct peer *typelocal = NULL;
3458 	struct peer *typepps = NULL;
3459 #endif /* REFCLOCK */
3460 	static struct endpoint *endpoint = NULL;
3461 	static int *indx = NULL;
3462 	static peer_select *peers = NULL;
3463 	static u_int endpoint_size = 0;
3464 	static u_int peers_size = 0;
3465 	static u_int indx_size = 0;
3466 	size_t octets;
3467 
3468 	/*
3469 	 * Initialize and create endpoint, index and peer lists big
3470 	 * enough to handle all associations.
3471 	 */
3472 	osys_peer = sys_peer;
3473 	sys_survivors = 0;
3474 #ifdef LOCKCLOCK
3475 	set_sys_leap(LEAP_NOTINSYNC);
3476 	sys_stratum = STRATUM_UNSPEC;
3477 	memcpy(&sys_refid, "DOWN", 4);
3478 #endif /* LOCKCLOCK */
3479 
3480 	/*
3481 	 * Allocate dynamic space depending on the number of
3482 	 * associations.
3483 	 */
3484 	nlist = 1;
3485 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3486 		nlist++;
3487 	endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
3488 	peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
3489 	indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
3490 	octets = endpoint_size + peers_size + indx_size;
3491 	endpoint = erealloc(endpoint, octets);
3492 	peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
3493 	indx = INC_ALIGNED_PTR(peers, peers_size);
3494 
3495 	/*
3496 	 * Initially, we populate the island with all the rifraff peers
3497 	 * that happen to be lying around. Those with seriously
3498 	 * defective clocks are immediately booted off the island. Then,
3499 	 * the falsetickers are culled and put to sea. The truechimers
3500 	 * remaining are subject to repeated rounds where the most
3501 	 * unpopular at each round is kicked off. When the population
3502 	 * has dwindled to sys_minclock, the survivors split a million
3503 	 * bucks and collectively crank the chimes.
3504 	 */
3505 	nlist = nl2 = 0;	/* none yet */
3506 	for (peer = peer_list; peer != NULL; peer = peer->p_link) {
3507 		peer->new_status = CTL_PST_SEL_REJECT;
3508 
3509 		/*
3510 		 * Leave the island immediately if the peer is
3511 		 * unfit to synchronize.
3512 		 */
3513 		if (peer_unfit(peer)) {
3514 			continue;
3515 		}
3516 
3517 		/*
3518 		 * If we have never been synchronised, look for any peer
3519 		 * which has ever been synchronised and pick the one which
3520 		 * has the lowest root distance. This can be used as a last
3521 		 * resort if all else fails. Once we get an initial sync
3522 		 * with this peer, sys_reftime gets set and so this
3523 		 * function becomes disabled.
3524 		 */
3525 		if (L_ISZERO(&sys_reftime)) {
3526 			d = root_distance(peer);
3527 			if (!L_ISZERO(&peer->reftime) && d < lastresort_dist) {
3528 				typelastresort = peer;
3529 				lastresort_dist = d;
3530 			}
3531 		}
3532 
3533 		/*
3534 		 * If this peer is an orphan parent, elect the
3535 		 * one with the lowest metric defined as the
3536 		 * IPv4 address or the first 64 bits of the
3537 		 * hashed IPv6 address.  To ensure convergence
3538 		 * on the same selected orphan, consider as
3539 		 * well that this system may have the lowest
3540 		 * metric and be the orphan parent.  If this
3541 		 * system wins, sys_peer will be NULL to trigger
3542 		 * orphan mode in timer().
3543 		 */
3544 		if (peer->stratum == sys_orphan) {
3545 			u_int32	localmet;
3546 			u_int32 peermet;
3547 
3548 			if (peer->dstadr != NULL)
3549 				localmet = ntohl(peer->dstadr->addr_refid);
3550 			else
3551 				localmet = U_INT32_MAX;
3552 			peermet = ntohl(addr2refid(&peer->srcadr));
3553 			if (peermet < localmet && peermet < orphmet) {
3554 				typeorphan = peer;
3555 				orphmet = peermet;
3556 			}
3557 			continue;
3558 		}
3559 
3560 		/*
3561 		 * If this peer could have the orphan parent
3562 		 * as a synchronization ancestor, exclude it
3563 		 * from selection to avoid forming a
3564 		 * synchronization loop within the orphan mesh,
3565 		 * triggering stratum climb to infinity
3566 		 * instability.  Peers at stratum higher than
3567 		 * the orphan stratum could have the orphan
3568 		 * parent in ancestry so are excluded.
3569 		 * See http://bugs.ntp.org/2050
3570 		 */
3571 		if (peer->stratum > sys_orphan) {
3572 			continue;
3573 		}
3574 #ifdef REFCLOCK
3575 		/*
3576 		 * The following are special cases. We deal
3577 		 * with them later.
3578 		 */
3579 		if (!(peer->flags & FLAG_PREFER)) {
3580 			switch (peer->refclktype) {
3581 			case REFCLK_LOCALCLOCK:
3582 				if (   current_time > orphwait
3583 				    && typelocal == NULL)
3584 					typelocal = peer;
3585 				continue;
3586 
3587 			case REFCLK_ACTS:
3588 				if (   current_time > orphwait
3589 				    && typeacts == NULL)
3590 					typeacts = peer;
3591 				continue;
3592 			}
3593 		}
3594 #endif /* REFCLOCK */
3595 
3596 		/*
3597 		 * If we get this far, the peer can stay on the
3598 		 * island, but does not yet have the immunity
3599 		 * idol.
3600 		 */
3601 		peer->new_status = CTL_PST_SEL_SANE;
3602 		f = root_distance(peer);
3603 		peers[nlist].peer = peer;
3604 		peers[nlist].error = peer->jitter;
3605 		peers[nlist].synch = f;
3606 		nlist++;
3607 
3608 		/*
3609 		 * Insert each interval endpoint on the unsorted
3610 		 * endpoint[] list.
3611 		 */
3612 		e = peer->offset;
3613 		endpoint[nl2].type = -1;	/* lower end */
3614 		endpoint[nl2].val = e - f;
3615 		nl2++;
3616 		endpoint[nl2].type = 1;		/* upper end */
3617 		endpoint[nl2].val = e + f;
3618 		nl2++;
3619 	}
3620 	/*
3621 	 * Construct sorted indx[] of endpoint[] indexes ordered by
3622 	 * offset.
3623 	 */
3624 	for (i = 0; i < nl2; i++)
3625 		indx[i] = i;
3626 	for (i = 0; i < nl2; i++) {
3627 		endp = endpoint[indx[i]];
3628 		e = endp.val;
3629 		k = i;
3630 		for (j = i + 1; j < nl2; j++) {
3631 			endp = endpoint[indx[j]];
3632 			if (endp.val < e) {
3633 				e = endp.val;
3634 				k = j;
3635 			}
3636 		}
3637 		if (k != i) {
3638 			j = indx[k];
3639 			indx[k] = indx[i];
3640 			indx[i] = j;
3641 		}
3642 	}
3643 	for (i = 0; i < nl2; i++)
3644 		DPRINTF(3, ("select: endpoint %2d %.6f\n",
3645 			endpoint[indx[i]].type, endpoint[indx[i]].val));
3646 
3647 	/*
3648 	 * This is the actual algorithm that cleaves the truechimers
3649 	 * from the falsetickers. The original algorithm was described
3650 	 * in Keith Marzullo's dissertation, but has been modified for
3651 	 * better accuracy.
3652 	 *
3653 	 * Briefly put, we first assume there are no falsetickers, then
3654 	 * scan the candidate list first from the low end upwards and
3655 	 * then from the high end downwards. The scans stop when the
3656 	 * number of intersections equals the number of candidates less
3657 	 * the number of falsetickers. If this doesn't happen for a
3658 	 * given number of falsetickers, we bump the number of
3659 	 * falsetickers and try again. If the number of falsetickers
3660 	 * becomes equal to or greater than half the number of
3661 	 * candidates, the Albanians have won the Byzantine wars and
3662 	 * correct synchronization is not possible.
3663 	 *
3664 	 * Here, nlist is the number of candidates and allow is the
3665 	 * number of falsetickers. Upon exit, the truechimers are the
3666 	 * survivors with offsets not less than low and not greater than
3667 	 * high. There may be none of them.
3668 	 */
3669 	low = 1e9;
3670 	high = -1e9;
3671 	for (allow = 0; 2 * allow < nlist; allow++) {
3672 
3673 		/*
3674 		 * Bound the interval (low, high) as the smallest
3675 		 * interval containing points from the most sources.
3676 		 */
3677 		n = 0;
3678 		for (i = 0; i < nl2; i++) {
3679 			low = endpoint[indx[i]].val;
3680 			n -= endpoint[indx[i]].type;
3681 			if (n >= nlist - allow)
3682 				break;
3683 		}
3684 		n = 0;
3685 		for (j = nl2 - 1; j >= 0; j--) {
3686 			high = endpoint[indx[j]].val;
3687 			n += endpoint[indx[j]].type;
3688 			if (n >= nlist - allow)
3689 				break;
3690 		}
3691 
3692 		/*
3693 		 * If an interval containing truechimers is found, stop.
3694 		 * If not, increase the number of falsetickers and go
3695 		 * around again.
3696 		 */
3697 		if (high > low)
3698 			break;
3699 	}
3700 
3701 	/*
3702 	 * Clustering algorithm. Whittle candidate list of falsetickers,
3703 	 * who leave the island immediately. The TRUE peer is always a
3704 	 * truechimer. We must leave at least one peer to collect the
3705 	 * million bucks.
3706 	 *
3707 	 * We assert the correct time is contained in the interval, but
3708 	 * the best offset estimate for the interval might not be
3709 	 * contained in the interval. For this purpose, a truechimer is
3710 	 * defined as the midpoint of an interval that overlaps the
3711 	 * intersection interval.
3712 	 */
3713 	j = 0;
3714 	for (i = 0; i < nlist; i++) {
3715 		double	h;
3716 
3717 		peer = peers[i].peer;
3718 		h = peers[i].synch;
3719 		if ((   high <= low
3720 		     || peer->offset + h < low
3721 		     || peer->offset - h > high
3722 		    ) && !(peer->flags & FLAG_TRUE))
3723 			continue;
3724 
3725 #ifdef REFCLOCK
3726 		/*
3727 		 * Eligible PPS peers must survive the intersection
3728 		 * algorithm. Use the first one found, but don't
3729 		 * include any of them in the cluster population.
3730 		 */
3731 		if (peer->flags & FLAG_PPS) {
3732 			if (typepps == NULL)
3733 				typepps = peer;
3734 			if (!(peer->flags & FLAG_TSTAMP_PPS))
3735 				continue;
3736 		}
3737 #endif /* REFCLOCK */
3738 
3739 		if (j != i)
3740 			peers[j] = peers[i];
3741 		j++;
3742 	}
3743 	nlist = j;
3744 
3745 	/*
3746 	 * If no survivors remain at this point, check if the modem
3747 	 * driver, local driver or orphan parent in that order. If so,
3748 	 * nominate the first one found as the only survivor.
3749 	 * Otherwise, give up and leave the island to the rats.
3750 	 */
3751 	if (nlist == 0) {
3752 		peers[0].error = 0;
3753 		peers[0].synch = sys_mindisp;
3754 #ifdef REFCLOCK
3755 		if (typeacts != NULL) {
3756 			peers[0].peer = typeacts;
3757 			nlist = 1;
3758 		} else if (typelocal != NULL) {
3759 			peers[0].peer = typelocal;
3760 			nlist = 1;
3761 		} else
3762 #endif /* REFCLOCK */
3763 		if (typeorphan != NULL) {
3764 			peers[0].peer = typeorphan;
3765 			nlist = 1;
3766 		} else if (typelastresort != NULL) {
3767 			peers[0].peer = typelastresort;
3768 			nlist = 1;
3769 		}
3770 	}
3771 
3772 	/*
3773 	 * Mark the candidates at this point as truechimers.
3774 	 */
3775 	for (i = 0; i < nlist; i++) {
3776 		peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3777 		DPRINTF(2, ("select: survivor %s %f\n",
3778 			stoa(&peers[i].peer->srcadr), peers[i].synch));
3779 	}
3780 
3781 	/*
3782 	 * Now, vote outliers off the island by select jitter weighted
3783 	 * by root distance. Continue voting as long as there are more
3784 	 * than sys_minclock survivors and the select jitter of the peer
3785 	 * with the worst metric is greater than the minimum peer
3786 	 * jitter. Stop if we are about to discard a TRUE or PREFER
3787 	 * peer, who of course have the immunity idol.
3788 	 */
3789 	while (1) {
3790 		d = 1e9;
3791 		e = -1e9;
3792 		g = 0;
3793 		k = 0;
3794 		for (i = 0; i < nlist; i++) {
3795 			if (peers[i].error < d)
3796 				d = peers[i].error;
3797 			peers[i].seljit = 0;
3798 			if (nlist > 1) {
3799 				f = 0;
3800 				for (j = 0; j < nlist; j++)
3801 					f += DIFF(peers[j].peer->offset,
3802 					    peers[i].peer->offset);
3803 				peers[i].seljit = SQRT(f / (nlist - 1));
3804 			}
3805 			if (peers[i].seljit * peers[i].synch > e) {
3806 				g = peers[i].seljit;
3807 				e = peers[i].seljit * peers[i].synch;
3808 				k = i;
3809 			}
3810 		}
3811 		g = max(g, LOGTOD(sys_precision));
3812 		if (   nlist <= max(1, sys_minclock)
3813 		    || g <= d
3814 		    || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3815 			break;
3816 
3817 		DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3818 			ntoa(&peers[k].peer->srcadr), g, d));
3819 		if (nlist > sys_maxclock)
3820 			peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3821 		for (j = k + 1; j < nlist; j++)
3822 			peers[j - 1] = peers[j];
3823 		nlist--;
3824 	}
3825 
3826 	/*
3827 	 * What remains is a list usually not greater than sys_minclock
3828 	 * peers. Note that unsynchronized peers cannot survive this
3829 	 * far.  Count and mark these survivors.
3830 	 *
3831 	 * While at it, count the number of leap warning bits found.
3832 	 * This will be used later to vote the system leap warning bit.
3833 	 * If a leap warning bit is found on a reference clock, the vote
3834 	 * is always won.
3835 	 *
3836 	 * Choose the system peer using a hybrid metric composed of the
3837 	 * selection jitter scaled by the root distance augmented by
3838 	 * stratum scaled by sys_mindisp (.001 by default). The goal of
3839 	 * the small stratum factor is to avoid clockhop between a
3840 	 * reference clock and a network peer which has a refclock and
3841 	 * is using an older ntpd, which does not floor sys_rootdisp at
3842 	 * sys_mindisp.
3843 	 *
3844 	 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3845 	 * in selecting the system peer, using a weight of 1 second of
3846 	 * additional root distance per stratum.  This heavy bias is no
3847 	 * longer appropriate, as the scaled root distance provides a
3848 	 * more rational metric carrying the cumulative error budget.
3849 	 */
3850 	e = 1e9;
3851 	speer = 0;
3852 	leap_vote_ins = 0;
3853 	leap_vote_del = 0;
3854 	for (i = 0; i < nlist; i++) {
3855 		peer = peers[i].peer;
3856 		peer->unreach = 0;
3857 		peer->new_status = CTL_PST_SEL_SYNCCAND;
3858 		sys_survivors++;
3859 		if (peer->leap == LEAP_ADDSECOND) {
3860 			if (peer->flags & FLAG_REFCLOCK)
3861 				leap_vote_ins = nlist;
3862 			else if (leap_vote_ins < nlist)
3863 				leap_vote_ins++;
3864 		}
3865 		if (peer->leap == LEAP_DELSECOND) {
3866 			if (peer->flags & FLAG_REFCLOCK)
3867 				leap_vote_del = nlist;
3868 			else if (leap_vote_del < nlist)
3869 				leap_vote_del++;
3870 		}
3871 		if (peer->flags & FLAG_PREFER)
3872 			sys_prefer = peer;
3873 		speermet = peers[i].seljit * peers[i].synch +
3874 		    peer->stratum * sys_mindisp;
3875 		if (speermet < e) {
3876 			e = speermet;
3877 			speer = i;
3878 		}
3879 	}
3880 
3881 	/*
3882 	 * Unless there are at least sys_misane survivors, leave the
3883 	 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3884 	 * use the selected survivor speer. However, if the current
3885 	 * system peer is not speer, stay with the current system peer
3886 	 * as long as it doesn't get too old or too ugly.
3887 	 */
3888 	if (nlist > 0 && nlist >= sys_minsane) {
3889 		double	x;
3890 
3891 		typesystem = peers[speer].peer;
3892 		if (osys_peer == NULL || osys_peer == typesystem) {
3893 			sys_clockhop = 0;
3894 		} else if ((x = fabs(typesystem->offset -
3895 		    osys_peer->offset)) < sys_mindisp) {
3896 			if (sys_clockhop == 0)
3897 				sys_clockhop = sys_mindisp;
3898 			else
3899 				sys_clockhop *= .5;
3900 			DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3901 				j, x, sys_clockhop));
3902 			if (fabs(x) < sys_clockhop)
3903 				typesystem = osys_peer;
3904 			else
3905 				sys_clockhop = 0;
3906 		} else {
3907 			sys_clockhop = 0;
3908 		}
3909 	}
3910 
3911 	/*
3912 	 * Mitigation rules of the game. We have the pick of the
3913 	 * litter in typesystem if any survivors are left. If
3914 	 * there is a prefer peer, use its offset and jitter.
3915 	 * Otherwise, use the combined offset and jitter of all kitters.
3916 	 */
3917 	if (typesystem != NULL) {
3918 		if (sys_prefer == NULL) {
3919 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3920 			clock_combine(peers, sys_survivors, speer);
3921 		} else {
3922 			typesystem = sys_prefer;
3923 			sys_clockhop = 0;
3924 			typesystem->new_status = CTL_PST_SEL_SYSPEER;
3925 			sys_offset = typesystem->offset;
3926 			sys_jitter = typesystem->jitter;
3927 		}
3928 		DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3929 			sys_offset, sys_jitter));
3930 	}
3931 #ifdef REFCLOCK
3932 	/*
3933 	 * If a PPS driver is lit and the combined offset is less than
3934 	 * 0.4 s, select the driver as the PPS peer and use its offset
3935 	 * and jitter. However, if this is the atom driver, use it only
3936 	 * if there is a prefer peer or there are no survivors and none
3937 	 * are required.
3938 	 */
3939 	if (   typepps != NULL
3940 	    && fabs(sys_offset) < 0.4
3941 	    && (   typepps->refclktype != REFCLK_ATOM_PPS
3942 		|| (   typepps->refclktype == REFCLK_ATOM_PPS
3943 		    && (   sys_prefer != NULL
3944 			|| (typesystem == NULL && sys_minsane == 0))))) {
3945 		typesystem = typepps;
3946 		sys_clockhop = 0;
3947 		typesystem->new_status = CTL_PST_SEL_PPS;
3948 		sys_offset = typesystem->offset;
3949 		sys_jitter = typesystem->jitter;
3950 		DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3951 			sys_offset, sys_jitter));
3952 	}
3953 #endif /* REFCLOCK */
3954 
3955 	/*
3956 	 * If there are no survivors at this point, there is no
3957 	 * system peer. If so and this is an old update, keep the
3958 	 * current statistics, but do not update the clock.
3959 	 */
3960 	if (typesystem == NULL) {
3961 		if (osys_peer != NULL) {
3962 			orphwait = current_time + sys_orphwait;
3963 			report_event(EVNT_NOPEER, NULL, NULL);
3964 		}
3965 		sys_peer = NULL;
3966 		for (peer = peer_list; peer != NULL; peer = peer->p_link)
3967 			peer->status = peer->new_status;
3968 		return;
3969 	}
3970 
3971 	/*
3972 	 * Do not use old data, as this may mess up the clock discipline
3973 	 * stability.
3974 	 */
3975 	if (typesystem->epoch <= sys_epoch)
3976 		return;
3977 
3978 	/*
3979 	 * We have found the alpha male. Wind the clock.
3980 	 */
3981 	if (osys_peer != typesystem)
3982 		report_event(PEVNT_NEWPEER, typesystem, NULL);
3983 	for (peer = peer_list; peer != NULL; peer = peer->p_link)
3984 		peer->status = peer->new_status;
3985 	clock_update(typesystem);
3986 }
3987 
3988 
3989 static void
clock_combine(peer_select * peers,int npeers,int syspeer)3990 clock_combine(
3991 	peer_select *	peers,	/* survivor list */
3992 	int		npeers,	/* number of survivors */
3993 	int		syspeer	/* index of sys.peer */
3994 	)
3995 {
3996 	int	i;
3997 	double	x, y, z, w;
3998 
3999 	y = z = w = 0;
4000 	for (i = 0; i < npeers; i++) {
4001 		x = 1. / peers[i].synch;
4002 		y += x;
4003 		z += x * peers[i].peer->offset;
4004 		w += x * DIFF(peers[i].peer->offset,
4005 		    peers[syspeer].peer->offset);
4006 	}
4007 	sys_offset = z / y;
4008 	sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
4009 }
4010 
4011 
4012 /*
4013  * root_distance - compute synchronization distance from peer to root
4014  */
4015 static double
root_distance(struct peer * peer)4016 root_distance(
4017 	struct peer *peer	/* peer structure pointer */
4018 	)
4019 {
4020 	double	dtemp;
4021 
4022 	/*
4023 	 * Root Distance (LAMBDA) is defined as:
4024 	 * (delta + DELTA)/2 + epsilon + EPSILON + D
4025 	 *
4026 	 * where:
4027 	 *  delta   is the round-trip delay
4028 	 *  DELTA   is the root delay
4029 	 *  epsilon is the peer dispersion
4030 	 *	    + (15 usec each second)
4031 	 *  EPSILON is the root dispersion
4032 	 *  D       is sys_jitter
4033 	 *
4034 	 * NB: Think hard about why we are using these values, and what
4035 	 * the alternatives are, and the various pros/cons.
4036 	 *
4037 	 * DLM thinks these are probably the best choices from any of the
4038 	 * other worse choices.
4039 	 */
4040 	dtemp = (peer->delay + peer->rootdelay) / 2
4041 		+ peer->disp
4042 		  + clock_phi * (current_time - peer->update)
4043 		+ peer->rootdisp
4044 		+ peer->jitter;
4045 	/*
4046 	 * Careful squeak here. The value returned must be greater than
4047 	 * the minimum root dispersion in order to avoid clockhop with
4048 	 * highly precise reference clocks. Note that the root distance
4049 	 * cannot exceed the sys_maxdist, as this is the cutoff by the
4050 	 * selection algorithm.
4051 	 */
4052 	if (dtemp < sys_mindisp)
4053 		dtemp = sys_mindisp;
4054 	return (dtemp);
4055 }
4056 
4057 
4058 /*
4059  * peer_xmit - send packet for persistent association.
4060  */
4061 static void
peer_xmit(struct peer * peer)4062 peer_xmit(
4063 	struct peer *peer	/* peer structure pointer */
4064 	)
4065 {
4066 	struct pkt xpkt;	/* transmit packet */
4067 	size_t	sendlen, authlen;
4068 	keyid_t	xkeyid = 0;	/* transmit key ID */
4069 	l_fp	xmt_tx, xmt_ty;
4070 
4071 	if (!peer->dstadr)	/* drop peers without interface */
4072 		return;
4073 
4074 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
4075 	    peer->hmode);
4076 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4077 	xpkt.ppoll = peer->hpoll;
4078 	xpkt.precision = sys_precision;
4079 	xpkt.refid = sys_refid;
4080 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4081 	xpkt.rootdisp =  HTONS_FP(DTOUFP(sys_rootdisp));
4082 	/* Use sys_reftime for peer exchanges */
4083 	HTONL_FP(&sys_reftime, &xpkt.reftime);
4084 	HTONL_FP(&peer->rec, &xpkt.org);
4085 	HTONL_FP(&peer->dst, &xpkt.rec);
4086 
4087 	/*
4088 	 * If the received packet contains a MAC, the transmitted packet
4089 	 * is authenticated and contains a MAC. If not, the transmitted
4090 	 * packet is not authenticated.
4091 	 *
4092 	 * It is most important when autokey is in use that the local
4093 	 * interface IP address be known before the first packet is
4094 	 * sent. Otherwise, it is not possible to compute a correct MAC
4095 	 * the recipient will accept. Thus, the I/O semantics have to do
4096 	 * a little more work. In particular, the wildcard interface
4097 	 * might not be usable.
4098 	 */
4099 	sendlen = LEN_PKT_NOMAC;
4100 	if (
4101 #ifdef AUTOKEY
4102 	    !(peer->flags & FLAG_SKEY) &&
4103 #endif	/* !AUTOKEY */
4104 	    peer->keyid == 0) {
4105 
4106 		/*
4107 		 * Transmit a-priori timestamps
4108 		 */
4109 		get_systime(&xmt_tx);
4110 		if (peer->flip == 0) {	/* basic mode */
4111 			peer->aorg = xmt_tx;
4112 			HTONL_FP(&xmt_tx, &xpkt.xmt);
4113 		} else {		/* interleaved modes */
4114 			if (peer->hmode == MODE_BROADCAST) { /* bcst */
4115 				HTONL_FP(&xmt_tx, &xpkt.xmt);
4116 				if (peer->flip > 0)
4117 					HTONL_FP(&peer->borg,
4118 					    &xpkt.org);
4119 				else
4120 					HTONL_FP(&peer->aorg,
4121 					    &xpkt.org);
4122 			} else {	/* symmetric */
4123 				if (peer->flip > 0)
4124 					HTONL_FP(&peer->borg,
4125 					    &xpkt.xmt);
4126 				else
4127 					HTONL_FP(&peer->aorg,
4128 					    &xpkt.xmt);
4129 			}
4130 		}
4131 		peer->t21_bytes = sendlen;
4132 		sendpkt(&peer->srcadr, peer->dstadr,
4133 			sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
4134 			&xpkt, sendlen);
4135 		peer->sent++;
4136 		peer->throttle += (1 << peer->minpoll) - 2;
4137 
4138 		/*
4139 		 * Capture a-posteriori timestamps
4140 		 */
4141 		get_systime(&xmt_ty);
4142 		if (peer->flip != 0) {		/* interleaved modes */
4143 			if (peer->flip > 0)
4144 				peer->aorg = xmt_ty;
4145 			else
4146 				peer->borg = xmt_ty;
4147 			peer->flip = -peer->flip;
4148 		}
4149 		L_SUB(&xmt_ty, &xmt_tx);
4150 		LFPTOD(&xmt_ty, peer->xleave);
4151 		DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
4152 			    current_time,
4153 			    peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
4154 			    stoa(&peer->srcadr), peer->hmode, sendlen,
4155 			    xmt_tx.l_ui, xmt_tx.l_uf));
4156 		return;
4157 	}
4158 
4159 	/*
4160 	 * Authentication is enabled, so the transmitted packet must be
4161 	 * authenticated. If autokey is enabled, fuss with the various
4162 	 * modes; otherwise, symmetric key cryptography is used.
4163 	 */
4164 #ifdef AUTOKEY
4165 	if (peer->flags & FLAG_SKEY) {
4166 		struct exten *exten;	/* extension field */
4167 
4168 		/*
4169 		 * The Public Key Dance (PKD): Cryptographic credentials
4170 		 * are contained in extension fields, each including a
4171 		 * 4-octet length/code word followed by a 4-octet
4172 		 * association ID and optional additional data. Optional
4173 		 * data includes a 4-octet data length field followed by
4174 		 * the data itself. Request messages are sent from a
4175 		 * configured association; response messages can be sent
4176 		 * from a configured association or can take the fast
4177 		 * path without ever matching an association. Response
4178 		 * messages have the same code as the request, but have
4179 		 * a response bit and possibly an error bit set. In this
4180 		 * implementation, a message may contain no more than
4181 		 * one command and one or more responses.
4182 		 *
4183 		 * Cryptographic session keys include both a public and
4184 		 * a private componet. Request and response messages
4185 		 * using extension fields are always sent with the
4186 		 * private component set to zero. Packets without
4187 		 * extension fields indlude the private component when
4188 		 * the session key is generated.
4189 		 */
4190 		while (1) {
4191 
4192 			/*
4193 			 * Allocate and initialize a keylist if not
4194 			 * already done. Then, use the list in inverse
4195 			 * order, discarding keys once used. Keep the
4196 			 * latest key around until the next one, so
4197 			 * clients can use client/server packets to
4198 			 * compute propagation delay.
4199 			 *
4200 			 * Note that once a key is used from the list,
4201 			 * it is retained in the key cache until the
4202 			 * next key is used. This is to allow a client
4203 			 * to retrieve the encrypted session key
4204 			 * identifier to verify authenticity.
4205 			 *
4206 			 * If for some reason a key is no longer in the
4207 			 * key cache, a birthday has happened or the key
4208 			 * has expired, so the pseudo-random sequence is
4209 			 * broken. In that case, purge the keylist and
4210 			 * regenerate it.
4211 			 */
4212 			if (peer->keynumber == 0)
4213 				make_keylist(peer, peer->dstadr);
4214 			else
4215 				peer->keynumber--;
4216 			xkeyid = peer->keylist[peer->keynumber];
4217 			if (authistrusted(xkeyid))
4218 				break;
4219 			else
4220 				key_expire(peer);
4221 		}
4222 		peer->keyid = xkeyid;
4223 		exten = NULL;
4224 		switch (peer->hmode) {
4225 
4226 		/*
4227 		 * In broadcast server mode the autokey values are
4228 		 * required by the broadcast clients. Push them when a
4229 		 * new keylist is generated; otherwise, push the
4230 		 * association message so the client can request them at
4231 		 * other times.
4232 		 */
4233 		case MODE_BROADCAST:
4234 			if (peer->flags & FLAG_ASSOC)
4235 				exten = crypto_args(peer, CRYPTO_AUTO |
4236 				    CRYPTO_RESP, peer->associd, NULL);
4237 			else
4238 				exten = crypto_args(peer, CRYPTO_ASSOC |
4239 				    CRYPTO_RESP, peer->associd, NULL);
4240 			break;
4241 
4242 		/*
4243 		 * In symmetric modes the parameter, certificate,
4244 		 * identity, cookie and autokey exchanges are
4245 		 * required. The leapsecond exchange is optional. But, a
4246 		 * peer will not believe the other peer until the other
4247 		 * peer has synchronized, so the certificate exchange
4248 		 * might loop until then. If a peer finds a broken
4249 		 * autokey sequence, it uses the autokey exchange to
4250 		 * retrieve the autokey values. In any case, if a new
4251 		 * keylist is generated, the autokey values are pushed.
4252 		 */
4253 		case MODE_ACTIVE:
4254 		case MODE_PASSIVE:
4255 
4256 			/*
4257 			 * Parameter, certificate and identity.
4258 			 */
4259 			if (!peer->crypto)
4260 				exten = crypto_args(peer, CRYPTO_ASSOC,
4261 				    peer->associd, hostval.ptr);
4262 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4263 				exten = crypto_args(peer, CRYPTO_CERT,
4264 				    peer->associd, peer->issuer);
4265 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4266 				exten = crypto_args(peer,
4267 				    crypto_ident(peer), peer->associd,
4268 				    NULL);
4269 
4270 			/*
4271 			 * Cookie and autokey. We request the cookie
4272 			 * only when the this peer and the other peer
4273 			 * are synchronized. But, this peer needs the
4274 			 * autokey values when the cookie is zero. Any
4275 			 * time we regenerate the key list, we offer the
4276 			 * autokey values without being asked. If for
4277 			 * some reason either peer finds a broken
4278 			 * autokey sequence, the autokey exchange is
4279 			 * used to retrieve the autokey values.
4280 			 */
4281 			else if (   sys_leap != LEAP_NOTINSYNC
4282 				 && peer->leap != LEAP_NOTINSYNC
4283 				 && !(peer->crypto & CRYPTO_FLAG_COOK))
4284 				exten = crypto_args(peer, CRYPTO_COOK,
4285 				    peer->associd, NULL);
4286 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4287 				exten = crypto_args(peer, CRYPTO_AUTO,
4288 				    peer->associd, NULL);
4289 			else if (   peer->flags & FLAG_ASSOC
4290 				 && peer->crypto & CRYPTO_FLAG_SIGN)
4291 				exten = crypto_args(peer, CRYPTO_AUTO |
4292 				    CRYPTO_RESP, peer->assoc, NULL);
4293 
4294 			/*
4295 			 * Wait for clock sync, then sign the
4296 			 * certificate and retrieve the leapsecond
4297 			 * values.
4298 			 */
4299 			else if (sys_leap == LEAP_NOTINSYNC)
4300 				break;
4301 
4302 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4303 				exten = crypto_args(peer, CRYPTO_SIGN,
4304 				    peer->associd, hostval.ptr);
4305 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4306 				exten = crypto_args(peer, CRYPTO_LEAP,
4307 				    peer->associd, NULL);
4308 			break;
4309 
4310 		/*
4311 		 * In client mode the parameter, certificate, identity,
4312 		 * cookie and sign exchanges are required. The
4313 		 * leapsecond exchange is optional. If broadcast client
4314 		 * mode the same exchanges are required, except that the
4315 		 * autokey exchange is substitutes for the cookie
4316 		 * exchange, since the cookie is always zero. If the
4317 		 * broadcast client finds a broken autokey sequence, it
4318 		 * uses the autokey exchange to retrieve the autokey
4319 		 * values.
4320 		 */
4321 		case MODE_CLIENT:
4322 
4323 			/*
4324 			 * Parameter, certificate and identity.
4325 			 */
4326 			if (!peer->crypto)
4327 				exten = crypto_args(peer, CRYPTO_ASSOC,
4328 				    peer->associd, hostval.ptr);
4329 			else if (!(peer->crypto & CRYPTO_FLAG_CERT))
4330 				exten = crypto_args(peer, CRYPTO_CERT,
4331 				    peer->associd, peer->issuer);
4332 			else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
4333 				exten = crypto_args(peer,
4334 				    crypto_ident(peer), peer->associd,
4335 				    NULL);
4336 
4337 			/*
4338 			 * Cookie and autokey. These are requests, but
4339 			 * we use the peer association ID with autokey
4340 			 * rather than our own.
4341 			 */
4342 			else if (!(peer->crypto & CRYPTO_FLAG_COOK))
4343 				exten = crypto_args(peer, CRYPTO_COOK,
4344 				    peer->associd, NULL);
4345 			else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
4346 				exten = crypto_args(peer, CRYPTO_AUTO,
4347 				    peer->assoc, NULL);
4348 
4349 			/*
4350 			 * Wait for clock sync, then sign the
4351 			 * certificate and retrieve the leapsecond
4352 			 * values.
4353 			 */
4354 			else if (sys_leap == LEAP_NOTINSYNC)
4355 				break;
4356 
4357 			else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
4358 				exten = crypto_args(peer, CRYPTO_SIGN,
4359 				    peer->associd, hostval.ptr);
4360 			else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
4361 				exten = crypto_args(peer, CRYPTO_LEAP,
4362 				    peer->associd, NULL);
4363 			break;
4364 		}
4365 
4366 		/*
4367 		 * Add a queued extension field if present. This is
4368 		 * always a request message, so the reply ID is already
4369 		 * in the message. If an error occurs, the error bit is
4370 		 * lit in the response.
4371 		 */
4372 		if (peer->cmmd != NULL) {
4373 			u_int32 temp32;
4374 
4375 			temp32 = CRYPTO_RESP;
4376 			peer->cmmd->opcode |= htonl(temp32);
4377 			sendlen += crypto_xmit(peer, &xpkt, NULL,
4378 			    sendlen, peer->cmmd, 0);
4379 			free(peer->cmmd);
4380 			peer->cmmd = NULL;
4381 		}
4382 
4383 		/*
4384 		 * Add an extension field created above. All but the
4385 		 * autokey response message are request messages.
4386 		 */
4387 		if (exten != NULL) {
4388 			if (exten->opcode != 0)
4389 				sendlen += crypto_xmit(peer, &xpkt,
4390 				    NULL, sendlen, exten, 0);
4391 			free(exten);
4392 		}
4393 
4394 		/*
4395 		 * Calculate the next session key. Since extension
4396 		 * fields are present, the cookie value is zero.
4397 		 */
4398 		if (sendlen > (int)LEN_PKT_NOMAC) {
4399 			session_key(&peer->dstadr->sin, &peer->srcadr,
4400 			    xkeyid, 0, 2);
4401 		}
4402 	}
4403 #endif	/* AUTOKEY */
4404 
4405 	/*
4406 	 * Transmit a-priori timestamps
4407 	 */
4408 	get_systime(&xmt_tx);
4409 	if (peer->flip == 0) {		/* basic mode */
4410 		peer->aorg = xmt_tx;
4411 		HTONL_FP(&xmt_tx, &xpkt.xmt);
4412 	} else {			/* interleaved modes */
4413 		if (peer->hmode == MODE_BROADCAST) { /* bcst */
4414 			HTONL_FP(&xmt_tx, &xpkt.xmt);
4415 			if (peer->flip > 0)
4416 				HTONL_FP(&peer->borg, &xpkt.org);
4417 			else
4418 				HTONL_FP(&peer->aorg, &xpkt.org);
4419 		} else {		/* symmetric */
4420 			if (peer->flip > 0)
4421 				HTONL_FP(&peer->borg, &xpkt.xmt);
4422 			else
4423 				HTONL_FP(&peer->aorg, &xpkt.xmt);
4424 		}
4425 	}
4426 	xkeyid = peer->keyid;
4427 	authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4428 	if (authlen == 0) {
4429 		report_event(PEVNT_AUTH, peer, "no key");
4430 		peer->flash |= TEST5;		/* auth error */
4431 		peer->badauth++;
4432 		return;
4433 	}
4434 	sendlen += authlen;
4435 #ifdef AUTOKEY
4436 	if (xkeyid > NTP_MAXKEY)
4437 		authtrust(xkeyid, 0);
4438 #endif	/* AUTOKEY */
4439 	if (sendlen > sizeof(xpkt)) {
4440 		msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
4441 		exit (-1);
4442 	}
4443 	peer->t21_bytes = sendlen;
4444 	sendpkt(&peer->srcadr, peer->dstadr,
4445 		sys_ttl[(peer->ttl >= sys_ttlmax) ? sys_ttlmax : peer->ttl],
4446 		&xpkt, sendlen);
4447 	peer->sent++;
4448 	peer->throttle += (1 << peer->minpoll) - 2;
4449 
4450 	/*
4451 	 * Capture a-posteriori timestamps
4452 	 */
4453 	get_systime(&xmt_ty);
4454 	if (peer->flip != 0) {			/* interleaved modes */
4455 		if (peer->flip > 0)
4456 			peer->aorg = xmt_ty;
4457 		else
4458 			peer->borg = xmt_ty;
4459 		peer->flip = -peer->flip;
4460 	}
4461 	L_SUB(&xmt_ty, &xmt_tx);
4462 	LFPTOD(&xmt_ty, peer->xleave);
4463 #ifdef AUTOKEY
4464 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
4465 		    current_time, latoa(peer->dstadr),
4466 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
4467 		    peer->keynumber));
4468 #else	/* !AUTOKEY follows */
4469 	DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu\n",
4470 		    current_time, peer->dstadr ?
4471 		    ntoa(&peer->dstadr->sin) : "-",
4472 		    ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
4473 #endif	/* !AUTOKEY */
4474 
4475 	return;
4476 }
4477 
4478 
4479 #ifdef LEAP_SMEAR
4480 
4481 static void
leap_smear_add_offs(l_fp * t,l_fp * t_recv)4482 leap_smear_add_offs(
4483 	l_fp *t,
4484 	l_fp *t_recv
4485 	)
4486 {
4487 
4488 	L_ADD(t, &leap_smear.offset);
4489 
4490 	/*
4491 	** XXX: Should the smear be added to the root dispersion?
4492 	*/
4493 
4494 	return;
4495 }
4496 
4497 #endif /* LEAP_SMEAR */
4498 
4499 
4500 /*
4501  * fast_xmit - Send packet for nonpersistent association. Note that
4502  * neither the source or destination can be a broadcast address.
4503  */
4504 static void
fast_xmit(struct recvbuf * rbufp,int xmode,keyid_t xkeyid,int flags)4505 fast_xmit(
4506 	struct recvbuf *rbufp,	/* receive packet pointer */
4507 	int	xmode,		/* receive mode */  /* XXX: HMS: really? */
4508 	keyid_t	xkeyid,		/* transmit key ID */
4509 	int	flags		/* restrict mask */
4510 	)
4511 {
4512 	struct pkt xpkt;	/* transmit packet structure */
4513 	struct pkt *rpkt;	/* receive packet structure */
4514 	l_fp	xmt_tx, xmt_ty;
4515 	size_t	sendlen;
4516 #ifdef AUTOKEY
4517 	u_int32	temp32;
4518 #endif
4519 
4520 	/*
4521 	 * Initialize transmit packet header fields from the receive
4522 	 * buffer provided. We leave the fields intact as received, but
4523 	 * set the peer poll at the maximum of the receive peer poll and
4524 	 * the system minimum poll (ntp_minpoll). This is for KoD rate
4525 	 * control and not strictly specification compliant, but doesn't
4526 	 * break anything.
4527 	 *
4528 	 * If the gazinta was from a multicast address, the gazoutta
4529 	 * must go out another way.
4530 	 */
4531 	rpkt = &rbufp->recv_pkt;
4532 	if (rbufp->dstadr->flags & INT_MCASTOPEN)
4533 		rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
4534 
4535 	/*
4536 	 * If this is a kiss-o'-death (KoD) packet, show leap
4537 	 * unsynchronized, stratum zero, reference ID the four-character
4538 	 * kiss code and (???) system root delay. Note we don't reveal
4539 	 * the local time, so these packets can't be used for
4540 	 * synchronization.
4541 	 */
4542 	if (flags & RES_KOD) {
4543 		sys_kodsent++;
4544 		xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
4545 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4546 		xpkt.stratum = STRATUM_PKT_UNSPEC;
4547 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4548 		xpkt.precision = rpkt->precision;
4549 		memcpy(&xpkt.refid, "RATE", 4);
4550 		xpkt.rootdelay = rpkt->rootdelay;
4551 		xpkt.rootdisp = rpkt->rootdisp;
4552 		xpkt.reftime = rpkt->reftime;
4553 		xpkt.org = rpkt->xmt;
4554 		xpkt.rec = rpkt->xmt;
4555 		xpkt.xmt = rpkt->xmt;
4556 
4557 	/*
4558 	 * This is a normal packet. Use the system variables.
4559 	 */
4560 	} else {
4561 		double this_rootdisp;
4562 		l_fp this_ref_time;
4563 
4564 #ifdef LEAP_SMEAR
4565 		/*
4566 		 * Make copies of the variables which can be affected by smearing.
4567 		 */
4568 		l_fp this_recv_time;
4569 #endif
4570 
4571 		/*
4572 		 * If we are inside the leap smear interval we add
4573 		 * the current smear offset to:
4574 		 * - the packet receive time,
4575 		 * - the packet transmit time,
4576 		 * - and eventually to the reftime to make sure the
4577 		 *   reftime isn't later than the transmit/receive times.
4578 		 */
4579 		xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
4580 		    PKT_VERSION(rpkt->li_vn_mode), xmode);
4581 
4582 		xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4583 		xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
4584 		xpkt.precision = sys_precision;
4585 		xpkt.refid = sys_refid;
4586 		xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4587 
4588 		/*
4589 		** Server Response Fuzzing
4590 		**
4591 		** Which values do we want to use for reftime and rootdisp?
4592 		*/
4593 
4594 		if (   MODE_SERVER == xmode
4595 		    && RES_SRVRSPFUZ & flags) {
4596 			if (current_time < p2_time) {
4597 				this_ref_time = p2_reftime;
4598 				this_rootdisp = p2_rootdisp;
4599 			} else if (current_time < prev_time) {
4600 				this_ref_time = prev_reftime;
4601 				this_rootdisp = prev_rootdisp;
4602 			} else {
4603 				this_ref_time = sys_reftime;
4604 				this_rootdisp = sys_rootdisp;
4605 			}
4606 
4607 			SRVRSP_FUZZ(this_ref_time);
4608 		} else {
4609 			this_ref_time = sys_reftime;
4610 			this_rootdisp = sys_rootdisp;
4611 		}
4612 
4613 		/*
4614 		** ROOT DISPERSION
4615 		*/
4616 
4617 		xpkt.rootdisp = HTONS_FP(DTOUFP(this_rootdisp));
4618 
4619 		/*
4620 		** REFTIME
4621 		*/
4622 
4623 #ifdef LEAP_SMEAR
4624 		if (leap_smear.in_progress) {
4625 			/* adjust the reftime by the same amount as the
4626 			 * leap smear, as we don't want to risk the
4627 			 * reftime being later than the transmit time.
4628 			 */
4629 			leap_smear_add_offs(&this_ref_time, NULL);
4630 		}
4631 #endif
4632 
4633 		HTONL_FP(&this_ref_time, &xpkt.reftime);
4634 
4635 		/*
4636 		** REFID
4637 		*/
4638 
4639 #ifdef LEAP_SMEAR
4640 		if (leap_smear.in_progress) {
4641 			xpkt.refid = convertLFPToRefID(leap_smear.offset);
4642 			DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
4643 				ntohl(xpkt.refid),
4644 				lfptoa(&leap_smear.offset, 8)
4645 				));
4646 		}
4647 #endif
4648 
4649 		/*
4650 		** ORIGIN
4651 		*/
4652 
4653 		xpkt.org = rpkt->xmt;
4654 
4655 		/*
4656 		** RECEIVE
4657 		*/
4658 #ifdef LEAP_SMEAR
4659 		this_recv_time = rbufp->recv_time;
4660 		if (leap_smear.in_progress)
4661 			leap_smear_add_offs(&this_recv_time, NULL);
4662 		HTONL_FP(&this_recv_time, &xpkt.rec);
4663 #else
4664 		HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4665 #endif
4666 
4667 		/*
4668 		** TRANSMIT
4669 		*/
4670 
4671 		get_systime(&xmt_tx);
4672 #ifdef LEAP_SMEAR
4673 		if (leap_smear.in_progress)
4674 			leap_smear_add_offs(&xmt_tx, &this_recv_time);
4675 #endif
4676 		HTONL_FP(&xmt_tx, &xpkt.xmt);
4677 	}
4678 
4679 #ifdef HAVE_NTP_SIGND
4680 	if (flags & RES_MSSNTP) {
4681 		send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4682 		return;
4683 	}
4684 #endif /* HAVE_NTP_SIGND */
4685 
4686 	/*
4687 	 * If the received packet contains a MAC, the transmitted packet
4688 	 * is authenticated and contains a MAC. If not, the transmitted
4689 	 * packet is not authenticated.
4690 	 */
4691 	sendlen = LEN_PKT_NOMAC;
4692 	if ((size_t)rbufp->recv_length == sendlen) {
4693 		sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4694 		    sendlen);
4695 		DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4696 			    current_time, stoa(&rbufp->dstadr->sin),
4697 			    stoa(&rbufp->recv_srcadr), xmode,
4698 			    (u_long)sendlen));
4699 		return;
4700 	}
4701 
4702 	/*
4703 	 * The received packet contains a MAC, so the transmitted packet
4704 	 * must be authenticated. For symmetric key cryptography, use
4705 	 * the predefined and trusted symmetric keys to generate the
4706 	 * cryptosum. For autokey cryptography, use the server private
4707 	 * value to generate the cookie, which is unique for every
4708 	 * source-destination-key ID combination.
4709 	 */
4710 #ifdef AUTOKEY
4711 	if (xkeyid > NTP_MAXKEY) {
4712 		keyid_t cookie;
4713 
4714 		/*
4715 		 * The only way to get here is a reply to a legitimate
4716 		 * client request message, so the mode must be
4717 		 * MODE_SERVER. If an extension field is present, there
4718 		 * can be only one and that must be a command. Do what
4719 		 * needs, but with private value of zero so the poor
4720 		 * jerk can decode it. If no extension field is present,
4721 		 * use the cookie to generate the session key.
4722 		 */
4723 		cookie = session_key(&rbufp->recv_srcadr,
4724 		    &rbufp->dstadr->sin, 0, sys_private, 0);
4725 		if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4726 			session_key(&rbufp->dstadr->sin,
4727 			    &rbufp->recv_srcadr, xkeyid, 0, 2);
4728 			temp32 = CRYPTO_RESP;
4729 			rpkt->exten[0] |= htonl(temp32);
4730 			sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4731 			    sendlen, (struct exten *)rpkt->exten,
4732 			    cookie);
4733 		} else {
4734 			session_key(&rbufp->dstadr->sin,
4735 			    &rbufp->recv_srcadr, xkeyid, cookie, 2);
4736 		}
4737 	}
4738 #endif	/* AUTOKEY */
4739 	get_systime(&xmt_tx);
4740 	sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4741 #ifdef AUTOKEY
4742 	if (xkeyid > NTP_MAXKEY)
4743 		authtrust(xkeyid, 0);
4744 #endif	/* AUTOKEY */
4745 	sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4746 	get_systime(&xmt_ty);
4747 	L_SUB(&xmt_ty, &xmt_tx);
4748 	sys_authdelay = xmt_ty;
4749 	DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4750 		    current_time, ntoa(&rbufp->dstadr->sin),
4751 		    ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4752 		    (u_long)sendlen));
4753 }
4754 
4755 
4756 /*
4757  * pool_xmit - resolve hostname or send unicast solicitation for pool.
4758  */
4759 static void
pool_xmit(struct peer * pool)4760 pool_xmit(
4761 	struct peer *pool	/* pool solicitor association */
4762 	)
4763 {
4764 #ifdef WORKER
4765 	struct pkt		xpkt;	/* transmit packet structure */
4766 	struct addrinfo		hints;
4767 	int			rc;
4768 	struct interface *	lcladr;
4769 	sockaddr_u *		rmtadr;
4770 	r4addr			r4a;
4771 	u_short			restrict_mask;
4772 	struct peer *		p;
4773 	l_fp			xmt_tx;
4774 
4775 	DEBUG_REQUIRE(pool);
4776 	if (NULL == pool->ai) {
4777 		if (pool->addrs != NULL) {
4778 			/* free() is used with copy_addrinfo_list() */
4779 			free(pool->addrs);
4780 			pool->addrs = NULL;
4781 		}
4782 		ZERO(hints);
4783 		hints.ai_family = AF(&pool->srcadr);
4784 		hints.ai_socktype = SOCK_DGRAM;
4785 		hints.ai_protocol = IPPROTO_UDP;
4786 		/* ignore getaddrinfo_sometime() errors, we will retry */
4787 		rc = getaddrinfo_sometime(
4788 			pool->hostname,
4789 			"ntp",
4790 			&hints,
4791 			0,			/* no retry */
4792 			&pool_name_resolved,
4793 			(void *)(intptr_t)pool->associd);
4794 		if (!rc)
4795 			DPRINTF(1, ("pool DNS lookup %s started\n",
4796 				pool->hostname));
4797 		else
4798 			msyslog(LOG_ERR,
4799 				"unable to start pool DNS %s: %m",
4800 				pool->hostname);
4801 		return;
4802 	}
4803 
4804 	do {
4805 		/* copy_addrinfo_list ai_addr points to a sockaddr_u */
4806 		rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4807 		pool->ai = pool->ai->ai_next;
4808 		p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0, NULL);
4809 	} while (p != NULL && pool->ai != NULL);
4810 	if (p != NULL)
4811 		return;	/* out of addresses, re-query DNS next poll */
4812 	restrictions(rmtadr, &r4a);
4813 	restrict_mask = r4a.rflags;
4814 	if (RES_FLAGS & restrict_mask)
4815 		restrict_source(rmtadr, 0,
4816 				current_time + POOL_SOLICIT_WINDOW + 1);
4817 	lcladr = findinterface(rmtadr);
4818 	memset(&xpkt, 0, sizeof(xpkt));
4819 	xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4820 					 MODE_CLIENT);
4821 	xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4822 	xpkt.ppoll = pool->hpoll;
4823 	xpkt.precision = sys_precision;
4824 	xpkt.refid = sys_refid;
4825 	xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4826 	xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4827 	/* Bug 3596: What are the pros/cons of using sys_reftime here? */
4828 	HTONL_FP(&sys_reftime, &xpkt.reftime);
4829 
4830 	/* HMS: the following is better done after the ntp_random() calls */
4831 	get_systime(&xmt_tx);
4832 	pool->aorg = xmt_tx;
4833 
4834 	if (FLAG_LOOPNONCE & pool->flags) {
4835 		l_fp nonce;
4836 
4837 		do {
4838 			nonce.l_ui = ntp_random();
4839 		} while (0 == nonce.l_ui);
4840 		do {
4841 			nonce.l_uf = ntp_random();
4842 		} while (0 == nonce.l_uf);
4843 		pool->nonce = nonce;
4844 		HTONL_FP(&nonce, &xpkt.xmt);
4845 	} else {
4846 		L_CLR(&pool->nonce);
4847 		HTONL_FP(&xmt_tx, &xpkt.xmt);
4848 	}
4849 	sendpkt(rmtadr, lcladr,
4850 		sys_ttl[(pool->ttl >= sys_ttlmax) ? sys_ttlmax : pool->ttl],
4851 		&xpkt, LEN_PKT_NOMAC);
4852 	pool->sent++;
4853 	pool->throttle += (1 << pool->minpoll) - 2;
4854 	DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4855 		    current_time, latoa(lcladr), stoa(rmtadr)));
4856 	msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4857 #endif	/* WORKER */
4858 }
4859 
4860 
4861 #ifdef AUTOKEY
4862 	/*
4863 	 * group_test - test if this is the same group
4864 	 *
4865 	 * host		assoc		return		action
4866 	 * none		none		0		mobilize *
4867 	 * none		group		0		mobilize *
4868 	 * group	none		0		mobilize *
4869 	 * group	group		1		mobilize
4870 	 * group	different	1		ignore
4871 	 * * ignore if notrust
4872 	 */
4873 int
group_test(char * grp,char * ident)4874 group_test(
4875 	char	*grp,
4876 	char	*ident
4877 	)
4878 {
4879 	if (grp == NULL)
4880 		return (0);
4881 
4882 	if (strcmp(grp, sys_groupname) == 0)
4883 		return (0);
4884 
4885 	if (ident == NULL)
4886 		return (1);
4887 
4888 	if (strcmp(grp, ident) == 0)
4889 		return (0);
4890 
4891 	return (1);
4892 }
4893 #endif /* AUTOKEY */
4894 
4895 
4896 #ifdef WORKER
4897 void
pool_name_resolved(int rescode,int gai_errno,void * context,const char * name,const char * service,const struct addrinfo * hints,const struct addrinfo * res)4898 pool_name_resolved(
4899 	int			rescode,
4900 	int			gai_errno,
4901 	void *			context,
4902 	const char *		name,
4903 	const char *		service,
4904 	const struct addrinfo *	hints,
4905 	const struct addrinfo *	res
4906 	)
4907 {
4908 	struct peer *	pool;	/* pool solicitor association */
4909 	associd_t	assoc;
4910 
4911 	if (rescode) {
4912 		msyslog(LOG_ERR,
4913 			"error resolving pool %s: %s (%d)",
4914 			name, gai_strerror(rescode), rescode);
4915 		return;
4916 	}
4917 
4918 	assoc = (associd_t)(intptr_t)context;
4919 	pool = findpeerbyassoc(assoc);
4920 	if (NULL == pool) {
4921 		msyslog(LOG_ERR,
4922 			"Could not find assoc %u for pool DNS %s",
4923 			assoc, name);
4924 		return;
4925 	}
4926 	DPRINTF(1, ("pool DNS %s completed\n", name));
4927 	pool->addrs = copy_addrinfo_list(res);
4928 	pool->ai = pool->addrs;
4929 	pool_xmit(pool);
4930 
4931 }
4932 #endif	/* WORKER */
4933 
4934 
4935 #ifdef AUTOKEY
4936 /*
4937  * key_expire - purge the key list
4938  */
4939 void
key_expire(struct peer * peer)4940 key_expire(
4941 	struct peer *peer	/* peer structure pointer */
4942 	)
4943 {
4944 	int i;
4945 
4946 	if (peer->keylist != NULL) {
4947 		for (i = 0; i <= peer->keynumber; i++)
4948 			authtrust(peer->keylist[i], 0);
4949 		free(peer->keylist);
4950 		peer->keylist = NULL;
4951 	}
4952 	value_free(&peer->sndval);
4953 	peer->keynumber = 0;
4954 	peer->flags &= ~FLAG_ASSOC;
4955 	DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4956 		    peer->associd));
4957 }
4958 #endif	/* AUTOKEY */
4959 
4960 
4961 /*
4962  * local_refid(peer) - check peer refid to avoid selecting peers
4963  *		       currently synced to this ntpd.
4964  */
4965 static int
local_refid(struct peer * p)4966 local_refid(
4967 	struct peer *	p
4968 	)
4969 {
4970 	endpt *	unicast_ep;
4971 
4972 	if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4973 		unicast_ep = p->dstadr;
4974 	else
4975 		unicast_ep = findinterface(&p->srcadr);
4976 
4977 	if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4978 		return TRUE;
4979 	else
4980 		return FALSE;
4981 }
4982 
4983 
4984 /*
4985  * Determine if the peer is unfit for synchronization
4986  *
4987  * A peer is unfit for synchronization if
4988  * > TEST10 bad leap or stratum below floor or at or above ceiling
4989  * > TEST11 root distance exceeded for remote peer
4990  * > TEST12 a direct or indirect synchronization loop would form
4991  * > TEST13 unreachable or noselect
4992  */
4993 int				/* FALSE if fit, TRUE if unfit */
peer_unfit(struct peer * peer)4994 peer_unfit(
4995 	struct peer *peer	/* peer structure pointer */
4996 	)
4997 {
4998 	int	rval = 0;
4999 
5000 	/*
5001 	 * A stratum error occurs if (1) the server has never been
5002 	 * synchronized, (2) the server stratum is below the floor or
5003 	 * greater than or equal to the ceiling.
5004 	 */
5005 	if (   peer->leap == LEAP_NOTINSYNC
5006 	    || peer->stratum < sys_floor
5007 	    || peer->stratum >= sys_ceiling) {
5008 		rval |= TEST10;		/* bad synch or stratum */
5009 	}
5010 
5011 	/*
5012 	 * A distance error for a remote peer occurs if the root
5013 	 * distance is greater than or equal to the distance threshold
5014 	 * plus the increment due to one host poll interval.
5015 	 */
5016 	if (   !(peer->flags & FLAG_REFCLOCK)
5017 	    && root_distance(peer) >= sys_maxdist
5018 				      + clock_phi * ULOGTOD(peer->hpoll)) {
5019 		rval |= TEST11;		/* distance exceeded */
5020 	}
5021 
5022 	/*
5023 	 * A loop error occurs if the remote peer is synchronized to the
5024 	 * local peer or if the remote peer is synchronized to the same
5025 	 * server as the local peer but only if the remote peer is
5026 	 * neither a reference clock nor an orphan.
5027 	 */
5028 	if (peer->stratum > 1 && local_refid(peer)) {
5029 		rval |= TEST12;		/* synchronization loop */
5030 	}
5031 
5032 	/*
5033 	 * An unreachable error occurs if the server is unreachable or
5034 	 * the noselect bit is set.
5035 	 */
5036 	if (!peer->reach || (peer->flags & FLAG_NOSELECT)) {
5037 		rval |= TEST13;		/* unreachable */
5038 	}
5039 
5040 	peer->flash &= ~PEER_TEST_MASK;
5041 	peer->flash |= rval;
5042 	return (rval);
5043 }
5044 
5045 
5046 /*
5047  * Find the precision of this particular machine
5048  */
5049 #define MINSTEP		20e-9	/* minimum clock increment (s) */
5050 #define MAXSTEP		1	/* maximum clock increment (s) */
5051 #define MINCHANGES	12	/* minimum number of step samples */
5052 #define MAXLOOPS	((int)(1. / MINSTEP))	/* avoid infinite loop */
5053 
5054 /*
5055  * This routine measures the system precision defined as the minimum of
5056  * a sequence of differences between successive readings of the system
5057  * clock. However, if a difference is less than MINSTEP, the clock has
5058  * been read more than once during a clock tick and the difference is
5059  * ignored. We set MINSTEP greater than zero in case something happens
5060  * like a cache miss, and to tolerate underlying system clocks which
5061  * ensure each reading is strictly greater than prior readings while
5062  * using an underlying stepping (not interpolated) clock.
5063  *
5064  * sys_tick and sys_precision represent the time to read the clock for
5065  * systems with high-precision clocks, and the tick interval or step
5066  * size for lower-precision stepping clocks.
5067  *
5068  * This routine also measures the time to read the clock on stepping
5069  * system clocks by counting the number of readings between changes of
5070  * the underlying clock.  With either type of clock, the minimum time
5071  * to read the clock is saved as sys_fuzz, and used to ensure the
5072  * get_systime() readings always increase and are fuzzed below sys_fuzz.
5073  */
5074 void
measure_precision(void)5075 measure_precision(void)
5076 {
5077 	/*
5078 	 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
5079 	 * is effectively disabled.  trunc_os_clock is FALSE to disable
5080 	 * get_ostime() simulation of a low-precision system clock.
5081 	 */
5082 	set_sys_fuzz(0.);
5083 	trunc_os_clock = FALSE;
5084 	measured_tick = measure_tick_fuzz();
5085 	set_sys_tick_precision(measured_tick);
5086 	msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
5087 		sys_tick * 1e6, sys_precision);
5088 	if (sys_fuzz < sys_tick) {
5089 		msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
5090 			sys_fuzz * 1e6);
5091 	}
5092 }
5093 
5094 
5095 /*
5096  * measure_tick_fuzz()
5097  *
5098  * measures the minimum time to read the clock (stored in sys_fuzz)
5099  * and returns the tick, the larger of the minimum increment observed
5100  * between successive clock readings and the time to read the clock.
5101  */
5102 double
measure_tick_fuzz(void)5103 measure_tick_fuzz(void)
5104 {
5105 	l_fp	minstep;	/* MINSTEP as l_fp */
5106 	l_fp	val;		/* current seconds fraction */
5107 	l_fp	last;		/* last seconds fraction */
5108 	l_fp	ldiff;		/* val - last */
5109 	double	tick;		/* computed tick value */
5110 	double	diff;
5111 	long	repeats;
5112 	long	max_repeats;
5113 	int	changes;
5114 	int	i;		/* log2 precision */
5115 
5116 	tick = MAXSTEP;
5117 	max_repeats = 0;
5118 	repeats = 0;
5119 	changes = 0;
5120 	DTOLFP(MINSTEP, &minstep);
5121 	get_systime(&last);
5122 	for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
5123 		get_systime(&val);
5124 		ldiff = val;
5125 		L_SUB(&ldiff, &last);
5126 		last = val;
5127 		if (L_ISGT(&ldiff, &minstep)) {
5128 			max_repeats = max(repeats, max_repeats);
5129 			repeats = 0;
5130 			changes++;
5131 			LFPTOD(&ldiff, diff);
5132 			tick = min(diff, tick);
5133 		} else {
5134 			repeats++;
5135 		}
5136 	}
5137 	if (changes < MINCHANGES) {
5138 		msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
5139 		exit(1);
5140 	}
5141 
5142 	if (0 == max_repeats) {
5143 		set_sys_fuzz(tick);
5144 	} else {
5145 		set_sys_fuzz(tick / max_repeats);
5146 	}
5147 
5148 	return tick;
5149 }
5150 
5151 
5152 void
set_sys_tick_precision(double tick)5153 set_sys_tick_precision(
5154 	double tick
5155 	)
5156 {
5157 	int i;
5158 
5159 	if (tick > 1.) {
5160 		msyslog(LOG_ERR,
5161 			"unsupported tick %.3f > 1s ignored", tick);
5162 		return;
5163 	}
5164 	if (tick < measured_tick) {
5165 		msyslog(LOG_ERR,
5166 			"proto: tick %.3f less than measured tick %.3f, ignored",
5167 			tick, measured_tick);
5168 		return;
5169 	} else if (tick > measured_tick) {
5170 		trunc_os_clock = TRUE;
5171 		msyslog(LOG_NOTICE,
5172 			"proto: truncating system clock to multiples of %.9f",
5173 			tick);
5174 	}
5175 	sys_tick = tick;
5176 
5177 	/*
5178 	 * Find the nearest power of two.
5179 	 */
5180 	for (i = 0; tick <= 1; i--)
5181 		tick *= 2;
5182 	if (tick - 1 > 1 - tick / 2)
5183 		i++;
5184 
5185 	sys_precision = (s_char)i;
5186 }
5187 
5188 
5189 /*
5190  * init_proto - initialize the protocol module's data
5191  */
5192 void
init_proto(void)5193 init_proto(void)
5194 {
5195 	l_fp	dummy;
5196 	int	i;
5197 
5198 	/*
5199 	 * Fill in the sys_* stuff.  Default is don't listen to
5200 	 * broadcasting, require authentication.
5201 	 */
5202 	set_sys_leap(LEAP_NOTINSYNC);
5203 	sys_stratum = STRATUM_UNSPEC;
5204 	memcpy(&sys_refid, "INIT", 4);
5205 	sys_peer = NULL;
5206 	sys_rootdelay = 0;
5207 	sys_rootdisp = 0;
5208 	L_CLR(&sys_reftime);
5209 	sys_jitter = 0;
5210 	measure_precision();
5211 	get_systime(&dummy);
5212 	sys_survivors = 0;
5213 	sys_manycastserver = 0;
5214 	sys_bclient = 0;
5215 	sys_bdelay = BDELAY_DEFAULT;	/*[Bug 3031] delay cutoff */
5216 	sys_authenticate = 1;
5217 	sys_stattime = current_time;
5218 	orphwait = current_time + sys_orphwait;
5219 	proto_clr_stats();
5220 	for (i = 0; i < MAX_TTL; ++i)
5221 		sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
5222 	sys_ttlmax = (MAX_TTL - 1);
5223 	hardpps_enable = 0;
5224 	stats_control = 1;
5225 }
5226 
5227 
5228 /*
5229  * proto_config - configure the protocol module
5230  */
5231 void
proto_config(int item,u_long value,double dvalue,sockaddr_u * svalue)5232 proto_config(
5233 	int	item,
5234 	u_long	value,
5235 	double	dvalue,
5236 	sockaddr_u *svalue
5237 	)
5238 {
5239 	/*
5240 	 * Figure out what he wants to change, then do it
5241 	 */
5242 	DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
5243 		    item, value, dvalue));
5244 
5245 	switch (item) {
5246 
5247 	/*
5248 	 * enable and disable commands - arguments are Boolean.
5249 	 */
5250 	case PROTO_AUTHENTICATE: /* authentication (auth) */
5251 		sys_authenticate = value;
5252 		break;
5253 
5254 	case PROTO_BROADCLIENT: /* broadcast client (bclient) */
5255 		sys_bclient = (int)value;
5256 		if (sys_bclient == 0)
5257 			io_unsetbclient();
5258 		else
5259 			io_setbclient();
5260 		break;
5261 
5262 #ifdef REFCLOCK
5263 	case PROTO_CAL:		/* refclock calibrate (calibrate) */
5264 		cal_enable = value;
5265 		break;
5266 #endif /* REFCLOCK */
5267 
5268 	case PROTO_KERNEL:	/* kernel discipline (kernel) */
5269 		select_loop(value);
5270 		break;
5271 
5272 	case PROTO_MONITOR:	/* monitoring (monitor) */
5273 		if (value)
5274 			mon_start(MON_ON);
5275 		else {
5276 			mon_stop(MON_ON);
5277 			if (mon_enabled)
5278 				msyslog(LOG_WARNING,
5279 					"restrict: 'monitor' cannot be disabled while 'limited' is enabled");
5280 		}
5281 		break;
5282 
5283 	case PROTO_NTP:		/* NTP discipline (ntp) */
5284 		ntp_enable = value;
5285 		break;
5286 
5287 	case PROTO_MODE7:	/* mode7 management (ntpdc) */
5288 		ntp_mode7 = value;
5289 		break;
5290 
5291 	case PROTO_PPS:		/* PPS discipline (pps) */
5292 		hardpps_enable = value;
5293 		break;
5294 
5295 	case PROTO_FILEGEN:	/* statistics (stats) */
5296 		stats_control = value;
5297 		break;
5298 
5299 	/*
5300 	 * tos command - arguments are double, sometimes cast to int
5301 	 */
5302 
5303 	case PROTO_BCPOLLBSTEP:	/* Broadcast Poll Backstep gate (bcpollbstep) */
5304 		sys_bcpollbstep = (u_char)dvalue;
5305 		break;
5306 
5307 	case PROTO_BEACON:	/* manycast beacon (beacon) */
5308 		sys_beacon = (int)dvalue;
5309 		break;
5310 
5311 	case PROTO_BROADDELAY:	/* default broadcast delay (bdelay) */
5312 		sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
5313 		break;
5314 
5315 	case PROTO_CEILING:	/* stratum ceiling (ceiling) */
5316 		sys_ceiling = (int)dvalue;
5317 		break;
5318 
5319 	case PROTO_COHORT:	/* cohort switch (cohort) */
5320 		sys_cohort = (int)dvalue;
5321 		break;
5322 
5323 	case PROTO_FLOOR:	/* stratum floor (floor) */
5324 		sys_floor = (int)dvalue;
5325 		break;
5326 
5327 	case PROTO_MAXCLOCK:	/* maximum candidates (maxclock) */
5328 		sys_maxclock = (int)dvalue;
5329 		break;
5330 
5331 	case PROTO_MAXDIST:	/* select threshold (maxdist) */
5332 		sys_maxdist = dvalue;
5333 		break;
5334 
5335 	case PROTO_CALLDELAY:	/* modem call delay (mdelay) */
5336 		break;		/* NOT USED */
5337 
5338 	case PROTO_MINCLOCK:	/* minimum candidates (minclock) */
5339 		sys_minclock = (int)dvalue;
5340 		break;
5341 
5342 	case PROTO_MINDISP:	/* minimum distance (mindist) */
5343 		sys_mindisp = dvalue;
5344 		break;
5345 
5346 	case PROTO_MINSANE:	/* minimum survivors (minsane) */
5347 		sys_minsane = (int)dvalue;
5348 		break;
5349 
5350 	case PROTO_ORPHAN:	/* orphan stratum (orphan) */
5351 		sys_orphan = (int)dvalue;
5352 		break;
5353 
5354 	case PROTO_ORPHWAIT:	/* orphan wait (orphwait) */
5355 		orphwait -= sys_orphwait;
5356 		sys_orphwait = (dvalue >= 1) ? (int)dvalue : NTP_ORPHWAIT;
5357 		orphwait += sys_orphwait;
5358 		break;
5359 
5360 	/*
5361 	 * Miscellaneous commands
5362 	 */
5363 	case PROTO_MULTICAST_ADD: /* add group address */
5364 		if (svalue != NULL)
5365 			io_multicast_add(svalue);
5366 		sys_bclient = 1;
5367 		break;
5368 
5369 	case PROTO_MULTICAST_DEL: /* delete group address */
5370 		if (svalue != NULL)
5371 			io_multicast_del(svalue);
5372 		break;
5373 
5374 	/*
5375 	 * Peer_clear Early policy choices
5376 	 */
5377 
5378 	case PROTO_PCEDIGEST:	/* Digest */
5379 		peer_clear_digest_early = value;
5380 		break;
5381 
5382 	/*
5383 	 * Unpeer Early policy choices
5384 	 */
5385 
5386 	case PROTO_UECRYPTO:	/* Crypto */
5387 		unpeer_crypto_early = value;
5388 		break;
5389 
5390 	case PROTO_UECRYPTONAK:	/* Crypto_NAK */
5391 		unpeer_crypto_nak_early = value;
5392 		break;
5393 
5394 	case PROTO_UEDIGEST:	/* Digest */
5395 		unpeer_digest_early = value;
5396 		break;
5397 
5398 	default:
5399 		msyslog(LOG_NOTICE,
5400 		    "proto: unsupported option %d", item);
5401 	}
5402 }
5403 
5404 
5405 /*
5406  * proto_clr_stats - clear protocol stat counters
5407  */
5408 void
proto_clr_stats(void)5409 proto_clr_stats(void)
5410 {
5411 	sys_stattime = current_time;
5412 	sys_received = 0;
5413 	sys_processed = 0;
5414 	sys_newversion = 0;
5415 	sys_oldversion = 0;
5416 	sys_declined = 0;
5417 	sys_restricted = 0;
5418 	sys_badlength = 0;
5419 	sys_badauth = 0;
5420 	sys_limitrejected = 0;
5421 	sys_kodsent = 0;
5422 	sys_lamport = 0;
5423 	sys_tsrounding = 0;
5424 }
5425