Sync usage with man page.
[netbsd-mini2440.git] / dist / ntp / ntpd / ntp_proto.c
blob8b4b70534c35e82de56c721e12c25e4447fa976b
1 /* $NetBSD: ntp_proto.c,v 1.6 2006/06/11 19:34:11 kardel Exp $ */
3 /*
4 * ntp_proto.c - NTP version 4 protocol machinery
6 * ATTENTION: Get approval from Dave Mills on all changes to this file!
8 */
9 #ifdef HAVE_CONFIG_H
10 #include <config.h>
11 #endif
13 #include "ntpd.h"
14 #include "ntp_stdlib.h"
15 #include "ntp_unixtime.h"
16 #include "ntp_control.h"
17 #include "ntp_string.h"
19 #include <stdio.h>
21 #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
22 #include "ntp_refclock.h"
23 #endif
25 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
26 #include <sys/sysctl.h>
27 #endif
30 * This macro defines the authentication state. If x is 1 authentication
31 * is required; othewise it is optional.
33 #define AUTH(x, y) ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
34 (y) == AUTH_NONE)
37 * System variables are declared here. See Section 3.2 of the
38 * specification.
40 u_char sys_leap; /* system leap indicator */
41 u_char sys_stratum; /* stratum of system */
42 s_char sys_precision; /* local clock precision (log2 s) */
43 double sys_rootdelay; /* roundtrip delay to primary source */
44 double sys_rootdispersion; /* dispersion to primary source */
45 u_int32 sys_refid; /* source/loop in network byte order */
46 static double sys_offset; /* current local clock offset */
47 l_fp sys_reftime; /* time we were last updated */
48 struct peer *sys_peer; /* our current peer */
49 struct peer *sys_pps; /* our PPS peer */
50 struct peer *sys_prefer; /* our cherished peer */
51 int sys_kod; /* kod credit */
52 int sys_kod_rate = 2; /* max kod packets per second */
53 #ifdef OPENSSL
54 u_long sys_automax; /* maximum session key lifetime */
55 #endif /* OPENSSL */
58 * Nonspecified system state variables.
60 int sys_bclient; /* broadcast client enable */
61 double sys_bdelay; /* broadcast client default delay */
62 int sys_calldelay; /* modem callup delay (s) */
63 int sys_authenticate; /* requre authentication for config */
64 l_fp sys_authdelay; /* authentication delay */
65 static u_long sys_authdly[2]; /* authentication delay shift reg */
66 static double sys_mindisp = MINDISPERSE; /* min disp increment (s) */
67 static double sys_maxdist = MAXDISTANCE; /* selection threshold (s) */
68 double sys_jitter; /* system jitter (s) */
69 static int sys_hopper; /* anticlockhop counter */
70 static int sys_maxhop = MAXHOP; /* anticlockhop counter threshold */
71 int leap_next; /* leap consensus */
72 keyid_t sys_private; /* private value for session seed */
73 int sys_manycastserver; /* respond to manycast client pkts */
74 int peer_ntpdate; /* active peers in ntpdate mode */
75 int sys_survivors; /* truest of the truechimers */
76 #ifdef OPENSSL
77 char *sys_hostname; /* gethostname() name */
78 #endif /* OPENSSL */
81 * TOS and multicast mapping stuff
83 int sys_floor = 0; /* cluster stratum floor */
84 int sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling */
85 int sys_minsane = 1; /* minimum candidates */
86 int sys_minclock = NTP_MINCLOCK; /* minimum survivors */
87 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
88 int sys_cohort = 0; /* cohort switch */
89 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
90 double sys_orphandelay = 0; /* orphan root delay */
91 int sys_beacon = BEACON; /* manycast beacon interval */
92 int sys_ttlmax; /* max ttl mapping vector index */
93 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
96 * Statistics counters
98 u_long sys_stattime; /* time since reset */
99 u_long sys_received; /* packets received */
100 u_long sys_processed; /* packets processed */
101 u_long sys_newversionpkt; /* current version */
102 u_long sys_oldversionpkt; /* recent version */
103 u_long sys_unknownversion; /* invalid version */
104 u_long sys_restricted; /* access denied */
105 u_long sys_badlength; /* bad length or format */
106 u_long sys_badauth; /* bad authentication */
107 u_long sys_limitrejected; /* rate exceeded */
109 static double root_distance P((struct peer *));
110 static void clock_combine P((struct peer **, int));
111 static void peer_xmit P((struct peer *));
112 static void fast_xmit P((struct recvbuf *, int, keyid_t,
113 int));
114 static void clock_update P((void));
115 static int default_get_precision P((void));
116 static int peer_unfit P((struct peer *));
120 * transmit - Transmit Procedure. See Section 3.4.2 of the
121 * specification.
123 void
124 transmit(
125 struct peer *peer /* peer structure pointer */
128 int hpoll;
131 * The polling state machine. There are two kinds of machines,
132 * those that never expect a reply (broadcast and manycast
133 * server modes) and those that do (all other modes). The dance
134 * is intricate...
137 * Orphan mode is active when enabled and when no servers less
138 * than the orphan statum are available. In this mode packets
139 * are sent at the orphan stratum. An orphan with no other
140 * synchronization source is an orphan parent. It assumes root
141 * delay zero and reference ID the loopback address. All others
142 * are orphan children with root delay randomized over a 1-s
143 * range. The root delay is used by the election algorithm to
144 * select the order of synchronization.
146 hpoll = peer->hpoll;
147 if (sys_orphan < STRATUM_UNSPEC && sys_peer == NULL) {
148 sys_leap = LEAP_NOWARNING;
149 sys_stratum = sys_orphan;
150 sys_refid = htonl(LOOPBACKADR);
151 sys_rootdelay = 0;
152 sys_rootdispersion = 0;
156 * In broadcast mode the poll interval is never changed from
157 * minpoll.
159 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
160 peer->outdate = current_time;
161 peer_xmit(peer);
162 poll_update(peer, hpoll);
163 return;
167 * In manycast mode we start with unity ttl. The ttl is
168 * increased by one for each poll until either sys_maxclock
169 * servers have been found or the maximum ttl is reached. When
170 * sys_maxclock servers are found we stop polling until one or
171 * more servers have timed out or until less than minpoll
172 * associations turn up. In this case additional better servers
173 * are dragged in and preempt the existing ones.
175 if (peer->cast_flags & MDF_ACAST) {
176 peer->outdate = current_time;
177 if (peer->unreach > sys_beacon) {
178 peer->unreach = 0;
179 peer->ttl = 0;
180 peer_xmit(peer);
181 } else if (sys_survivors < sys_minclock ||
182 peer_preempt < sys_maxclock) {
183 if (peer->ttl < sys_ttlmax)
184 peer->ttl++;
185 peer_xmit(peer);
187 peer->unreach++;
188 poll_update(peer, hpoll);
189 return;
193 * In unicast modes the dance is much more intricate. It is
194 * desigmed to back off whenever possible to minimize network
195 * traffic.
197 if (peer->burst == 0) {
198 u_char oreach;
201 * Update the reachability status. If not heard for
202 * three consecutive polls, stuff infinity in the clock
203 * filter.
205 oreach = peer->reach;
206 peer->outdate = current_time;
207 if (peer == sys_peer)
208 sys_hopper++;
209 peer->reach <<= 1;
210 if (!(peer->reach & 0x07))
211 clock_filter(peer, 0., 0., MAXDISPERSE);
212 if (!peer->reach) {
215 * Here the peer is unreachable. If it was
216 * previously reachable, raise a trap.
218 if (oreach) {
219 report_event(EVNT_UNREACH, peer);
220 peer->timereachable = current_time;
224 * Send a burst if enabled, but only once after
225 * a peer becomes unreachable. If the prempt
226 * flag is dim, bump the unreach counter by one;
227 * otherwise, bump it by three.
229 if (peer->flags & FLAG_IBURST &&
230 peer->unreach == 0) {
231 peer->burst = NTP_BURST;
233 if (!(peer->flags & FLAG_PREEMPT))
234 peer->unreach++;
235 else
236 peer->unreach += 3;
237 } else {
240 * Here the peer is reachable. Set the poll
241 * interval to the system poll interval. Send a
242 * burst only if enabled and the peer is fit.
244 * Respond to the peer evaluation produced by
245 * the selection algorithm. If less than the
246 * outlyer level, up the unreach by three. If
247 * there are excess associations, up the unreach
248 * by two if not a candidate and by one if so.
250 if (!(peer->flags & FLAG_PREEMPT)) {
251 peer->unreach = 0;
252 } else if (peer->status < CTL_PST_SEL_SELCAND) {
253 peer->unreach += 3;
254 } else if (peer_preempt > sys_maxclock) {
255 if (peer->status < CTL_PST_SEL_SYNCCAND)
256 peer->unreach += 2;
257 else
258 peer->unreach++;
259 } else {
260 peer->unreach = 0;
262 hpoll = sys_poll;
263 if (peer->flags & FLAG_BURST &&
264 !peer_unfit(peer))
265 peer->burst = NTP_BURST;
269 * Watch for timeout. If ephemeral or preemptable, toss
270 * the rascal; otherwise, bump the poll interval.
272 if (peer->unreach >= NTP_UNREACH) {
273 if (peer->flags & FLAG_PREEMPT ||
274 !(peer->flags & FLAG_CONFIG)) {
275 peer_clear(peer, "TIME");
276 unpeer(peer);
277 return;
278 } else {
279 hpoll++;
282 } else {
283 peer->burst--;
286 * If a broadcast client at this point, the burst has
287 * concluded, so we switch to client mode and purge the
288 * keylist, since no further transmissions will be made.
290 if (peer->burst == 0) {
291 if (peer->cast_flags & MDF_BCLNT) {
292 peer->hmode = MODE_BCLIENT;
293 #ifdef OPENSSL
294 key_expire(peer);
295 #endif /* OPENSSL */
299 * If ntpdate mode and the clock has not been
300 * set and all peers have completed the burst,
301 * we declare a successful failure.
303 if (mode_ntpdate) {
304 peer_ntpdate--;
305 if (peer_ntpdate == 0) {
306 msyslog(LOG_NOTICE,
307 "no reply; clock not set");
308 exit (0);
315 * Do not transmit if in broadcast client mode.
317 if (peer->hmode != MODE_BCLIENT)
318 peer_xmit(peer);
319 poll_update(peer, hpoll);
324 * receive - Receive Procedure. See section 3.4.3 in the specification.
326 void
327 receive(
328 struct recvbuf *rbufp
331 register struct peer *peer; /* peer structure pointer */
332 register struct pkt *pkt; /* receive packet pointer */
333 int hisversion; /* packet version */
334 int hisleap; /* packet leap indicator */
335 int hismode; /* packet mode */
336 int hisstratum; /* packet stratum */
337 int restrict_mask; /* restrict bits */
338 int has_mac; /* length of MAC field */
339 int authlen; /* offset of MAC field */
340 int is_authentic = 0; /* cryptosum ok */
341 keyid_t skeyid = 0; /* key ID */
342 struct sockaddr_storage *dstadr_sin; /* active runway */
343 struct peer *peer2; /* aux peer structure pointer */
344 l_fp p_org; /* origin timestamp */
345 l_fp p_rec; /* receive timestamp */
346 l_fp p_xmt; /* transmit timestamp */
347 #ifdef OPENSSL
348 keyid_t tkeyid = 0; /* temporary key ID */
349 keyid_t pkeyid = 0; /* previous key ID */
350 struct autokey *ap; /* autokey structure pointer */
351 int rval; /* cookie snatcher */
352 #endif /* OPENSSL */
353 int retcode = AM_NOMATCH;
354 int at_listhead;
357 * Monitor the packet and get restrictions. Note that the packet
358 * length for control and private mode packets must be checked
359 * by the service routines. Note that no statistics counters are
360 * recorded for restrict violations, since these counters are in
361 * the restriction routine. Note the careful distinctions here
362 * between a packet with a format error and a packet that is
363 * simply discarded without prejudice. Some restrictions have to
364 * be handled later in order to generate a kiss-of-death packet.
367 * Bogus port check is before anything, since it probably
368 * reveals a clogging attack.
370 sys_received++;
371 if (SRCPORT(&rbufp->recv_srcadr) == 0) {
372 sys_badlength++;
373 return; /* bogus port */
375 at_listhead = ntp_monitor(rbufp);
376 restrict_mask = restrictions(&rbufp->recv_srcadr, at_listhead);
377 #ifdef DEBUG
378 if (debug > 1)
379 printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
380 current_time, stoa(&rbufp->dstadr->sin),
381 stoa(&rbufp->recv_srcadr),
382 rbufp->dstadr->flags, restrict_mask);
383 #endif
384 if (restrict_mask & RES_IGNORE) {
385 sys_restricted++;
386 return; /* ignore everything */
388 pkt = &rbufp->recv_pkt;
389 hisversion = PKT_VERSION(pkt->li_vn_mode);
390 hisleap = PKT_LEAP(pkt->li_vn_mode);
391 hismode = (int)PKT_MODE(pkt->li_vn_mode);
392 hisstratum = PKT_TO_STRATUM(pkt->stratum);
393 if (hismode == MODE_PRIVATE) {
394 if (restrict_mask & RES_NOQUERY) {
395 sys_restricted++;
396 return; /* no query private */
398 process_private(rbufp, ((restrict_mask &
399 RES_NOMODIFY) == 0));
400 return;
402 if (hismode == MODE_CONTROL) {
403 if (restrict_mask & RES_NOQUERY) {
404 sys_restricted++;
405 return; /* no query control */
407 process_control(rbufp, restrict_mask);
408 return;
410 if (restrict_mask & RES_DONTSERVE) {
411 sys_restricted++;
412 return; /* no time */
414 if (rbufp->recv_length < LEN_PKT_NOMAC) {
415 sys_badlength++;
416 return; /* runt packet */
420 * Version check must be after the query packets, since they
421 * intentionally use early version.
423 if (hisversion == NTP_VERSION) {
424 sys_newversionpkt++; /* new version */
425 } else if (!(restrict_mask & RES_VERSION) && hisversion >=
426 NTP_OLDVERSION) {
427 sys_oldversionpkt++; /* previous version */
428 } else {
429 sys_unknownversion++;
430 return; /* old version */
434 * Figure out his mode and validate the packet. This has some
435 * legacy raunch that probably should be removed. In very early
436 * NTP versions mode 0 was equivalent to what later versions
437 * would interpret as client mode.
439 if (hismode == MODE_UNSPEC) {
440 if (hisversion == NTP_OLDVERSION) {
441 hismode = MODE_CLIENT;
442 } else {
443 sys_badlength++;
444 return; /* invalid mode */
449 * Parse the extension field if present. We figure out whether
450 * an extension field is present by measuring the MAC size. If
451 * the number of words following the packet header is 0, no MAC
452 * is present and the packet is not authenticated. If 1, the
453 * packet is a crypto-NAK; if 3, the packet is authenticated
454 * with DES; if 5, the packet is authenticated with MD5. If 2 or
455 * 4, the packet is a runt and discarded forthwith. If greater
456 * than 5, an extension field is present, so we subtract the
457 * length of the field and go around again.
459 authlen = LEN_PKT_NOMAC;
460 has_mac = rbufp->recv_length - authlen;
461 while (has_mac > 0) {
462 int temp;
464 if (has_mac % 4 != 0 || has_mac < 0) {
465 sys_badlength++;
466 return; /* bad MAC length */
468 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
469 MAX_MAC_LEN) {
470 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
471 break;
473 } else if (has_mac > MAX_MAC_LEN) {
474 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
475 0xffff;
476 if (temp < 4 || temp > NTP_MAXEXTEN || temp % 4
477 != 0) {
478 sys_badlength++;
479 return; /* bad MAC length */
481 authlen += temp;
482 has_mac -= temp;
483 } else {
484 sys_badlength++;
485 return; /* bad MAC length */
488 #ifdef OPENSSL
489 pkeyid = tkeyid = 0;
490 #endif /* OPENSSL */
493 * We have tossed out as many buggy packets as possible early in
494 * the game to reduce the exposure to a clogging attack. Now we
495 * have to burn some cycles to find the association and
496 * authenticate the packet if required. Note that we burn only
497 * MD5 cycles, again to reduce exposure. There may be no
498 * matching association and that's okay.
500 * More on the autokey mambo. Normally the local interface is
501 * found when the association was mobilized with respect to a
502 * designated remote address. We assume packets arriving from
503 * the remote address arrive via this interface and the local
504 * address used to construct the autokey is the unicast address
505 * of the interface. However, if the sender is a broadcaster,
506 * the interface broadcast address is used instead.
507 & Notwithstanding this technobabble, if the sender is a
508 * multicaster, the broadcast address is null, so we use the
509 * unicast address anyway. Don't ask.
511 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, hismode,
512 &retcode);
513 dstadr_sin = &rbufp->dstadr->sin;
514 NTOHL_FP(&pkt->org, &p_org);
515 NTOHL_FP(&pkt->rec, &p_rec);
516 NTOHL_FP(&pkt->xmt, &p_xmt);
519 * Authentication is conditioned by three switches:
521 * NOPEER (RES_NOPEER) do not mobilize an association unless
522 * authenticated
523 * NOTRUST (RES_DONTTRUST) do not allow access unless
524 * authenticated (implies NOPEER)
525 * enable (sys_authenticate) master NOPEER switch, by default
526 * on
528 * The NOPEER and NOTRUST can be specified on a per-client basis
529 * using the restrict command. The enable switch if on implies
530 * NOPEER for all clients. There are four outcomes:
532 * NONE The packet has no MAC.
533 * OK the packet has a MAC and authentication succeeds
534 * ERROR the packet has a MAC and authentication fails
535 * CRYPTO crypto-NAK. The MAC has four octets only.
537 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
538 * is zero, acceptable outcomes of y are NONE and OK. If x is
539 * one, the only acceptable outcome of y is OK.
541 if (has_mac == 0) {
542 is_authentic = AUTH_NONE; /* not required */
543 #ifdef DEBUG
544 if (debug)
545 printf("receive: at %ld %s<-%s mode %d code %d auth %d\n",
546 current_time, stoa(dstadr_sin),
547 stoa(&rbufp->recv_srcadr), hismode, retcode,
548 is_authentic);
549 #endif
550 } else if (has_mac == 4) {
551 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
552 #ifdef DEBUG
553 if (debug)
554 printf(
555 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
556 current_time, stoa(dstadr_sin),
557 stoa(&rbufp->recv_srcadr), hismode, retcode,
558 skeyid, authlen, has_mac, is_authentic);
559 #endif
560 } else {
561 #ifdef OPENSSL
563 * For autokey modes, generate the session key
564 * and install in the key cache. Use the socket
565 * broadcast or unicast address as appropriate.
567 if (skeyid > NTP_MAXKEY) {
570 * More on the autokey dance (AKD). A cookie is
571 * constructed from public and private values.
572 * For broadcast packets, the cookie is public
573 * (zero). For packets that match no
574 * association, the cookie is hashed from the
575 * addresses and private value. For server
576 * packets, the cookie was previously obtained
577 * from the server. For symmetric modes, the
578 * cookie was previously constructed using an
579 * agreement protocol; however, should PKI be
580 * unavailable, we construct a fake agreement as
581 * the EXOR of the peer and host cookies.
583 * hismode ephemeral persistent
584 * =======================================
585 * active 0 cookie#
586 * passive 0% cookie#
587 * client sys cookie 0%
588 * server 0% sys cookie
589 * broadcast 0 0
591 * # if unsync, 0
592 * % can't happen
594 if (hismode == MODE_BROADCAST) {
597 * For broadcaster, use the interface
598 * broadcast address when available;
599 * otherwise, use the unicast address
600 * found when the association was
601 * mobilized. However, if this is from
602 * the wildcard interface, game over.
604 if (crypto_flags && rbufp->dstadr ==
605 any_interface) {
606 sys_restricted++;
607 return; /* no wildcard */
609 pkeyid = 0;
610 if (!SOCKNUL(&rbufp->dstadr->bcast))
611 dstadr_sin =
612 &rbufp->dstadr->bcast;
613 } else if (peer == NULL) {
614 pkeyid = session_key(
615 &rbufp->recv_srcadr, dstadr_sin, 0,
616 sys_private, 0);
617 } else {
618 pkeyid = peer->pcookie;
622 * The session key includes both the public
623 * values and cookie. In case of an extension
624 * field, the cookie used for authentication
625 * purposes is zero. Note the hash is saved for
626 * use later in the autokey mambo.
628 if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
629 session_key(&rbufp->recv_srcadr,
630 dstadr_sin, skeyid, 0, 2);
631 tkeyid = session_key(
632 &rbufp->recv_srcadr, dstadr_sin,
633 skeyid, pkeyid, 0);
634 } else {
635 tkeyid = session_key(
636 &rbufp->recv_srcadr, dstadr_sin,
637 skeyid, pkeyid, 2);
641 #endif /* OPENSSL */
644 * Compute the cryptosum. Note a clogging attack may
645 * succeed in bloating the key cache. If an autokey,
646 * purge it immediately, since we won't be needing it
647 * again. If the packet is authentic, it can mobilize an
648 * association. Note that there is no key zero.
650 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
651 has_mac)) {
652 is_authentic = AUTH_ERROR;
653 sys_badauth++;
654 } else {
655 is_authentic = AUTH_OK;
657 #ifdef OPENSSL
658 if (skeyid > NTP_MAXKEY)
659 authtrust(skeyid, 0);
660 #endif /* OPENSSL */
661 #ifdef DEBUG
662 if (debug)
663 printf(
664 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
665 current_time, stoa(dstadr_sin),
666 stoa(&rbufp->recv_srcadr), hismode, retcode,
667 skeyid, authlen, has_mac, is_authentic);
668 #endif
672 * The association matching rules are implemented by a set of
673 * routines and an association table. A packet matching an
674 * association is processed by the peer process for that
675 * association. If there are no errors, an ephemeral association
676 * is mobilized: a broadcast packet mobilizes a broadcast client
677 * aassociation; a manycast server packet mobilizes a manycast
678 * client association; a symmetric active packet mobilizes a
679 * symmetric passive association.
681 switch (retcode) {
684 * This is a client mode packet not matching any association. If
685 * an ordinary client, simply toss a server mode packet back
686 * over the fence. If a manycast client, we have to work a
687 * little harder.
689 case AM_FXMIT:
692 * The vanilla case is when this is not a multicast
693 * interface. If authentication succeeds, return a
694 * server mode packet; if not and the key ID is nonzero,
695 * return a crypto-NAK.
697 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
698 if (AUTH(restrict_mask & RES_DONTTRUST,
699 is_authentic))
700 fast_xmit(rbufp, MODE_SERVER, skeyid,
701 restrict_mask);
702 else if (is_authentic == AUTH_ERROR)
703 fast_xmit(rbufp, MODE_SERVER, 0,
704 restrict_mask);
705 return; /* hooray */
709 * This must be manycast. Do not respond if not
710 * configured as a manycast server.
712 if (!sys_manycastserver) {
713 sys_restricted++;
714 return; /* not enabled */
718 * Do not respond if unsynchronized or stratum is below
719 * the floor or at or above the ceiling.
721 if (sys_leap == LEAP_NOTINSYNC || sys_stratum <
722 sys_floor || sys_stratum >= sys_ceiling)
723 return; /* bad stratum */
726 * Do not respond if our stratum is greater than the
727 * manycaster or it has already synchronized to us.
729 if (sys_peer == NULL || hisstratum < sys_stratum ||
730 (sys_cohort && hisstratum == sys_stratum) ||
731 rbufp->dstadr->addr_refid == pkt->refid)
732 return; /* no help */
735 * Respond only if authentication succeeds. Don't do a
736 * crypto-NAK, as that would not be useful.
738 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
739 fast_xmit(rbufp, MODE_SERVER, skeyid,
740 restrict_mask);
742 return; /* hooray */
745 * This is a server mode packet returned in response to a client
746 * mode packet sent to a multicast group address. The origin
747 * timestamp is a good nonce to reliably associate the reply
748 * with what was sent. If there is no match, that's curious and
749 * could be an intruder attempting to clog, so we just ignore
750 * it.
752 * If the packet is authentic and the manycast association is
753 * found, we mobilize a client association and copy pertinent
754 * variables from the manycast association to the new client
755 * association. If not, just ignore the packet.
757 * There is an implosion hazard at the manycast client, since
758 * the manycast servers send the server packet immediately. If
759 * the guy is already here, don't fire up a duplicate.
761 case AM_MANYCAST:
762 if (!AUTH(sys_authenticate | (restrict_mask &
763 (RES_NOPEER | RES_DONTTRUST)), is_authentic))
764 return; /* bad auth */
766 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
767 sys_restricted++;
768 return; /* not enabled */
770 if ((peer = newpeer(&rbufp->recv_srcadr,
771 rbufp->dstadr, MODE_CLIENT,
772 hisversion, NTP_MINDPOLL, NTP_MAXDPOLL,
773 FLAG_IBURST | FLAG_PREEMPT, MDF_UCAST | MDF_ACLNT,
774 0, skeyid)) == NULL)
775 return; /* system error */
778 * We don't need these, but it warms the billboards.
780 peer->ttl = peer2->ttl;
781 break;
784 * This is the first packet received from a broadcast server. If
785 * the packet is authentic and we are enabled as broadcast
786 * client, mobilize a broadcast client association. We don't
787 * kiss any frogs here.
789 case AM_NEWBCL:
790 if (!AUTH(sys_authenticate | (restrict_mask &
791 (RES_NOPEER | RES_DONTTRUST)), is_authentic))
792 return; /* bad auth */
795 * Do not respond if unsynchronized or stratum is below
796 * the floor or at or above the ceiling.
798 if (hisleap == LEAP_NOTINSYNC || hisstratum <
799 sys_floor || hisstratum >= sys_ceiling)
800 return; /* bad stratum */
802 switch (sys_bclient) {
805 * If not enabled, just skedaddle.
807 case 0:
808 sys_restricted++;
809 return; /* not enabled */
812 * Execute the initial volley in order to calibrate the
813 * propagation delay and run the Autokey protocol, if
814 * enabled.
816 case 1:
817 if ((peer = newpeer(&rbufp->recv_srcadr,
818 rbufp->dstadr, MODE_CLIENT, hisversion,
819 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_MCAST |
820 FLAG_IBURST, MDF_BCLNT, 0, skeyid)) ==
821 NULL)
822 return; /* system error */
823 #ifdef OPENSSL
824 if (skeyid > NTP_MAXKEY)
825 crypto_recv(peer, rbufp);
826 #endif /* OPENSSL */
827 return; /* hooray */
831 * Do not execute the initial volley.
833 case 2:
834 #ifdef OPENSSL
836 * If a two-way exchange is not possible,
837 * neither is Autokey.
839 if (skeyid > NTP_MAXKEY) {
840 msyslog(LOG_INFO,
841 "receive: autokey requires two-way communication");
842 return; /* no autokey */
844 #endif /* OPENSSL */
845 if ((peer = newpeer(&rbufp->recv_srcadr,
846 rbufp->dstadr, MODE_BCLIENT, hisversion,
847 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_BCLNT, 0,
848 skeyid)) == NULL)
849 return; /* system error */
851 break;
854 * This is the first packet received from a symmetric active
855 * peer. If the packet is authentic and the first he sent,
856 * mobilize a passive association. If not, kiss the frog.
858 case AM_NEWPASS:
861 * If the inbound packet is correctly authenticated and
862 * enabled, a symmetric passive association is
863 * mobilized. If not but correctly authenticated, a
864 * symmetric active response is sent. If authentication
865 * fails, send a crypto-NAK packet.
867 if (!AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
869 if (is_authentic == AUTH_ERROR)
870 fast_xmit(rbufp, MODE_ACTIVE, 0,
871 restrict_mask);
872 return; /* bad auth */
874 if (!AUTH(sys_authenticate | (restrict_mask &
875 RES_NOPEER), is_authentic)) {
876 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
877 restrict_mask);
878 return; /* hooray */
882 * Do not respond if stratum is below the floor.
884 if (hisstratum < sys_floor)
885 return; /* bad stratum */
887 if ((peer = newpeer(&rbufp->recv_srcadr,
888 rbufp->dstadr, MODE_PASSIVE, hisversion,
889 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
890 skeyid)) == NULL)
891 return; /* system error */
892 break;
895 * Process regular packet. Nothing special.
897 case AM_PROCPKT:
898 break;
901 * A passive packet matches a passive association. This is
902 * usually the result of reconfiguring a client on the fly. As
903 * this association might be legitamate and this packet an
904 * attempt to deny service, just ignore it.
906 case AM_ERR:
907 return;
910 * For everything else there is the bit bucket.
912 default:
913 return;
915 peer->flash &= ~PKT_TEST_MASK;
918 * Next comes a rigorous schedule of timestamp checking. If the
919 * transmit timestamp is zero, the server is horribly broken.
921 if (L_ISZERO(&p_xmt)) {
922 return; /* read rfc1305 */
925 * If the transmit timestamp duplicates a previous one, the
926 * packet is a replay. This prevents the bad guys from replaying
927 * the most recent packet, authenticated or not.
929 } else if (L_ISEQU(&peer->org, &p_xmt)) {
930 peer->flash |= TEST1;
931 peer->oldpkt++;
932 return; /* duplicate packet */
936 * If this is a broadcast mode packet, skip further checking.
938 } else if (hismode != MODE_BROADCAST) {
939 if (L_ISZERO(&p_org))
940 peer->flash |= TEST3; /* protocol unsynch */
941 else if (!L_ISEQU(&p_org, &peer->xmt))
942 peer->flash |= TEST2; /* bogus packet */
946 * Update the origin and destination timestamps. If
947 * unsynchronized or bogus abandon ship. If the crypto machine
948 * breaks, light the crypto bit and plaint the log.
950 peer->org = p_xmt;
951 peer->rec = rbufp->recv_time;
952 if (peer->flash & PKT_TEST_MASK) {
953 #ifdef OPENSSL
954 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
955 rval = crypto_recv(peer, rbufp);
956 if (rval != XEVNT_OK) {
957 peer_clear(peer, "CRYP");
958 peer->flash |= TEST9; /* crypto error */
961 #endif /* OPENSSL */
962 return; /* unsynch */
966 * The timestamps are valid and the receive packet matches the
967 * last one sent. If the packet is a crypto-NAK, the server
968 * might have just changed keys. We reset the association
969 * and restart the protocol.
971 if (is_authentic == AUTH_CRYPTO) {
972 peer_clear(peer, "AUTH");
973 return; /* crypto-NAK */
976 * If the association is authenticated, the key ID is nonzero
977 * and received packets must be authenticated. This is designed
978 * to avoid a bait-and-switch attack, which was possible in past
979 * versions. If symmetric modes, return a crypto-NAK. The peer
980 * should restart the protocol.
982 } else if (!AUTH(peer->keyid || (restrict_mask & RES_DONTTRUST),
983 is_authentic)) {
984 peer->flash |= TEST5;
985 if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)
986 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
987 return; /* bad auth */
991 * That was hard and I am sweaty, but the packet is squeaky
992 * clean. Get on with real work.
994 peer->received++;
995 peer->timereceived = current_time;
996 if (is_authentic == AUTH_OK)
997 peer->flags |= FLAG_AUTHENTIC;
998 else
999 peer->flags &= ~FLAG_AUTHENTIC;
1000 #ifdef OPENSSL
1002 * More autokey dance. The rules of the cha-cha are as follows:
1004 * 1. If there is no key or the key is not auto, do nothing.
1006 * 2. If this packet is in response to the one just previously
1007 * sent or from a broadcast server, do the extension fields.
1008 * Otherwise, assume bogosity and bail out.
1010 * 3. If an extension field contains a verified signature, it is
1011 * self-authenticated and we sit the dance.
1013 * 4. If this is a server reply, check only to see that the
1014 * transmitted key ID matches the received key ID.
1016 * 5. Check to see that one or more hashes of the current key ID
1017 * matches the previous key ID or ultimate original key ID
1018 * obtained from the broadcaster or symmetric peer. If no
1019 * match, sit the dance and wait for timeout.
1021 * In case of crypto error, fire the orchestra and stop dancing.
1022 * This is considered a permanant error, so light the crypto bit
1023 * to suppress further requests. If preemptable or ephemeral,
1024 * scuttle the ship.
1026 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
1027 peer->flash |= TEST8;
1028 rval = crypto_recv(peer, rbufp);
1029 if (rval != XEVNT_OK) {
1030 peer_clear(peer, "CRYP");
1031 peer->flash |= TEST9; /* crypto error */
1032 if (peer->flags & FLAG_PREEMPT ||
1033 !(peer->flags & FLAG_CONFIG))
1034 unpeer(peer);
1035 return;
1037 } else if (hismode == MODE_SERVER) {
1038 if (skeyid == peer->keyid)
1039 peer->flash &= ~TEST8;
1040 } else if (!(peer->flash & TEST8)) {
1041 peer->pkeyid = skeyid;
1042 } else if ((ap = (struct autokey *)peer->recval.ptr) !=
1043 NULL) {
1044 int i;
1046 for (i = 0; ; i++) {
1047 if (tkeyid == peer->pkeyid ||
1048 tkeyid == ap->key) {
1049 peer->flash &= ~TEST8;
1050 peer->pkeyid = skeyid;
1051 break;
1053 if (i > ap->seq)
1054 break;
1055 tkeyid = session_key(
1056 &rbufp->recv_srcadr, dstadr_sin,
1057 tkeyid, pkeyid, 0);
1060 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
1061 peer->flash |= TEST8; /* not proventic */
1064 * If the transmit queue is nonempty, clamp the host
1065 * poll interval to the packet poll interval.
1067 if (peer->cmmd != 0) {
1068 peer->ppoll = pkt->ppoll;
1069 poll_update(peer, peer->hpoll);
1072 #endif /* OPENSSL */
1075 * The dance is complete and the flash bits have been lit. Toss
1076 * the packet over the fence for processing, which may light up
1077 * more flashers.
1079 process_packet(peer, pkt);
1082 * Well, that was nice. If TEST4 is lit, either the crypto
1083 * machine jammed or a kiss-o'-death packet flew in, either of
1084 * which is fatal.
1086 if (peer->flash & TEST4) {
1087 msyslog(LOG_INFO, "receive: fatal error %04x for %s",
1088 peer->flash, stoa(&peer->srcadr));
1089 return;
1095 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1096 * specification. Or almost, at least. If we're in here we have a
1097 * reasonable expectation that we will be having a long term
1098 * relationship with this host.
1100 void
1101 process_packet(
1102 register struct peer *peer,
1103 register struct pkt *pkt
1106 double t34, t21;
1107 double p_offset, p_del, p_disp;
1108 l_fp p_rec, p_xmt, p_org, p_reftime;
1109 l_fp ci;
1110 u_char pmode, pleap, pstratum;
1112 sys_processed++;
1113 peer->processed++;
1114 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1115 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
1116 NTOHL_FP(&pkt->reftime, &p_reftime);
1117 NTOHL_FP(&pkt->rec, &p_rec);
1118 NTOHL_FP(&pkt->xmt, &p_xmt);
1119 pmode = PKT_MODE(pkt->li_vn_mode);
1120 pleap = PKT_LEAP(pkt->li_vn_mode);
1121 if (pmode != MODE_BROADCAST)
1122 NTOHL_FP(&pkt->org, &p_org);
1123 else
1124 p_org = peer->rec;
1125 pstratum = PKT_TO_STRATUM(pkt->stratum);
1128 * Test for kiss-o'death packet)
1130 if (pleap == LEAP_NOTINSYNC && pstratum == STRATUM_UNSPEC) {
1131 if (memcmp(&pkt->refid, "DENY", 4) == 0) {
1132 peer_clear(peer, "DENY");
1133 peer->flash |= TEST4; /* access denied */
1138 * Capture the header values.
1140 record_raw_stats(&peer->srcadr, peer->dstadr ? &peer->dstadr->sin : NULL, &p_org,
1141 &p_rec, &p_xmt, &peer->rec);
1142 peer->leap = pleap;
1143 peer->stratum = min(pstratum, STRATUM_UNSPEC);
1144 peer->pmode = pmode;
1145 peer->ppoll = pkt->ppoll;
1146 peer->precision = pkt->precision;
1147 peer->rootdelay = p_del;
1148 peer->rootdispersion = p_disp;
1149 peer->refid = pkt->refid; /* network byte order */
1150 peer->reftime = p_reftime;
1153 * Verify the server is synchronized; that is, the leap bits and
1154 * stratum are valid, the root delay and root dispersion are
1155 * valid and the reference timestamp is not later than the
1156 * transmit timestamp.
1158 if (pleap == LEAP_NOTINSYNC || /* test 6 */
1159 pstratum < sys_floor || pstratum >= sys_ceiling)
1160 peer->flash |= TEST6; /* peer not synch */
1161 if (p_del < 0 || p_disp < 0 || p_del / /* test 7 */
1162 2 + p_disp >= MAXDISPERSE || !L_ISHIS(&p_xmt, &p_reftime))
1163 peer->flash |= TEST7; /* bad header */
1166 * If any tests fail at this point, the packet is discarded.
1167 * Note that some flashers may have already been set in the
1168 * receive() routine.
1170 if (peer->flash & PKT_TEST_MASK) {
1171 #ifdef DEBUG
1172 if (debug)
1173 printf("packet: flash header %04x\n",
1174 peer->flash);
1175 #endif
1176 return;
1178 if (!(peer->reach)) {
1179 report_event(EVNT_REACH, peer);
1180 peer->timereachable = current_time;
1182 poll_update(peer, peer->hpoll);
1183 peer->reach |= 1;
1186 * For a client/server association, calculate the clock offset,
1187 * roundtrip delay and dispersion. The equations are reordered
1188 * from the spec for more efficient use of temporaries. For a
1189 * broadcast association, offset the last measurement by the
1190 * computed delay during the client/server volley. Note that
1191 * org has been set to the time of last reception. Note the
1192 * computation of dispersion includes the system precision plus
1193 * that due to the frequency error since the origin time.
1195 * It is very important to respect the hazards of overflow. The
1196 * only permitted operation on raw timestamps is subtraction,
1197 * where the result is a signed quantity spanning from 68 years
1198 * in the past to 68 years in the future. To avoid loss of
1199 * precision, these calculations are done using 64-bit integer
1200 * arithmetic. However, the offset and delay calculations are
1201 * sums and differences of these first-order differences, which
1202 * if done using 64-bit integer arithmetic, would be valid over
1203 * only half that span. Since the typical first-order
1204 * differences are usually very small, they are converted to 64-
1205 * bit doubles and all remaining calculations done in floating-
1206 * point arithmetic. This preserves the accuracy while retaining
1207 * the 68-year span.
1209 * Let t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->rec:
1211 ci = p_xmt; /* t3 - t4 */
1212 L_SUB(&ci, &peer->rec);
1213 LFPTOD(&ci, t34);
1214 ci = p_rec; /* t2 - t1 */
1215 L_SUB(&ci, &p_org);
1216 LFPTOD(&ci, t21);
1217 ci = peer->rec; /* t4 - t1 */
1218 L_SUB(&ci, &p_org);
1221 * If running in a broadcast association, the clock offset is
1222 * (t1 - t0) corrected by the one-way delay, but we can't
1223 * measure that directly. Therefore, we start up in MODE_CLIENT
1224 * mode, set FLAG_MCAST and exchange eight messages to determine
1225 * the clock offset. When the last message is sent, we switch to
1226 * MODE_BCLIENT mode. The next broadcast message after that
1227 * computes the broadcast offset and clears FLAG_MCAST.
1229 if (pmode == MODE_BROADCAST) {
1230 p_offset = t34;
1231 if (peer->flags & FLAG_MCAST) {
1232 peer->estbdelay = peer->offset - p_offset;
1233 if (peer->hmode == MODE_CLIENT)
1234 return;
1236 peer->flags &= ~(FLAG_MCAST | FLAG_BURST);
1238 p_offset += peer->estbdelay;
1239 p_del = peer->delay;
1240 p_disp = 0;
1241 } else {
1242 p_offset = (t21 + t34) / 2.;
1243 p_del = t21 - t34;
1244 LFPTOD(&ci, p_disp);
1245 p_disp = LOGTOD(sys_precision) +
1246 LOGTOD(peer->precision) + clock_phi * p_disp;
1248 p_del = max(p_del, LOGTOD(sys_precision));
1249 clock_filter(peer, p_offset, p_del, p_disp);
1250 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1251 peer->offset, peer->delay, peer->disp, peer->jitter);
1256 * clock_update - Called at system process update intervals.
1258 static void
1259 clock_update(void)
1261 u_char oleap;
1262 u_char ostratum;
1263 double dtemp;
1266 * There must be a system peer at this point. If we just changed
1267 * the system peer, but have a newer sample from the old one,
1268 * wait until newer data are available.
1270 if (sys_poll < sys_peer->minpoll)
1271 sys_poll = sys_peer->minpoll;
1272 if (sys_poll > sys_peer->maxpoll)
1273 sys_poll = sys_peer->maxpoll;
1274 poll_update(sys_peer, sys_poll);
1275 if (sys_peer->epoch <= sys_clocktime)
1276 return;
1278 #ifdef DEBUG
1279 if (debug)
1280 printf("clock_update: at %ld assoc %d \n", current_time,
1281 peer_associations);
1282 #endif
1283 oleap = sys_leap;
1284 ostratum = sys_stratum;
1285 switch (local_clock(sys_peer, sys_offset)) {
1288 * Clock exceeds panic threshold. Life as we know it ends.
1290 case -1:
1291 report_event(EVNT_SYSFAULT, NULL);
1292 exit (-1);
1293 /* not reached */
1296 * Clock was stepped. Flush all time values of all peers.
1298 case 2:
1299 clear_all();
1300 sys_leap = LEAP_NOTINSYNC;
1301 sys_stratum = STRATUM_UNSPEC;
1302 sys_peer = NULL;
1303 sys_rootdelay = 0;
1304 sys_rootdispersion = 0;
1305 memcpy(&sys_refid, "STEP", 4);
1306 report_event(EVNT_CLOCKRESET, NULL);
1307 break;
1310 * Clock was slewed. Update the system stratum, leap bits, root
1311 * delay, root dispersion, reference ID and reference time. If
1312 * the leap changes, we gotta reroll the keys. Except for
1313 * reference clocks, the minimum dispersion increment is not
1314 * less than sys_mindisp.
1316 case 1:
1317 sys_leap = leap_next;
1318 sys_stratum = min(sys_peer->stratum + 1,
1319 STRATUM_UNSPEC);
1320 sys_reftime = sys_peer->rec;
1323 * In orphan mode the stratum defaults to the orphan
1324 * stratum. The root delay is set to a random value
1325 * generated at startup. The root dispersion is set from
1326 * the peer dispersion; the peer root dispersion is
1327 * ignored.
1329 dtemp = sys_peer->disp + clock_phi * (current_time -
1330 sys_peer->update) + sys_jitter +
1331 fabs(sys_peer->offset);
1332 #ifdef REFCLOCK
1333 if (!(sys_peer->flags & FLAG_REFCLOCK) && dtemp <
1334 sys_mindisp)
1335 dtemp = sys_mindisp;
1336 #else
1337 if (dtemp < sys_mindisp)
1338 dtemp = sys_mindisp;
1339 #endif /* REFCLOCK */
1340 if (sys_stratum >= sys_orphan) {
1341 sys_stratum = sys_orphan;
1342 sys_rootdelay = sys_peer->delay;
1343 sys_rootdispersion = dtemp;
1344 } else {
1345 sys_rootdelay = sys_peer->delay +
1346 sys_peer->rootdelay;
1347 sys_rootdispersion = dtemp +
1348 sys_peer->rootdispersion;
1350 if (oleap == LEAP_NOTINSYNC) {
1351 report_event(EVNT_SYNCCHG, NULL);
1352 #ifdef OPENSSL
1353 expire_all();
1354 crypto_update();
1355 #endif /* OPENSSL */
1357 break;
1359 * Popcorn spike or step threshold exceeded. Pretend it never
1360 * happened.
1362 default:
1363 break;
1365 if (ostratum != sys_stratum)
1366 report_event(EVNT_PEERSTCHG, NULL);
1371 * poll_update - update peer poll interval
1373 void
1374 poll_update(
1375 struct peer *peer,
1376 int mpoll
1379 int hpoll;
1382 * This routine figures out when the next poll should be sent.
1383 * That turns out to be wickedly complicated. The big problem is
1384 * that sometimes the time for the next poll is in the past.
1385 * Watch out for races here between the receive process and the
1386 * poll process. The key assertion is that, if nextdate equals
1387 * current_time, the call is from the poll process; otherwise,
1388 * it is from the receive process.
1390 * First, bracket the poll interval according to the type of
1391 * association and options. If a fixed interval is configured,
1392 * use minpoll. This primarily is for reference clocks, but
1393 * works for any association.
1395 if (peer->flags & FLAG_FIXPOLL) {
1396 hpoll = peer->minpoll;
1399 * The ordinary case; clamp the poll interval between minpoll
1400 * and maxpoll.
1402 } else {
1403 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
1405 #ifdef OPENSSL
1407 * Bit of crass arrogance at this point. If the poll interval
1408 * has changed and we have a keylist, the lifetimes in the
1409 * keylist are probably bogus. In this case purge the keylist
1410 * and regenerate it later.
1412 if (hpoll != peer->hpoll)
1413 key_expire(peer);
1414 #endif /* OPENSSL */
1415 peer->hpoll = hpoll;
1418 * Now we figure out if there is an override. If during the
1419 * crypto protocol and a message is pending, make it wait not
1420 * more than two seconds.
1422 #ifdef OPENSSL
1423 if (peer->cmmd != NULL && (sys_leap != LEAP_NOTINSYNC ||
1424 peer->crypto)) {
1425 peer->nextdate = current_time + RESP_DELAY;
1428 * If we get called from the receive routine while a burst is
1429 * pending, just slink away. If from the poll routine and a
1430 * reference clock or a pending crypto response, delay for one
1431 * second. If this is the first sent in a burst, wait for the
1432 * modem to come up. For others in the burst, delay two seconds.
1434 } else if (peer->burst > 0) {
1435 #else /* OPENSSL */
1436 if (peer->burst > 0) {
1437 #endif /* OPENSSL */
1438 if (peer->nextdate != current_time)
1439 return;
1440 #ifdef REFCLOCK
1441 else if (peer->flags & FLAG_REFCLOCK)
1442 peer->nextdate += RESP_DELAY;
1443 #endif /* REFCLOCK */
1444 else if (peer->flags & (FLAG_IBURST | FLAG_BURST) &&
1445 peer->burst == NTP_BURST)
1446 peer->nextdate += sys_calldelay;
1447 else
1448 peer->nextdate += BURST_DELAY;
1450 * The ordinary case; use the minimum of the host and peer
1451 * intervals, but not less than minpoll. In other words,
1452 * oversampling is okay but understampling is evil.
1454 } else {
1455 peer->nextdate = peer->outdate +
1456 RANDPOLL(max(min(peer->ppoll, hpoll),
1457 peer->minpoll));
1461 * If the time for the next poll has already happened, bring it
1462 * up to the next second after this one. This way the only way
1463 * to get nexdate == current time is from the poll routine.
1465 if (peer->nextdate <= current_time)
1466 peer->nextdate = current_time + 1;
1467 #ifdef DEBUG
1468 if (debug > 1)
1469 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1470 current_time, ntoa(&peer->srcadr), peer->flags,
1471 peer->hpoll, peer->burst, peer->outdate,
1472 peer->nextdate);
1473 #endif
1477 * peer_crypto_clear - discard crypto information
1479 void
1480 peer_crypto_clear(
1481 struct peer *peer
1485 * If cryptographic credentials have been acquired, toss them to
1486 * Valhalla. Note that autokeys are ephemeral, in that they are
1487 * tossed immediately upon use. Therefore, the keylist can be
1488 * purged anytime without needing to preserve random keys. Note
1489 * that, if the peer is purged, the cryptographic variables are
1490 * purged, too. This makes it much harder to sneak in some
1491 * unauthenticated data in the clock filter.
1493 DPRINTF(1, ("peer_crypto_clear: at %ld next %ld assoc ID %d\n",
1494 current_time, peer->nextdate, peer->associd));
1496 #ifdef OPENSSL
1497 peer->assoc = 0;
1498 peer->crypto = 0;
1500 if (peer->pkey != NULL)
1501 EVP_PKEY_free(peer->pkey);
1502 peer->pkey = NULL;
1504 peer->digest = NULL; /* XXX MEMLEAK? check whether this needs to be freed in any way - never was freed */
1506 if (peer->subject != NULL)
1507 free(peer->subject);
1508 peer->subject = NULL;
1510 if (peer->issuer != NULL)
1511 free(peer->issuer);
1512 peer->issuer = NULL;
1514 peer->pkeyid = 0;
1516 peer->pcookie = 0;
1518 if (peer->ident_pkey != NULL)
1519 EVP_PKEY_free(peer->ident_pkey);
1520 peer->ident_pkey = NULL;
1522 memset(&peer->fstamp, 0, sizeof(peer->fstamp));
1524 if (peer->iffval != NULL)
1525 BN_free(peer->iffval);
1526 peer->iffval = NULL;
1528 if (peer->grpkey != NULL)
1529 BN_free(peer->grpkey);
1530 peer->grpkey = NULL;
1532 value_free(&peer->cookval);
1533 value_free(&peer->recval);
1535 if (peer->cmmd != NULL) {
1536 free(peer->cmmd);
1537 peer->cmmd = NULL;
1540 key_expire(peer);
1542 value_free(&peer->encrypt);
1543 #endif /* OPENSSL */
1547 * peer_clear - clear peer filter registers. See Section 3.4.8 of the spec.
1549 void
1550 peer_clear(
1551 struct peer *peer, /* peer structure */
1552 char *ident /* tally lights */
1555 int i;
1557 peer_crypto_clear(peer);
1559 if (peer == sys_peer)
1560 sys_peer = NULL;
1563 * Wipe the association clean and initialize the nonzero values.
1565 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1566 peer->estbdelay = sys_bdelay;
1567 peer->ppoll = peer->maxpoll;
1568 peer->hpoll = peer->minpoll;
1569 peer->disp = MAXDISPERSE;
1570 peer->jitter = LOGTOD(sys_precision);
1571 for (i = 0; i < NTP_SHIFT; i++) {
1572 peer->filter_order[i] = i;
1573 peer->filter_disp[i] = MAXDISPERSE;
1575 #ifdef REFCLOCK
1576 if (!(peer->flags & FLAG_REFCLOCK)) {
1577 peer->leap = LEAP_NOTINSYNC;
1578 peer->stratum = STRATUM_UNSPEC;
1579 memcpy(&peer->refid, ident, 4);
1581 #else
1582 peer->leap = LEAP_NOTINSYNC;
1583 peer->stratum = STRATUM_UNSPEC;
1584 memcpy(&peer->refid, ident, 4);
1585 #endif /* REFCLOCK */
1588 * During initialization use the association count to spread out
1589 * the polls at one-second intervals. Othersie, randomize over
1590 * the minimum poll interval in order to avoid broadcast
1591 * implosion.
1593 peer->nextdate = peer->update = peer->outdate = current_time;
1594 if (initializing)
1595 peer->nextdate += peer_associations;
1596 else if (peer->hmode == MODE_PASSIVE)
1597 peer->nextdate += RESP_DELAY;
1598 else
1599 peer->nextdate += (ntp_random() & ((1 << NTP_MINDPOLL) -
1600 1));
1602 DPRINTF(1, ("peer_clear: at %ld next %ld assoc ID %d refid %s\n",
1603 current_time, peer->nextdate, peer->associd, ident));
1608 * clock_filter - add incoming clock sample to filter register and run
1609 * the filter procedure to find the best sample.
1611 void
1612 clock_filter(
1613 struct peer *peer, /* peer structure pointer */
1614 double sample_offset, /* clock offset */
1615 double sample_delay, /* roundtrip delay */
1616 double sample_disp /* dispersion */
1619 double dst[NTP_SHIFT]; /* distance vector */
1620 int ord[NTP_SHIFT]; /* index vector */
1621 int i, j, k, m;
1622 double dtemp, etemp;
1625 * Shift the new sample into the register and discard the oldest
1626 * one. The new offset and delay come directly from the
1627 * timestamp calculations. The dispersion grows from the last
1628 * outbound packet or reference clock update to the present time
1629 * and increased by the sum of the peer precision and the system
1630 * precision. The delay can sometimes swing negative due to
1631 * frequency skew, so it is clamped non-negative.
1633 j = peer->filter_nextpt;
1634 peer->filter_offset[j] = sample_offset;
1635 peer->filter_delay[j] = max(0, sample_delay);
1636 peer->filter_disp[j] = sample_disp;
1637 peer->filter_epoch[j] = current_time;
1638 j = (j + 1) % NTP_SHIFT;
1639 peer->filter_nextpt = j;
1642 * Update dispersions since the last update and at the same
1643 * time initialize the distance and index lists. The distance
1644 * list uses a compound metric. If the sample is valid and
1645 * younger than the minimum Allan intercept, use delay;
1646 * otherwise, use biased dispersion.
1648 dtemp = clock_phi * (current_time - peer->update);
1649 peer->update = current_time;
1650 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1651 if (i != 0)
1652 peer->filter_disp[j] += dtemp;
1653 if (peer->filter_disp[j] >= MAXDISPERSE)
1654 peer->filter_disp[j] = MAXDISPERSE;
1655 if (peer->filter_disp[j] >= MAXDISPERSE)
1656 dst[i] = MAXDISPERSE;
1657 else if (peer->update - peer->filter_epoch[j] >
1658 allan_xpt)
1659 dst[i] = sys_maxdist + peer->filter_disp[j];
1660 else
1661 dst[i] = peer->filter_delay[j];
1662 ord[i] = j;
1663 j++; j %= NTP_SHIFT;
1667 * If the clock discipline has stabilized, sort the samples in
1668 * both lists by distance. Note, we do not displace a higher
1669 * distance sample by a lower distance one unless lower by at
1670 * least the precision.
1672 if (state == 4) {
1673 for (i = 1; i < NTP_SHIFT; i++) {
1674 for (j = 0; j < i; j++) {
1675 if (dst[j] > dst[i] +
1676 LOGTOD(sys_precision)) {
1677 k = ord[j];
1678 ord[j] = ord[i];
1679 ord[i] = k;
1680 etemp = dst[j];
1681 dst[j] = dst[i];
1682 dst[i] = etemp;
1689 * Copy the index list to the association structure so ntpq
1690 * can see it later. Prune the distance list to samples less
1691 * than max distance, but keep at least two valid samples for
1692 * jitter calculation.
1694 m = 0;
1695 for (i = 0; i < NTP_SHIFT; i++) {
1696 peer->filter_order[i] = (u_char) ord[i];
1697 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1698 sys_maxdist))
1699 continue;
1700 m++;
1704 * Compute the dispersion and jitter. The dispersion is weighted
1705 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
1706 * to 1.0. The jitter is the RMS differences relative to the
1707 * lowest delay sample. If no acceptable samples remain in the
1708 * shift register, quietly tiptoe home leaving only the
1709 * dispersion.
1711 peer->disp = peer->jitter = 0;
1712 k = ord[0];
1713 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1714 j = ord[i];
1715 peer->disp = NTP_FWEIGHT * (peer->disp +
1716 peer->filter_disp[j]);
1717 if (i < m)
1718 peer->jitter += DIFF(peer->filter_offset[j],
1719 peer->filter_offset[k]);
1723 * If no acceptable samples remain in the shift register,
1724 * quietly tiptoe home leaving only the dispersion. Otherwise,
1725 * save the offset, delay and jitter. Note the jitter must not
1726 * be less than the precision.
1728 if (m == 0)
1729 return;
1731 etemp = fabs(peer->offset - peer->filter_offset[k]);
1732 peer->offset = peer->filter_offset[k];
1733 peer->delay = peer->filter_delay[k];
1734 if (m > 1)
1735 peer->jitter /= m - 1;
1736 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
1739 * A new sample is useful only if it is younger than the last
1740 * one used. Note the order is FIFO if the clock discipline has
1741 * not stabilized.
1743 if (peer->filter_epoch[k] <= peer->epoch) {
1744 #ifdef DEBUG
1745 if (debug)
1746 printf("clock_filter: discard %lu\n",
1747 peer->epoch - peer->filter_epoch[k]);
1748 #endif
1749 return;
1753 * If the difference between the last offset and the current one
1754 * exceeds the jitter by CLOCK_SGATE and the interval since the
1755 * last update is less than twice the system poll interval,
1756 * consider the update a popcorn spike and ignore it.
1758 if (etemp > CLOCK_SGATE * peer->jitter && m > 1 &&
1759 peer->filter_epoch[k] - peer->epoch < 2. *
1760 ULOGTOD(sys_poll)) {
1761 #ifdef DEBUG
1762 if (debug)
1763 printf("clock_filter: popcorn %.6f %.6f\n",
1764 etemp, dtemp);
1765 #endif
1766 return;
1770 * The mitigated sample statistics are saved for later
1771 * processing. If not in a burst, tickle the select.
1773 peer->epoch = peer->filter_epoch[k];
1774 #ifdef DEBUG
1775 if (debug)
1776 printf(
1777 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1778 m, peer->offset, peer->delay, peer->disp,
1779 peer->jitter, current_time - peer->epoch);
1780 #endif
1781 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
1782 clock_select();
1787 * clock_select - find the pick-of-the-litter clock
1789 * LOCKCLOCK: If the local clock is the prefer peer, it will always be
1790 * enabled, even if declared falseticker, (2) only the prefer peer can
1791 * be selected as the system peer, (3) if the external source is down,
1792 * the system leap bits are set to 11 and the stratum set to infinity.
1794 void
1795 clock_select(void)
1797 struct peer *peer;
1798 int i, j, k, n;
1799 int nlist, nl3;
1801 int allow, osurv;
1802 double d, e, f, g;
1803 double high, low;
1804 double synch[NTP_MAXASSOC], error[NTP_MAXASSOC];
1805 struct peer *osys_peer;
1806 struct peer *typeacts = NULL;
1807 struct peer *typelocal = NULL;
1808 struct peer *typesystem = NULL;
1810 static int list_alloc = 0;
1811 static struct endpoint *endpoint = NULL;
1812 static int *indx = NULL;
1813 static struct peer **peer_list = NULL;
1814 static u_int endpoint_size = 0;
1815 static u_int indx_size = 0;
1816 static u_int peer_list_size = 0;
1819 * Initialize and create endpoint, index and peer lists big
1820 * enough to handle all associations.
1822 osys_peer = sys_peer;
1823 sys_peer = NULL;
1824 sys_pps = NULL;
1825 sys_prefer = NULL;
1826 osurv = sys_survivors;
1827 sys_survivors = 0;
1828 #ifdef LOCKCLOCK
1829 sys_leap = LEAP_NOTINSYNC;
1830 sys_stratum = STRATUM_UNSPEC;
1831 memcpy(&sys_refid, "DOWN", 4);
1832 #endif /* LOCKCLOCK */
1833 nlist = 0;
1834 for (n = 0; n < NTP_HASH_SIZE; n++)
1835 nlist += peer_hash_count[n];
1836 if (nlist > list_alloc) {
1837 if (list_alloc > 0) {
1838 free(endpoint);
1839 free(indx);
1840 free(peer_list);
1842 while (list_alloc < nlist) {
1843 list_alloc += 5;
1844 endpoint_size += 5 * 3 * sizeof(*endpoint);
1845 indx_size += 5 * 3 * sizeof(*indx);
1846 peer_list_size += 5 * sizeof(*peer_list);
1848 endpoint = (struct endpoint *)emalloc(endpoint_size);
1849 indx = (int *)emalloc(indx_size);
1850 peer_list = (struct peer **)emalloc(peer_list_size);
1854 * Initially, we populate the island with all the rifraff peers
1855 * that happen to be lying around. Those with seriously
1856 * defective clocks are immediately booted off the island. Then,
1857 * the falsetickers are culled and put to sea. The truechimers
1858 * remaining are subject to repeated rounds where the most
1859 * unpopular at each round is kicked off. When the population
1860 * has dwindled to sys_minclock, the survivors split a million
1861 * bucks and collectively crank the chimes.
1863 nlist = nl3 = 0; /* none yet */
1864 for (n = 0; n < NTP_HASH_SIZE; n++) {
1865 for (peer = peer_hash[n]; peer != NULL; peer =
1866 peer->next) {
1867 peer->flags &= ~FLAG_SYSPEER;
1868 peer->status = CTL_PST_SEL_REJECT;
1871 * Leave the island immediately if the peer is
1872 * unfit to synchronize.
1874 if (peer_unfit(peer))
1875 continue;
1878 * Don't allow the local clock or modem drivers
1879 * in the kitchen at this point, unless the
1880 * prefer peer. Do that later, but only if
1881 * nobody else is around. These guys are all
1882 * configured, so we never throw them away.
1884 #ifdef REFCLOCK
1885 if (peer->refclktype == REFCLK_LOCALCLOCK
1886 #if defined(VMS) && defined(VMS_LOCALUNIT)
1887 /* wjm: VMS_LOCALUNIT taken seriously */
1888 && REFCLOCKUNIT(&peer->srcadr) !=
1889 VMS_LOCALUNIT
1890 #endif /* VMS && VMS_LOCALUNIT */
1892 typelocal = peer;
1893 #ifndef LOCKCLOCK
1894 if (!(peer->flags & FLAG_PREFER))
1895 continue; /* no local clock */
1896 #endif /* LOCKCLOCK */
1898 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1899 typeacts = peer;
1900 if (!(peer->flags & FLAG_PREFER))
1901 continue; /* no acts */
1903 #endif /* REFCLOCK */
1906 * If we get this far, the peer can stay on the
1907 * island, but does not yet have the immunity
1908 * idol.
1910 peer->status = CTL_PST_SEL_SANE;
1911 peer_list[nlist++] = peer;
1914 * Insert each interval endpoint on the sorted
1915 * list.
1917 e = peer->offset; /* Upper end */
1918 f = root_distance(peer);
1919 e = e + f;
1920 for (i = nl3 - 1; i >= 0; i--) {
1921 if (e >= endpoint[indx[i]].val)
1922 break;
1924 indx[i + 3] = indx[i];
1926 indx[i + 3] = nl3;
1927 endpoint[nl3].type = 1;
1928 endpoint[nl3++].val = e;
1930 e = e - f; /* Center point */
1931 for (; i >= 0; i--) {
1932 if (e >= endpoint[indx[i]].val)
1933 break;
1935 indx[i + 2] = indx[i];
1937 indx[i + 2] = nl3;
1938 endpoint[nl3].type = 0;
1939 endpoint[nl3++].val = e;
1941 e = e - f; /* Lower end */
1942 for (; i >= 0; i--) {
1943 if (e >= endpoint[indx[i]].val)
1944 break;
1946 indx[i + 1] = indx[i];
1948 indx[i + 1] = nl3;
1949 endpoint[nl3].type = -1;
1950 endpoint[nl3++].val = e;
1953 #ifdef DEBUG
1954 if (debug > 2)
1955 for (i = 0; i < nl3; i++)
1956 printf("select: endpoint %2d %.6f\n",
1957 endpoint[indx[i]].type,
1958 endpoint[indx[i]].val);
1959 #endif
1961 * This is the actual algorithm that cleaves the truechimers
1962 * from the falsetickers. The original algorithm was described
1963 * in Keith Marzullo's dissertation, but has been modified for
1964 * better accuracy.
1966 * Briefly put, we first assume there are no falsetickers, then
1967 * scan the candidate list first from the low end upwards and
1968 * then from the high end downwards. The scans stop when the
1969 * number of intersections equals the number of candidates less
1970 * the number of falsetickers. If this doesn't happen for a
1971 * given number of falsetickers, we bump the number of
1972 * falsetickers and try again. If the number of falsetickers
1973 * becomes equal to or greater than half the number of
1974 * candidates, the Albanians have won the Byzantine wars and
1975 * correct synchronization is not possible.
1977 * Here, nlist is the number of candidates and allow is the
1978 * number of falsetickers. Upon exit, the truechimers are the
1979 * susvivors with offsets not less than low and not greater than
1980 * high. There may be none of them.
1982 low = 1e9;
1983 high = -1e9;
1984 for (allow = 0; 2 * allow < nlist; allow++) {
1985 int found;
1988 * Bound the interval (low, high) as the largest
1989 * interval containing points from presumed truechimers.
1991 found = 0;
1992 n = 0;
1993 for (i = 0; i < nl3; i++) {
1994 low = endpoint[indx[i]].val;
1995 n -= endpoint[indx[i]].type;
1996 if (n >= nlist - allow)
1997 break;
1998 if (endpoint[indx[i]].type == 0)
1999 found++;
2001 n = 0;
2002 for (j = nl3 - 1; j >= 0; j--) {
2003 high = endpoint[indx[j]].val;
2004 n += endpoint[indx[j]].type;
2005 if (n >= nlist - allow)
2006 break;
2007 if (endpoint[indx[j]].type == 0)
2008 found++;
2012 * If the number of candidates found outside the
2013 * interval is greater than the number of falsetickers,
2014 * then at least one truechimer is outside the interval,
2015 * so go around again. This is what makes this algorithm
2016 * different than Marzullo's.
2018 if (found > allow)
2019 continue;
2022 * If an interval containing truechimers is found, stop.
2023 * If not, increase the number of falsetickers and go
2024 * around again.
2026 if (high > low)
2027 break;
2031 * Clustering algorithm. Construct candidate list in order first
2032 * by stratum then by root distance, but keep only the best
2033 * NTP_MAXASSOC of them. Scan the list to find falsetickers, who
2034 * leave the island immediately. The TRUE peer is always a
2035 * truechimer. We must leave at least one peer to collect the
2036 * million bucks. If in orphan mode, rascals found with lower
2037 * stratum are guaranteed a seat on the bus.
2039 j = 0;
2040 for (i = 0; i < nlist; i++) {
2041 peer = peer_list[i];
2042 if (nlist > 1 && (peer->offset <= low || peer->offset >=
2043 high) && !(peer->flags & FLAG_TRUE) &&
2044 !(sys_stratum >= sys_orphan && peer->stratum <
2045 sys_orphan))
2046 continue;
2048 peer->status = CTL_PST_SEL_DISTSYSPEER;
2051 * The order metric is formed from the stratum times
2052 * max distance (1.) plus the root distance. It strongly
2053 * favors the lowest stratum, but a higher stratum peer
2054 * can capture the clock if the low stratum dominant
2055 * hasn't been heard for awhile.
2057 d = root_distance(peer) + peer->stratum * sys_maxdist;
2058 if (j >= NTP_MAXASSOC) {
2059 if (d >= synch[j - 1])
2060 continue;
2061 else
2062 j--;
2064 for (k = j; k > 0; k--) {
2065 if (d >= synch[k - 1])
2066 break;
2068 peer_list[k] = peer_list[k - 1];
2069 error[k] = error[k - 1];
2070 synch[k] = synch[k - 1];
2072 peer_list[k] = peer;
2073 error[k] = peer->jitter;
2074 synch[k] = d;
2075 j++;
2077 nlist = j;
2080 * If no survivors remain at this point, check if the local
2081 * clock or modem drivers have been found. If so, nominate one
2082 * of them as the only survivor. Otherwise, give up and leave
2083 * the island to the rats.
2085 if (nlist == 0) {
2086 if (typeacts != 0) {
2087 typeacts->status = CTL_PST_SEL_DISTSYSPEER;
2088 peer_list[0] = typeacts;
2089 nlist = 1;
2090 } else if (typelocal != 0) {
2091 typelocal->status = CTL_PST_SEL_DISTSYSPEER;
2092 peer_list[0] = typelocal;
2093 nlist = 1;
2094 } else {
2095 if (osys_peer != NULL) {
2096 NLOG(NLOG_SYNCSTATUS)
2097 msyslog(LOG_INFO,
2098 "no servers reachable");
2099 report_event(EVNT_PEERSTCHG, NULL);
2105 * We can only trust the survivors if the number of candidates
2106 * sys_minsane is at least the number required to detect and
2107 * cast out one falsticker. For the Byzantine agreement
2108 * algorithm used here, that number is 4; however, the default
2109 * sys_minsane is 1 to speed initial synchronization. Careful
2110 * operators will tinker a higher value and use at least that
2111 * number of synchronization sources.
2113 if (nlist < sys_minsane)
2114 return;
2116 for (i = 0; i < nlist; i++)
2117 peer_list[i]->status = CTL_PST_SEL_SELCAND;
2120 * Now, vote outlyers off the island by select jitter weighted
2121 * by root distance. Continue voting as long as there are more
2122 * than sys_minclock survivors and the minimum select jitter is
2123 * greater than the maximum peer jitter. Stop if we are about to
2124 * discard a TRUE or PREFER peer, who of course has the
2125 * immunity idol.
2127 while (1) {
2128 d = 1e9;
2129 e = -1e9;
2130 f = g = 0;
2131 k = 0;
2132 for (i = 0; i < nlist; i++) {
2133 if (error[i] < d)
2134 d = error[i];
2135 f = 0;
2136 if (nlist > 1) {
2137 for (j = 0; j < nlist; j++)
2138 f += DIFF(peer_list[j]->offset,
2139 peer_list[i]->offset);
2140 f = SQRT(f / (nlist - 1));
2142 if (f * synch[i] > e) {
2143 g = f;
2144 e = f * synch[i];
2145 k = i;
2148 f = max(f, LOGTOD(sys_precision));
2149 if (nlist <= sys_minclock || f <= d ||
2150 peer_list[k]->flags & (FLAG_TRUE | FLAG_PREFER))
2151 break;
2152 #ifdef DEBUG
2153 if (debug > 2)
2154 printf(
2155 "select: drop %s select %.6f jitter %.6f\n",
2156 ntoa(&peer_list[k]->srcadr), g, d);
2157 #endif
2158 for (j = k + 1; j < nlist; j++) {
2159 peer_list[j - 1] = peer_list[j];
2160 error[j - 1] = error[j];
2162 nlist--;
2166 * What remains is a list usually not greater than sys_minclock
2167 * peers. We want only a peer at the lowest stratum to become
2168 * the system peer, although all survivors are eligible for the
2169 * combining algorithm. Consider each peer in turn and OR the
2170 * leap bits on the assumption that, if some of them honk
2171 * nonzero bits, they must know what they are doing. Check for
2172 * prefer and pps peers at any stratum. Note that the head of
2173 * the list is at the lowest stratum and that unsynchronized
2174 * peers cannot survive this far.
2176 leap_next = 0;
2177 for (i = 0; i < nlist; i++) {
2178 peer = peer_list[i];
2179 sys_survivors++;
2180 leap_next |= peer->leap;
2181 peer->status = CTL_PST_SEL_SYNCCAND;
2182 if (peer->flags & FLAG_PREFER)
2183 sys_prefer = peer;
2184 if (peer == osys_peer)
2185 typesystem = peer;
2186 #ifdef REFCLOCK
2187 if (peer->refclktype == REFCLK_ATOM_PPS)
2188 sys_pps = peer;
2189 #endif /* REFCLOCK */
2190 #if DEBUG
2191 if (debug > 1)
2192 printf("cluster: survivor %s metric %.6f\n",
2193 ntoa(&peer_list[i]->srcadr), synch[i]);
2194 #endif
2198 * Anticlockhop provision. Keep the current system peer if it is
2199 * a survivor but not first in the list. But do that only HOPPER
2200 * times.
2202 if (osys_peer == NULL || typesystem == NULL || typesystem ==
2203 peer_list[0] || sys_hopper > sys_maxhop) {
2204 typesystem = peer_list[0];
2205 sys_hopper = 0;
2206 } else {
2207 peer->selbroken++;
2211 * Mitigation rules of the game. There are several types of
2212 * peers that can be selected here: (1) orphan, (2) prefer peer
2213 * (flag FLAG_PREFER) (3) pps peers (type REFCLK_ATOM_PPS), (4)
2214 * the existing system peer, if any, and (5) the head of the
2215 * survivor list.
2217 if (typesystem->stratum >= sys_orphan) {
2220 * If in orphan mode, choose the system peer. If the
2221 * lowest distance, we are the orphan parent and the
2222 * offset is zero.
2224 sys_peer = typesystem;
2225 sys_peer->status = CTL_PST_SEL_SYSPEER;
2226 if (sys_orphandelay < sys_peer->rootdelay) {
2227 sys_offset = 0;
2228 sys_refid = htonl(LOOPBACKADR);
2229 } else {
2230 sys_offset = sys_peer->offset;
2231 sys_refid = addr2refid(&sys_peer->srcadr);
2233 sys_jitter = LOGTOD(sys_precision);
2234 #ifdef DEBUG
2235 if (debug > 1)
2236 printf("select: orphan offset %.6f\n",
2237 sys_offset);
2238 #endif
2239 } else if (sys_prefer) {
2242 * If a pps peer is present, choose it; otherwise,
2243 * choose the prefer peer.
2245 if (sys_pps) {
2246 sys_peer = sys_pps;
2247 sys_peer->status = CTL_PST_SEL_PPS;
2248 sys_offset = sys_peer->offset;
2249 if (!pps_control)
2250 NLOG(NLOG_SYSEVENT)
2251 msyslog(LOG_INFO,
2252 "pps sync enabled");
2253 pps_control = current_time;
2254 #ifdef DEBUG
2255 if (debug > 1)
2256 printf("select: pps offset %.6f\n",
2257 sys_offset);
2258 #endif
2259 } else {
2260 sys_peer = sys_prefer;
2261 sys_peer->status = CTL_PST_SEL_SYSPEER;
2262 sys_offset = sys_peer->offset;
2263 #ifdef DEBUG
2264 if (debug > 1)
2265 printf("select: prefer offset %.6f\n",
2266 sys_offset);
2267 #endif
2269 if (sys_peer->stratum == STRATUM_REFCLOCK ||
2270 sys_peer->stratum == STRATUM_UNSPEC)
2271 sys_refid = sys_peer->refid;
2272 else
2273 sys_refid = addr2refid(&sys_peer->srcadr);
2274 sys_jitter = sys_peer->jitter;
2275 } else {
2278 * Otherwise, choose the anticlockhopper.
2280 sys_peer = typesystem;
2281 sys_peer->status = CTL_PST_SEL_SYSPEER;
2282 clock_combine(peer_list, nlist);
2283 if (sys_peer->stratum == STRATUM_REFCLOCK ||
2284 sys_peer->stratum == STRATUM_UNSPEC)
2285 sys_refid = sys_peer->refid;
2286 else
2287 sys_refid = addr2refid(&sys_peer->srcadr);
2288 sys_jitter = SQRT(SQUARE(sys_peer->jitter) +
2289 SQUARE(sys_jitter));
2290 #ifdef DEBUG
2291 if (debug > 1)
2292 printf("select: combine offset %.6f\n",
2293 sys_offset);
2294 #endif
2298 * We have found the alpha male.
2300 sys_peer->flags |= FLAG_SYSPEER;
2301 if (osys_peer != sys_peer) {
2302 char *src;
2304 report_event(EVNT_PEERSTCHG, NULL);
2306 #ifdef REFCLOCK
2307 if (sys_peer->flags & FLAG_REFCLOCK)
2308 src = refnumtoa(&sys_peer->srcadr);
2309 else
2310 #endif /* REFCLOCK */
2311 src = ntoa(&sys_peer->srcadr);
2312 NLOG(NLOG_SYNCSTATUS)
2313 msyslog(LOG_INFO, "synchronized to %s, stratum %d",
2314 src, sys_peer->stratum);
2316 clock_update();
2321 * clock_combine - compute system offset and jitter from selected peers
2323 static void
2324 clock_combine(
2325 struct peer **peers, /* survivor list */
2326 int npeers /* number of survivors */
2329 int i;
2330 double x, y, z, w;
2332 y = z = w = 0;
2333 for (i = 0; i < npeers; i++) {
2334 x = root_distance(peers[i]);
2335 y += 1. / x;
2336 z += peers[i]->offset / x;
2337 w += SQUARE(peers[i]->offset - peers[0]->offset) / x;
2339 sys_offset = z / y;
2340 sys_jitter = SQRT(w / y);
2344 * root_distance - compute synchronization distance from peer to root
2346 static double
2347 root_distance(
2348 struct peer *peer
2351 double dist;
2354 * Careful squeak here. The value returned must be greater than
2355 * the minimum root dispersion in order to avoid clockhop with
2356 * highly precise reference clocks. In orphan mode lose the peer
2357 * root delay, as that is used by the election algorithm.
2359 if (peer->stratum >= sys_orphan)
2360 dist = 0;
2361 else
2362 dist = peer->rootdelay;
2363 dist += max(sys_mindisp, dist + peer->delay) / 2 +
2364 peer->rootdispersion + peer->disp + clock_phi *
2365 (current_time - peer->update) + peer->jitter;
2366 return (dist);
2370 * peer_xmit - send packet for persistent association.
2372 static void
2373 peer_xmit(
2374 struct peer *peer /* peer structure pointer */
2377 struct pkt xpkt; /* transmit packet */
2378 int sendlen, authlen;
2379 keyid_t xkeyid = 0; /* transmit key ID */
2380 l_fp xmt_tx;
2382 if (!peer->dstadr) /* don't bother with peers without interface */
2383 return;
2386 * This is deliciously complicated. There are three cases.
2388 * case leap stratum refid delay dispersion
2390 * normal system system system system system
2391 * orphan child 00 orphan system orphan system
2392 * orphan parent 00 orphan loopbk 0 0
2395 * This is a normal packet. Use the system variables.
2397 if (sys_stratum < sys_orphan) {
2398 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2399 peer->version, peer->hmode);
2400 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2401 xpkt.refid = sys_refid;
2402 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2403 xpkt.rootdispersion =
2404 HTONS_FP(DTOUFP(sys_rootdispersion));
2407 * This is a orphan child packet. The host is synchronized to an
2408 * orphan parent. Show leap synchronized, orphan stratum, system
2409 * reference ID, orphan root delay and system root dispersion.
2411 } else if (sys_peer != NULL) {
2412 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2413 peer->version, peer->hmode);
2414 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2415 xpkt.refid = htonl(LOOPBACKADR);
2416 xpkt.rootdelay = HTONS_FP(DTOFP(sys_orphandelay));
2417 xpkt.rootdispersion =
2418 HTONS_FP(DTOUFP(sys_rootdispersion));
2421 * This is an orphan parent. Show leap synchronized, orphan
2422 * stratum, loopack reference ID and zero root delay and root
2423 * dispersion.
2425 } else {
2426 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2427 peer->version, peer->hmode);
2428 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2429 xpkt.refid = sys_refid;
2430 xpkt.rootdelay = 0;
2431 xpkt.rootdispersion = 0;
2433 xpkt.ppoll = peer->hpoll;
2434 xpkt.precision = sys_precision;
2435 HTONL_FP(&sys_reftime, &xpkt.reftime);
2436 HTONL_FP(&peer->org, &xpkt.org);
2437 HTONL_FP(&peer->rec, &xpkt.rec);
2440 * If the received packet contains a MAC, the transmitted packet
2441 * is authenticated and contains a MAC. If not, the transmitted
2442 * packet is not authenticated.
2444 * It is most important when autokey is in use that the local
2445 * interface IP address be known before the first packet is
2446 * sent. Otherwise, it is not possible to compute a correct MAC
2447 * the recipient will accept. Thus, the I/O semantics have to do
2448 * a little more work. In particular, the wildcard interface
2449 * might not be usable.
2451 sendlen = LEN_PKT_NOMAC;
2452 if (!(peer->flags & FLAG_AUTHENABLE)) {
2453 get_systime(&peer->xmt);
2454 HTONL_FP(&peer->xmt, &xpkt.xmt);
2455 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2456 &xpkt, sendlen);
2457 peer->sent++;
2458 #ifdef DEBUG
2459 if (debug)
2460 printf("transmit: at %ld %s->%s mode %d\n",
2461 current_time, peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
2462 stoa(&peer->srcadr), peer->hmode);
2463 #endif
2464 return;
2468 * The received packet contains a MAC, so the transmitted packet
2469 * must be authenticated. If autokey is enabled, fuss with the
2470 * various modes; otherwise, symmetric key cryptography is used.
2472 #ifdef OPENSSL
2473 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
2474 struct exten *exten; /* extension field */
2477 * The Public Key Dance (PKD): Cryptographic credentials
2478 * are contained in extension fields, each including a
2479 * 4-octet length/code word followed by a 4-octet
2480 * association ID and optional additional data. Optional
2481 * data includes a 4-octet data length field followed by
2482 * the data itself. Request messages are sent from a
2483 * configured association; response messages can be sent
2484 * from a configured association or can take the fast
2485 * path without ever matching an association. Response
2486 * messages have the same code as the request, but have
2487 * a response bit and possibly an error bit set. In this
2488 * implementation, a message may contain no more than
2489 * one command and no more than one response.
2491 * Cryptographic session keys include both a public and
2492 * a private componet. Request and response messages
2493 * using extension fields are always sent with the
2494 * private component set to zero. Packets without
2495 * extension fields indlude the private component when
2496 * the session key is generated.
2498 while (1) {
2501 * Allocate and initialize a keylist if not
2502 * already done. Then, use the list in inverse
2503 * order, discarding keys once used. Keep the
2504 * latest key around until the next one, so
2505 * clients can use client/server packets to
2506 * compute propagation delay.
2508 * Note that once a key is used from the list,
2509 * it is retained in the key cache until the
2510 * next key is used. This is to allow a client
2511 * to retrieve the encrypted session key
2512 * identifier to verify authenticity.
2514 * If for some reason a key is no longer in the
2515 * key cache, a birthday has happened and the
2516 * pseudo-random sequence is probably broken. In
2517 * that case, purge the keylist and regenerate
2518 * it.
2520 if (peer->keynumber == 0)
2521 make_keylist(peer, peer->dstadr);
2522 else
2523 peer->keynumber--;
2524 xkeyid = peer->keylist[peer->keynumber];
2525 if (authistrusted(xkeyid))
2526 break;
2527 else
2528 key_expire(peer);
2530 peer->keyid = xkeyid;
2531 exten = NULL;
2532 switch (peer->hmode) {
2535 * In broadcast server mode the autokey values are
2536 * required by the broadcast clients. Push them when a
2537 * new keylist is generated; otherwise, push the
2538 * association message so the client can request them at
2539 * other times.
2541 case MODE_BROADCAST:
2542 if (peer->flags & FLAG_ASSOC)
2543 exten = crypto_args(peer, CRYPTO_AUTO |
2544 CRYPTO_RESP, NULL);
2545 else
2546 exten = crypto_args(peer, CRYPTO_ASSOC |
2547 CRYPTO_RESP, NULL);
2548 break;
2551 * In symmetric modes the digest, certificate, agreement
2552 * parameters, cookie and autokey values are required.
2553 * The leapsecond table is optional. But, a passive peer
2554 * will not believe the active peer until the latter has
2555 * synchronized, so the agreement must be postponed
2556 * until then. In any case, if a new keylist is
2557 * generated, the autokey values are pushed.
2559 * If the crypto bit is lit, don't send requests.
2561 case MODE_ACTIVE:
2562 case MODE_PASSIVE:
2563 if (peer->flash & TEST9)
2564 break;
2566 * Parameter and certificate.
2568 if (!peer->crypto)
2569 exten = crypto_args(peer, CRYPTO_ASSOC,
2570 sys_hostname);
2571 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2572 exten = crypto_args(peer, CRYPTO_CERT,
2573 peer->issuer);
2576 * Identity. Note we have to sign the
2577 * certificate before the cookie to avoid a
2578 * deadlock when the passive peer is walking the
2579 * certificate trail. Awesome.
2581 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2582 exten = crypto_args(peer,
2583 crypto_ident(peer), NULL);
2584 else if (sys_leap != LEAP_NOTINSYNC &&
2585 !(peer->crypto & CRYPTO_FLAG_SIGN))
2586 exten = crypto_args(peer, CRYPTO_SIGN,
2587 sys_hostname);
2590 * Autokey. We request the cookie only when the
2591 * server and client are synchronized and
2592 * signatures work both ways. On the other hand,
2593 * the active peer needs the autokey values
2594 * before then and when the passive peer is
2595 * waiting for the active peer to synchronize.
2596 * Any time we regenerate the key list, we offer
2597 * the autokey values without being asked.
2599 else if (sys_leap != LEAP_NOTINSYNC &&
2600 peer->leap != LEAP_NOTINSYNC &&
2601 !(peer->crypto & CRYPTO_FLAG_AGREE))
2602 exten = crypto_args(peer, CRYPTO_COOK,
2603 NULL);
2604 else if (peer->flags & FLAG_ASSOC)
2605 exten = crypto_args(peer, CRYPTO_AUTO |
2606 CRYPTO_RESP, NULL);
2607 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
2608 exten = crypto_args(peer, CRYPTO_AUTO,
2609 NULL);
2612 * Postamble. We trade leapseconds only when the
2613 * server and client are synchronized.
2615 else if (sys_leap != LEAP_NOTINSYNC &&
2616 peer->leap != LEAP_NOTINSYNC &&
2617 peer->crypto & CRYPTO_FLAG_TAI &&
2618 !(peer->crypto & CRYPTO_FLAG_LEAP))
2619 exten = crypto_args(peer, CRYPTO_TAI,
2620 NULL);
2621 break;
2624 * In client mode the digest, certificate, agreement
2625 * parameters and cookie are required. The leapsecond
2626 * table is optional. If broadcast client mode, the
2627 * autokey values are required as well. In broadcast
2628 * client mode, these values must be acquired during the
2629 * client/server exchange to avoid having to wait until
2630 * the next key list regeneration. Otherwise, the poor
2631 * dude may die a lingering death until becoming
2632 * unreachable and attempting rebirth.
2634 * If neither the server or client have the agreement
2635 * parameters, the protocol transmits the cookie in the
2636 * clear. If the server has the parameters, the client
2637 * requests them and the protocol blinds it using the
2638 * agreed key. It is a protocol error if the client has
2639 * the parameters but the server does not.
2641 * If the crypto bit is lit, don't send requests.
2643 case MODE_CLIENT:
2644 if (peer->flash & TEST9)
2645 break;
2647 * Parameter and certificate.
2649 if (!peer->crypto)
2650 exten = crypto_args(peer, CRYPTO_ASSOC,
2651 sys_hostname);
2652 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2653 exten = crypto_args(peer, CRYPTO_CERT,
2654 peer->issuer);
2657 * Identity
2659 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
2660 exten = crypto_args(peer,
2661 crypto_ident(peer), NULL);
2664 * Autokey
2666 else if (!(peer->crypto & CRYPTO_FLAG_AGREE))
2667 exten = crypto_args(peer, CRYPTO_COOK,
2668 NULL);
2669 else if (!(peer->crypto & CRYPTO_FLAG_AUTO) &&
2670 (peer->cast_flags & MDF_BCLNT))
2671 exten = crypto_args(peer, CRYPTO_AUTO,
2672 NULL);
2675 * Postamble. We can sign the certificate here,
2676 * since there is no chance of deadlock.
2678 else if (sys_leap != LEAP_NOTINSYNC &&
2679 !(peer->crypto & CRYPTO_FLAG_SIGN))
2680 exten = crypto_args(peer, CRYPTO_SIGN,
2681 sys_hostname);
2682 else if (sys_leap != LEAP_NOTINSYNC &&
2683 peer->crypto & CRYPTO_FLAG_TAI &&
2684 !(peer->crypto & CRYPTO_FLAG_LEAP))
2685 exten = crypto_args(peer, CRYPTO_TAI,
2686 NULL);
2687 break;
2691 * Build the extension fields as directed. A response to
2692 * a request is always sent, even if an error. If an
2693 * error occurs when sending a request, the crypto
2694 * machinery broke or was misconfigured. In that case
2695 * light the crypto bit to suppress further requests.
2697 if (peer->cmmd != NULL) {
2698 peer->cmmd->associd = htonl(peer->associd);
2699 sendlen += crypto_xmit(&xpkt, &peer->srcadr,
2700 sendlen, peer->cmmd, 0);
2701 free(peer->cmmd);
2702 peer->cmmd = NULL;
2704 if (exten != NULL) {
2705 int ltemp = 0;
2707 if (exten->opcode != 0) {
2708 ltemp = crypto_xmit(&xpkt,
2709 &peer->srcadr, sendlen, exten, 0);
2710 if (ltemp == 0) {
2711 peer->flash |= TEST9; /* crypto error */
2712 free(exten);
2713 return;
2716 sendlen += ltemp;
2717 free(exten);
2721 * If extension fields are present, we must use a
2722 * private cookie value of zero. Don't send if the
2723 * crypto bit is set and no extension field is present,
2724 * but in that case give back the key. Most intricate.
2726 if (sendlen > LEN_PKT_NOMAC) {
2727 session_key(&peer->dstadr->sin, &peer->srcadr,
2728 xkeyid, 0, 2);
2729 } else if (peer->flash & TEST9) {
2730 authtrust(xkeyid, 0);
2731 return;
2734 #endif /* OPENSSL */
2737 * Stash the transmit timestamp corrected for the encryption
2738 * delay. If autokey, give back the key, as we use keys only
2739 * once. Check for errors such as missing keys, buffer overflow,
2740 * etc.
2742 xkeyid = peer->keyid;
2743 get_systime(&peer->xmt);
2744 L_ADD(&peer->xmt, &sys_authdelay);
2745 HTONL_FP(&peer->xmt, &xpkt.xmt);
2746 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2747 if (authlen == 0) {
2748 msyslog(LOG_INFO, "transmit: %s key %u not found",
2749 stoa(&peer->srcadr), xkeyid);
2750 peer->flash |= TEST9; /* no key found */
2751 return;
2753 sendlen += authlen;
2754 #ifdef OPENSSL
2755 if (xkeyid > NTP_MAXKEY)
2756 authtrust(xkeyid, 0);
2757 #endif /* OPENSSL */
2758 get_systime(&xmt_tx);
2759 if (sendlen > sizeof(xpkt)) {
2760 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2761 exit (-1);
2763 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
2764 sendlen);
2767 * Calculate the encryption delay. Keep the minimum over
2768 * the latest two samples.
2770 L_SUB(&xmt_tx, &peer->xmt);
2771 L_ADD(&xmt_tx, &sys_authdelay);
2772 sys_authdly[1] = sys_authdly[0];
2773 sys_authdly[0] = xmt_tx.l_uf;
2774 if (sys_authdly[0] < sys_authdly[1])
2775 sys_authdelay.l_uf = sys_authdly[0];
2776 else
2777 sys_authdelay.l_uf = sys_authdly[1];
2778 peer->sent++;
2779 #ifdef OPENSSL
2780 #ifdef DEBUG
2781 if (debug)
2782 printf(
2783 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2784 current_time, peer->dstadr ? ntoa(&peer->dstadr->sin) : "-",
2785 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2786 authlen, authlen, peer->keynumber);
2787 #endif
2788 #else
2789 #ifdef DEBUG
2790 if (debug)
2791 printf(
2792 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2793 current_time, peer->dstadr ? ntoa(&peer->dstadr->sin) : "-",
2794 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2795 authlen, authlen);
2796 #endif
2797 #endif /* OPENSSL */
2802 * fast_xmit - Send packet for nonpersistent association. Note that
2803 * neither the source or destination can be a broadcast address.
2805 static void
2806 fast_xmit(
2807 struct recvbuf *rbufp, /* receive packet pointer */
2808 int xmode, /* transmit mode */
2809 keyid_t xkeyid, /* transmit key ID */
2810 int mask /* restrict mask */
2813 struct pkt xpkt; /* transmit packet structure */
2814 struct pkt *rpkt; /* receive packet structure */
2815 l_fp xmt_ts; /* timestamp */
2816 l_fp xmt_tx; /* timestamp after authent */
2817 int sendlen, authlen;
2818 #ifdef OPENSSL
2819 u_int32 temp32;
2820 #endif
2823 * Initialize transmit packet header fields from the receive
2824 * buffer provided. We leave some fields intact as received. If
2825 * the gazinta was from a multicast address, the gazoutta must
2826 * go out another way.
2828 * The root delay field is special. If the system stratum is
2829 * less than the orphan stratum, send the real root delay.
2830 * Otherwise, if there is no system peer, send the orphan delay.
2831 * Otherwise, we must be an orphan parent, so send zero.
2833 rpkt = &rbufp->recv_pkt;
2834 if (rbufp->dstadr->flags & INT_MCASTOPEN)
2835 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2838 * This is deliciously complicated. There are four cases.
2840 * case leap stratum refid delay dispersion
2842 * KoD 11 16 KISS system system
2843 * normal system system system system system
2844 * orphan child 00 orphan system orphan system
2845 * orphan parent 00 orphan loopbk 0 0
2848 * This is a kiss-of-death (KoD) packet. Show leap
2849 * unsynchronized, stratum zero, reference ID the four-character
2850 * kiss code and system root delay. Note the rate limit on these
2851 * packets. Once a second initialize a bucket counter. Every
2852 * packet sent decrements the counter until reaching zero. If
2853 * the counter is zero, drop the kiss.
2855 if (mask & RES_LIMITED) {
2856 sys_limitrejected++;
2857 if (sys_kod == 0 || !(mask & RES_DEMOBILIZE))
2858 return;
2860 sys_kod--;
2861 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2862 PKT_VERSION(rpkt->li_vn_mode), xmode);
2863 xpkt.stratum = STRATUM_UNSPEC;
2864 memcpy(&xpkt.refid, "RATE", 4);
2865 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2866 xpkt.rootdispersion =
2867 HTONS_FP(DTOUFP(sys_rootdispersion));
2870 * This is a normal packet. Use the system variables.
2872 } else if (sys_stratum < sys_orphan) {
2873 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2874 PKT_VERSION(rpkt->li_vn_mode), xmode);
2875 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2876 xpkt.refid = sys_refid;
2877 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2878 xpkt.rootdispersion =
2879 HTONS_FP(DTOUFP(sys_rootdispersion));
2882 * This is a orphan child packet. The host is synchronized to an
2883 * orphan parent. Show leap synchronized, orphan stratum, system
2884 * reference ID and orphan root delay.
2886 } else if (sys_peer != NULL) {
2887 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2888 PKT_VERSION(rpkt->li_vn_mode), xmode);
2889 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2890 xpkt.refid = sys_refid;
2891 xpkt.rootdelay = HTONS_FP(DTOFP(sys_orphandelay));
2892 xpkt.rootdispersion =
2893 HTONS_FP(DTOUFP(sys_rootdispersion));
2896 * This is an orphan parent. Show leap synchronized, orphan
2897 * stratum, loopack reference ID and zero root delay.
2899 } else {
2900 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOWARNING,
2901 PKT_VERSION(rpkt->li_vn_mode), xmode);
2902 xpkt.stratum = STRATUM_TO_PKT(sys_orphan);
2903 xpkt.refid = htonl(LOOPBACKADR);
2904 xpkt.rootdelay = HTONS_FP(DTOFP(0));
2905 xpkt.rootdispersion = HTONS_FP(DTOFP(0));
2907 xpkt.ppoll = rpkt->ppoll;
2908 xpkt.precision = sys_precision;
2909 xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
2910 HTONL_FP(&sys_reftime, &xpkt.reftime);
2911 xpkt.org = rpkt->xmt;
2912 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2915 * If the received packet contains a MAC, the transmitted packet
2916 * is authenticated and contains a MAC. If not, the transmitted
2917 * packet is not authenticated.
2919 sendlen = LEN_PKT_NOMAC;
2920 if (rbufp->recv_length == sendlen) {
2921 get_systime(&xmt_ts);
2922 HTONL_FP(&xmt_ts, &xpkt.xmt);
2923 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2924 sendlen);
2925 #ifdef DEBUG
2926 if (debug)
2927 printf("transmit: at %ld %s->%s mode %d\n",
2928 current_time, stoa(&rbufp->dstadr->sin),
2929 stoa(&rbufp->recv_srcadr), xmode);
2930 #endif
2931 return;
2935 * The received packet contains a MAC, so the transmitted packet
2936 * must be authenticated. For symmetric key cryptography, use
2937 * the predefined and trusted symmetric keys to generate the
2938 * cryptosum. For autokey cryptography, use the server private
2939 * value to generate the cookie, which is unique for every
2940 * source-destination-key ID combination.
2942 #ifdef OPENSSL
2943 if (xkeyid > NTP_MAXKEY) {
2944 keyid_t cookie;
2947 * The only way to get here is a reply to a legitimate
2948 * client request message, so the mode must be
2949 * MODE_SERVER. If an extension field is present, there
2950 * can be only one and that must be a command. Do what
2951 * needs, but with private value of zero so the poor
2952 * jerk can decode it. If no extension field is present,
2953 * use the cookie to generate the session key.
2955 cookie = session_key(&rbufp->recv_srcadr,
2956 &rbufp->dstadr->sin, 0, sys_private, 0);
2957 if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN +
2958 2 * sizeof(u_int32))) {
2959 session_key(&rbufp->dstadr->sin,
2960 &rbufp->recv_srcadr, xkeyid, 0, 2);
2961 temp32 = CRYPTO_RESP;
2962 rpkt->exten[0] |= htonl(temp32);
2963 sendlen += crypto_xmit(&xpkt,
2964 &rbufp->recv_srcadr, sendlen,
2965 (struct exten *)rpkt->exten, cookie);
2966 } else {
2967 session_key(&rbufp->dstadr->sin,
2968 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2971 #endif /* OPENSSL */
2972 get_systime(&xmt_ts);
2973 L_ADD(&xmt_ts, &sys_authdelay);
2974 HTONL_FP(&xmt_ts, &xpkt.xmt);
2975 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2976 sendlen += authlen;
2977 #ifdef OPENSSL
2978 if (xkeyid > NTP_MAXKEY)
2979 authtrust(xkeyid, 0);
2980 #endif /* OPENSSL */
2981 get_systime(&xmt_tx);
2982 if (sendlen > sizeof(xpkt)) {
2983 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2984 exit (-1);
2986 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2989 * Calculate the encryption delay. Keep the minimum over the
2990 * latest two samples.
2992 L_SUB(&xmt_tx, &xmt_ts);
2993 L_ADD(&xmt_tx, &sys_authdelay);
2994 sys_authdly[1] = sys_authdly[0];
2995 sys_authdly[0] = xmt_tx.l_uf;
2996 if (sys_authdly[0] < sys_authdly[1])
2997 sys_authdelay.l_uf = sys_authdly[0];
2998 else
2999 sys_authdelay.l_uf = sys_authdly[1];
3000 #ifdef DEBUG
3001 if (debug)
3002 printf(
3003 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
3004 current_time, ntoa(&rbufp->dstadr->sin),
3005 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen -
3006 authlen, authlen);
3007 #endif
3011 #ifdef OPENSSL
3013 * key_expire - purge the key list
3015 void
3016 key_expire(
3017 struct peer *peer /* peer structure pointer */
3020 int i;
3022 if (peer->keylist != NULL) {
3023 for (i = 0; i <= peer->keynumber; i++)
3024 authtrust(peer->keylist[i], 0);
3025 free(peer->keylist);
3026 peer->keylist = NULL;
3028 value_free(&peer->sndval);
3029 peer->keynumber = 0;
3030 #ifdef DEBUG
3031 if (debug)
3032 printf("key_expire: at %lu\n", current_time);
3033 #endif
3035 #endif /* OPENSSL */
3039 * Determine if the peer is unfit for synchronization
3041 * A peer is unfit for synchronization if
3042 * > TEST10 bad leap or stratum below floor or at or above ceiling
3043 * > TEST11 root distance exceeded
3044 * > TEST12 a direct or indirect synchronization loop would form
3045 * > TEST13 unreachable or noselect
3047 int /* FALSE if fit, TRUE if unfit */
3048 peer_unfit(
3049 struct peer *peer /* peer structure pointer */
3052 int rval = 0;
3055 * A stratum error occurs if (1) the server has never been
3056 * synchronized, (2) the server stratum is below the floor or
3057 * greater than or equal to the ceiling, (3) the system stratum
3058 * is below the orphan stratum and the server stratum is greater
3059 * than or equal to the orphan stratum.
3061 if (peer->leap == LEAP_NOTINSYNC || peer->stratum < sys_floor ||
3062 peer->stratum >= sys_ceiling || (sys_stratum < sys_orphan &&
3063 peer->stratum >= sys_orphan))
3064 rval |= TEST10; /* stratum out of bounds */
3067 * A distance error occurs if the root distance is greater than
3068 * or equal to the distance threshold plus the increment due to
3069 * one poll interval.
3071 if (root_distance(peer) >= sys_maxdist + clock_phi *
3072 ULOGTOD(sys_poll))
3073 rval |= TEST11; /* distance exceeded */
3076 * A loop error occurs if the remote peer is synchronized to the
3077 * local peer of if the remote peer is synchronized to the same
3078 * server as the local peer, but only if the remote peer is not
3079 * the orphan parent.
3081 if (peer->stratum > 1 && peer->refid != htonl(LOOPBACKADR) &&
3082 ((!peer->dstadr || peer->refid == peer->dstadr->addr_refid) ||
3083 peer->refid == sys_refid))
3084 rval |= TEST12; /* synch loop */
3087 * An unreachable error occurs if the server is unreachable or
3088 * the noselect bit is set.
3090 if (!peer->reach || peer->flags & FLAG_NOSELECT)
3091 rval |= TEST13; /* unreachable */
3093 peer->flash &= ~PEER_TEST_MASK;
3094 peer->flash |= rval;
3095 return (rval);
3100 * Find the precision of this particular machine
3102 #define MINSTEP 100e-9 /* minimum clock increment (s) */
3103 #define MAXSTEP 20e-3 /* maximum clock increment (s) */
3104 #define MINLOOPS 5 /* minimum number of step samples */
3107 * This routine calculates the system precision, defined as the minimum
3108 * of a sequence of differences between successive readings of the
3109 * system clock. However, if the system clock can be read more than once
3110 * during a tick interval, the difference can be zero or one LSB unit,
3111 * where the LSB corresponds to one nanosecond or one microsecond.
3112 * Conceivably, if some other process preempts this one and reads the
3113 * clock, the difference can be more than one LSB unit.
3115 * For hardware clock frequencies of 10 MHz or less, we assume the
3116 * logical clock advances only at the hardware clock tick. For higher
3117 * frequencies, we assume the logical clock can advance no more than 100
3118 * nanoseconds between ticks.
3121 default_get_precision(void)
3123 l_fp val; /* current seconds fraction */
3124 l_fp last; /* last seconds fraction */
3125 l_fp diff; /* difference */
3126 double tick; /* computed tick value */
3127 double dtemp; /* scratch */
3128 int i; /* log2 precision */
3131 * Loop to find tick value in nanoseconds. Toss out outlyer
3132 * values less than the minimun tick value. In wacky cases, use
3133 * the default maximum value.
3135 get_systime(&last);
3136 tick = MAXSTEP;
3137 for (i = 0; i < MINLOOPS;) {
3138 get_systime(&val);
3139 diff = val;
3140 L_SUB(&diff, &last);
3141 last = val;
3142 LFPTOD(&diff, dtemp);
3143 if (dtemp < MINSTEP)
3144 continue;
3145 i++;
3146 if (dtemp < tick)
3147 tick = dtemp;
3151 * Find the nearest power of two.
3153 NLOG(NLOG_SYSEVENT)
3154 msyslog(LOG_INFO, "precision = %.3f usec", tick * 1e6);
3155 for (i = 0; tick <= 1; i++)
3156 tick *= 2;
3157 if (tick - 1. > 1. - tick / 2)
3158 i--;
3159 return (-i);
3164 * kod_proto - called once per second to limit kiss-of-death packets
3166 void
3167 kod_proto(void)
3169 sys_kod = sys_kod_rate;
3174 * init_proto - initialize the protocol module's data
3176 void
3177 init_proto(void)
3179 l_fp dummy;
3180 int i;
3183 * Fill in the sys_* stuff. Default is don't listen to
3184 * broadcasting, authenticate.
3186 sys_leap = LEAP_NOTINSYNC;
3187 sys_stratum = STRATUM_UNSPEC;
3188 memcpy(&sys_refid, "INIT", 4);
3189 sys_precision = (s_char)default_get_precision();
3190 sys_jitter = LOGTOD(sys_precision);
3191 sys_rootdelay = 0;
3192 sys_orphandelay = (double)(ntp_random() & 0xffff) / 65536. *
3193 sys_maxdist;
3194 sys_rootdispersion = 0;
3195 L_CLR(&sys_reftime);
3196 sys_peer = NULL;
3197 sys_survivors = 0;
3198 get_systime(&dummy);
3199 sys_manycastserver = 0;
3200 sys_bclient = 0;
3201 sys_bdelay = DEFBROADDELAY;
3202 sys_calldelay = BURST_DELAY;
3203 sys_authenticate = 1;
3204 L_CLR(&sys_authdelay);
3205 sys_authdly[0] = sys_authdly[1] = 0;
3206 sys_stattime = 0;
3207 proto_clr_stats();
3208 for (i = 0; i < MAX_TTL; i++) {
3209 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
3210 sys_ttlmax = i;
3212 #ifdef OPENSSL
3213 sys_automax = 1 << NTP_AUTOMAX;
3214 #endif /* OPENSSL */
3217 * Default these to enable
3219 ntp_enable = 1;
3220 #ifndef KERNEL_FLL_BUG
3221 kern_enable = 1;
3222 #endif
3223 pps_enable = 0;
3224 stats_control = 1;
3229 * proto_config - configure the protocol module
3231 void
3232 proto_config(
3233 int item,
3234 u_long value,
3235 double dvalue,
3236 struct sockaddr_storage* svalue
3240 * Figure out what he wants to change, then do it
3242 switch (item) {
3245 * Turn on/off kernel discipline.
3247 case PROTO_KERNEL:
3248 kern_enable = (int)value;
3249 break;
3252 * Turn on/off clock discipline.
3254 case PROTO_NTP:
3255 ntp_enable = (int)value;
3256 break;
3259 * Turn on/off monitoring.
3261 case PROTO_MONITOR:
3262 if (value)
3263 mon_start(MON_ON);
3264 else
3265 mon_stop(MON_ON);
3266 break;
3269 * Turn on/off statistics.
3271 case PROTO_FILEGEN:
3272 stats_control = (int)value;
3273 break;
3276 * Turn on/off enable broadcasts.
3278 case PROTO_BROADCLIENT:
3279 sys_bclient = (int)value;
3280 if (sys_bclient == 0)
3281 io_unsetbclient();
3282 else
3283 io_setbclient();
3284 break;
3287 * Turn on/off PPS discipline.
3289 case PROTO_PPS:
3290 pps_enable = (int)value;
3291 break;
3294 * Add muliticast group address.
3296 case PROTO_MULTICAST_ADD:
3297 if (svalue)
3298 io_multicast_add(*svalue);
3299 sys_bclient = 1;
3300 break;
3303 * Delete multicast group address.
3305 case PROTO_MULTICAST_DEL:
3306 if (svalue)
3307 io_multicast_del(*svalue);
3308 break;
3311 * Set default broadcast delay.
3313 case PROTO_BROADDELAY:
3314 sys_bdelay = dvalue;
3315 break;
3318 * Set modem call delay.
3320 case PROTO_CALLDELAY:
3321 sys_calldelay = (int)value;
3322 break;
3325 * Turn on/off authentication to mobilize ephemeral
3326 * associations.
3328 case PROTO_AUTHENTICATE:
3329 sys_authenticate = (int)value;
3330 break;
3333 * Set minimum number of survivors.
3335 case PROTO_MINCLOCK:
3336 sys_minclock = (int)dvalue;
3337 break;
3340 * Set maximum number of preemptable associations.
3342 case PROTO_MAXCLOCK:
3343 sys_maxclock = (int)dvalue;
3344 break;
3347 * Set minimum number of survivors.
3349 case PROTO_MINSANE:
3350 sys_minsane = (int)dvalue;
3351 break;
3354 * Set stratum floor.
3356 case PROTO_FLOOR:
3357 sys_floor = (int)dvalue;
3358 break;
3361 * Set stratum ceiling.
3363 case PROTO_CEILING:
3364 sys_ceiling = (int)dvalue;
3365 break;
3368 * Set orphan stratum.
3370 case PROTO_ORPHAN:
3371 sys_orphan = (int)dvalue;
3372 break;
3375 * Set cohort switch.
3377 case PROTO_COHORT:
3378 sys_cohort = (int)dvalue;
3379 break;
3382 * Set minimum dispersion increment.
3384 case PROTO_MINDISP:
3385 sys_mindisp = dvalue;
3386 break;
3389 * Set maximum distance (select threshold).
3391 case PROTO_MAXDIST:
3392 sys_maxdist = dvalue;
3393 break;
3396 * Set anticlockhop threshold.
3398 case PROTO_MAXHOP:
3399 sys_maxhop = (int)dvalue;
3400 break;
3403 * Set adjtime() resolution (s).
3405 case PROTO_ADJ:
3406 sys_tick = dvalue;
3407 break;
3410 * Set manycast beacon interval.
3412 case PROTO_BEACON:
3413 sys_beacon = (int)dvalue;
3414 break;
3416 #ifdef REFCLOCK
3418 * Turn on/off refclock calibrate
3420 case PROTO_CAL:
3421 cal_enable = (int)value;
3422 break;
3423 #endif /* REFCLOCK */
3424 default:
3427 * Log this error.
3429 msyslog(LOG_INFO,
3430 "proto_config: illegal item %d, value %ld", item,
3431 value);
3437 * proto_clr_stats - clear protocol stat counters
3439 void
3440 proto_clr_stats(void)
3442 sys_stattime = current_time;
3443 sys_received = 0;
3444 sys_processed = 0;
3445 sys_newversionpkt = 0;
3446 sys_oldversionpkt = 0;
3447 sys_unknownversion = 0;
3448 sys_restricted = 0;
3449 sys_badlength = 0;
3450 sys_badauth = 0;
3451 sys_limitrejected = 0;