2 * ntp_proto.c - NTP version 4 protocol machinery
4 * ATTENTION: Get approval from Dave Mills on all changes to this file!
12 #include "ntp_stdlib.h"
13 #include "ntp_unixtime.h"
14 #include "ntp_control.h"
15 #include "ntp_string.h"
16 #include "ntp_leapsec.h"
27 * This macro defines the authentication state. If x is 1 authentication
28 * is required; othewise it is optional.
30 #define AUTH(x, y) ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
33 #define AUTH_NONE 0 /* authentication not required */
34 #define AUTH_OK 1 /* authentication OK */
35 #define AUTH_ERROR 2 /* authentication error */
36 #define AUTH_CRYPTO 3 /* crypto_NAK */
39 * traffic shaping parameters
41 #define NTP_IBURST 6 /* packets in iburst */
42 #define RESP_DELAY 1 /* refclock burst delay (s) */
45 * pool soliciting restriction duration (s)
47 #define POOL_SOLICIT_WINDOW 8
50 * peer_select groups statistics for a peer used by clock_select() and
53 typedef struct peer_select_tag {
55 double synch; /* sync distance */
56 double error; /* jitter */
57 double seljit; /* selection jitter */
61 * System variables are declared here. Unless specified otherwise, all
62 * times are in seconds.
64 u_char sys_leap; /* system leap indicator */
65 u_char sys_stratum; /* system stratum */
66 s_char sys_precision; /* local clock precision (log2 s) */
67 double sys_rootdelay; /* roundtrip delay to primary source */
68 double sys_rootdisp; /* dispersion to primary source */
69 u_int32 sys_refid; /* reference id (network byte order) */
70 l_fp sys_reftime; /* last update time */
71 struct peer *sys_peer; /* current peer */
74 * Rate controls. Leaky buckets are used to throttle the packet
75 * transmission rates in order to protect busy servers such as at NIST
76 * and USNO. There is a counter for each association and another for KoD
77 * packets. The association counter decrements each second, but not
78 * below zero. Each time a packet is sent the counter is incremented by
79 * a configurable value representing the average interval between
80 * packets. A packet is delayed as long as the counter is greater than
81 * zero. Note this does not affect the time value computations.
84 * Nonspecified system state variables
86 int sys_bclient; /* broadcast client enable */
87 double sys_bdelay; /* broadcast client default delay */
88 int sys_authenticate; /* requre authentication for config */
89 l_fp sys_authdelay; /* authentication delay */
90 double sys_offset; /* current local clock offset */
91 double sys_mindisp = MINDISPERSE; /* minimum distance (s) */
92 double sys_maxdist = MAXDISTANCE; /* selection threshold */
93 double sys_jitter; /* system jitter */
94 u_long sys_epoch; /* last clock update time */
95 static double sys_clockhop; /* clockhop threshold */
96 static int leap_vote_ins; /* leap consensus for insert */
97 static int leap_vote_del; /* leap consensus for delete */
98 keyid_t sys_private; /* private value for session seed */
99 int sys_manycastserver; /* respond to manycast client pkts */
100 int ntp_mode7; /* respond to ntpdc (mode7) */
101 int peer_ntpdate; /* active peers in ntpdate mode */
102 int sys_survivors; /* truest of the truechimers */
103 char *sys_ident = NULL; /* identity scheme */
106 * TOS and multicast mapping stuff
108 int sys_floor = 0; /* cluster stratum floor */
109 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
110 int sys_minsane = 1; /* minimum candidates */
111 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
112 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
113 int sys_cohort = 0; /* cohort switch */
114 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
115 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
116 int sys_beacon = BEACON; /* manycast beacon interval */
117 int sys_ttlmax; /* max ttl mapping vector index */
118 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
121 * Statistics counters - first the good, then the bad
123 u_long sys_stattime; /* elapsed time */
124 u_long sys_received; /* packets received */
125 u_long sys_processed; /* packets for this host */
126 u_long sys_newversion; /* current version */
127 u_long sys_oldversion; /* old version */
128 u_long sys_restricted; /* access denied */
129 u_long sys_badlength; /* bad length or format */
130 u_long sys_badauth; /* bad authentication */
131 u_long sys_declined; /* declined */
132 u_long sys_limitrejected; /* rate exceeded */
133 u_long sys_kodsent; /* KoD sent */
135 static double root_distance (struct peer *);
136 static void clock_combine (peer_select *, int, int);
137 static void peer_xmit (struct peer *);
138 static void fast_xmit (struct recvbuf *, int, keyid_t, int);
139 static void pool_xmit (struct peer *);
140 static void clock_update (struct peer *);
141 static void measure_precision(void);
142 static double measure_tick_fuzz(void);
143 static int local_refid (struct peer *);
144 static int peer_unfit (struct peer *);
146 static int group_test (char *, char *);
149 void pool_name_resolved (int, int, void *, const char *,
150 const char *, const struct addrinfo *,
151 const struct addrinfo *);
156 * transmit - transmit procedure called by poll timeout
160 struct peer *peer /* peer structure pointer */
166 * The polling state machine. There are two kinds of machines,
167 * those that never expect a reply (broadcast and manycast
168 * server modes) and those that do (all other modes). The dance
174 * In broadcast mode the poll interval is never changed from
177 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
178 peer->outdate = current_time;
179 if (sys_leap != LEAP_NOTINSYNC)
181 poll_update(peer, hpoll);
186 * In manycast mode we start with unity ttl. The ttl is
187 * increased by one for each poll until either sys_maxclock
188 * servers have been found or the maximum ttl is reached. When
189 * sys_maxclock servers are found we stop polling until one or
190 * more servers have timed out or until less than sys_minclock
191 * associations turn up. In this case additional better servers
192 * are dragged in and preempt the existing ones. Once every
193 * sys_beacon seconds we are to transmit unconditionally, but
194 * this code is not quite right -- peer->unreach counts polls
195 * and is being compared with sys_beacon, so the beacons happen
196 * every sys_beacon polls.
198 if (peer->cast_flags & MDF_ACAST) {
199 peer->outdate = current_time;
200 if (peer->unreach > sys_beacon) {
204 } else if (sys_survivors < sys_minclock ||
205 peer_associations < sys_maxclock) {
206 if (peer->ttl < (u_int32)sys_ttlmax)
211 poll_update(peer, hpoll);
216 * Pool associations transmit unicast solicitations when there
217 * are less than a hard limit of 2 * sys_maxclock associations,
218 * and either less than sys_minclock survivors or less than
219 * sys_maxclock associations. The hard limit prevents unbounded
220 * growth in associations if the system clock or network quality
221 * result in survivor count dipping below sys_minclock often.
222 * This was observed testing with pool, where sys_maxclock == 12
223 * resulted in 60 associations without the hard limit. A
224 * similar hard limit on manycastclient ephemeral associations
225 * may be appropriate.
227 if (peer->cast_flags & MDF_POOL) {
228 peer->outdate = current_time;
229 if ((peer_associations <= 2 * sys_maxclock) &&
230 (peer_associations < sys_maxclock ||
231 sys_survivors < sys_minclock))
233 poll_update(peer, hpoll);
238 * In unicast modes the dance is much more intricate. It is
239 * designed to back off whenever possible to minimize network
242 if (peer->burst == 0) {
246 * Update the reachability status. If not heard for
247 * three consecutive polls, stuff infinity in the clock
250 oreach = peer->reach;
251 peer->outdate = current_time;
257 * Here the peer is unreachable. If it was
258 * previously reachable raise a trap. Send a
261 clock_filter(peer, 0., 0., MAXDISPERSE);
264 report_event(PEVNT_UNREACH, peer, NULL);
266 if ((peer->flags & FLAG_IBURST) &&
268 peer->retry = NTP_RETRY;
272 * Here the peer is reachable. Send a burst if
273 * enabled and the peer is fit. Reset unreach
274 * for persistent and ephemeral associations.
275 * Unreach is also reset for survivors in
279 if (!(peer->flags & FLAG_PREEMPT))
281 if ((peer->flags & FLAG_BURST) && peer->retry ==
282 0 && !peer_unfit(peer))
283 peer->retry = NTP_RETRY;
287 * Watch for timeout. If ephemeral, toss the rascal;
288 * otherwise, bump the poll interval. Note the
289 * poll_update() routine will clamp it to maxpoll.
290 * If preemptible and we have more peers than maxclock,
291 * and this peer has the minimum score of preemptibles,
294 if (peer->unreach >= NTP_UNREACH) {
296 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
297 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
298 report_event(PEVNT_RESTART, peer, "timeout");
299 peer_clear(peer, "TIME");
303 if ((peer->flags & FLAG_PREEMPT) &&
304 (peer_associations > sys_maxclock) &&
306 report_event(PEVNT_RESTART, peer, "timeout");
307 peer_clear(peer, "TIME");
314 if (peer->burst == 0) {
317 * If ntpdate mode and the clock has not been
318 * set and all peers have completed the burst,
319 * we declare a successful failure.
323 if (peer_ntpdate == 0) {
325 "ntpd: no servers found");
328 "ntpd: no servers found\n");
338 * Do not transmit if in broadcast client mode.
340 if (peer->hmode != MODE_BCLIENT)
342 poll_update(peer, hpoll);
347 * receive - receive procedure called for each packet received
351 struct recvbuf *rbufp
354 register struct peer *peer; /* peer structure pointer */
355 register struct pkt *pkt; /* receive packet pointer */
356 u_char hisversion; /* packet version */
357 u_char hisleap; /* packet leap indicator */
358 u_char hismode; /* packet mode */
359 u_char hisstratum; /* packet stratum */
360 u_short restrict_mask; /* restrict bits */
361 int has_mac; /* length of MAC field */
362 int authlen; /* offset of MAC field */
363 int is_authentic = 0; /* cryptosum ok */
364 int retcode = AM_NOMATCH; /* match code */
365 keyid_t skeyid = 0; /* key IDs */
366 u_int32 opcode = 0; /* extension field opcode */
367 sockaddr_u *dstadr_sin; /* active runway */
368 struct peer *peer2; /* aux peer structure pointer */
369 endpt * match_ep; /* newpeer() local address */
370 l_fp p_org; /* origin timestamp */
371 l_fp p_rec; /* receive timestamp */
372 l_fp p_xmt; /* transmit timestamp */
374 char hostname[NTP_MAXSTRLEN + 1];
375 char *groupname = NULL;
376 struct autokey *ap; /* autokey structure pointer */
377 int rval; /* cookie snatcher */
378 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
380 #ifdef HAVE_NTP_SIGND
381 static unsigned char zero_key[16];
382 #endif /* HAVE_NTP_SIGND */
385 * Monitor the packet and get restrictions. Note that the packet
386 * length for control and private mode packets must be checked
387 * by the service routines. Some restrictions have to be handled
388 * later in order to generate a kiss-o'-death packet.
391 * Bogus port check is before anything, since it probably
392 * reveals a clogging attack.
395 if (0 == SRCPORT(&rbufp->recv_srcadr)) {
397 return; /* bogus port */
399 restrict_mask = restrictions(&rbufp->recv_srcadr);
400 DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x\n",
401 current_time, stoa(&rbufp->dstadr->sin),
402 stoa(&rbufp->recv_srcadr),
403 rbufp->dstadr->flags, restrict_mask));
404 pkt = &rbufp->recv_pkt;
405 hisversion = PKT_VERSION(pkt->li_vn_mode);
406 hisleap = PKT_LEAP(pkt->li_vn_mode);
407 hismode = (int)PKT_MODE(pkt->li_vn_mode);
408 hisstratum = PKT_TO_STRATUM(pkt->stratum);
409 if (restrict_mask & RES_IGNORE) {
411 return; /* ignore everything */
413 if (hismode == MODE_PRIVATE) {
414 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
416 return; /* no query private */
418 process_private(rbufp, ((restrict_mask &
419 RES_NOMODIFY) == 0));
422 if (hismode == MODE_CONTROL) {
423 if (restrict_mask & RES_NOQUERY) {
425 return; /* no query control */
427 process_control(rbufp, restrict_mask);
430 if (restrict_mask & RES_DONTSERVE) {
432 return; /* no time serve */
436 * This is for testing. If restricted drop ten percent of
439 if (restrict_mask & RES_FLAKE) {
440 if ((double)ntp_random() / 0x7fffffff < .1) {
442 return; /* no flakeway */
447 * Version check must be after the query packets, since they
448 * intentionally use an early version.
450 if (hisversion == NTP_VERSION) {
451 sys_newversion++; /* new version */
452 } else if (!(restrict_mask & RES_VERSION) && hisversion >=
454 sys_oldversion++; /* previous version */
457 return; /* old version */
461 * Figure out his mode and validate the packet. This has some
462 * legacy raunch that probably should be removed. In very early
463 * NTP versions mode 0 was equivalent to what later versions
464 * would interpret as client mode.
466 if (hismode == MODE_UNSPEC) {
467 if (hisversion == NTP_OLDVERSION) {
468 hismode = MODE_CLIENT;
471 return; /* invalid mode */
476 * Parse the extension field if present. We figure out whether
477 * an extension field is present by measuring the MAC size. If
478 * the number of words following the packet header is 0, no MAC
479 * is present and the packet is not authenticated. If 1, the
480 * packet is a crypto-NAK; if 3, the packet is authenticated
481 * with DES; if 5, the packet is authenticated with MD5; if 6,
482 * the packet is authenticated with SHA. If 2 or * 4, the packet
483 * is a runt and discarded forthwith. If greater than 6, an
484 * extension field is present, so we subtract the length of the
485 * field and go around again.
487 authlen = LEN_PKT_NOMAC;
488 has_mac = rbufp->recv_length - authlen;
489 while (has_mac > 0) {
496 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
498 return; /* bad length */
500 if (has_mac <= (int)MAX_MAC_LEN) {
501 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
505 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
506 len = opcode & 0xffff;
507 if (len % 4 != 0 || len < 4 || (int)len +
508 authlen > rbufp->recv_length) {
510 return; /* bad length */
514 * Extract calling group name for later. If
515 * sys_groupname is non-NULL, there must be
516 * a group name provided to elicit a response.
518 if ((opcode & 0x3fff0000) == CRYPTO_ASSOC &&
519 sys_groupname != NULL) {
520 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
521 hostlen = ntohl(ep->vallen);
522 if (hostlen >= sizeof(hostname) ||
524 offsetof(struct exten, pkt)) {
526 return; /* bad length */
528 memcpy(hostname, &ep->pkt, hostlen);
529 hostname[hostlen] = '\0';
530 groupname = strchr(hostname, '@');
531 if (groupname == NULL) {
544 * If has_mac is < 0 we had a malformed packet.
548 return; /* bad length */
552 * If authentication required, a MAC must be present.
554 if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
556 return; /* access denied */
560 * Update the MRU list and finger the cloggers. It can be a
561 * little expensive, so turn it off for production use.
562 * RES_LIMITED and RES_KOD will be cleared in the returned
563 * restrict_mask unless one or both actions are warranted.
565 restrict_mask = ntp_monitor(rbufp, restrict_mask);
566 if (restrict_mask & RES_LIMITED) {
568 if (!(restrict_mask & RES_KOD) || MODE_BROADCAST ==
569 hismode || MODE_SERVER == hismode) {
570 if (MODE_SERVER == hismode)
571 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
572 stoa(&rbufp->recv_srcadr)));
573 return; /* rate exceeded */
575 if (hismode == MODE_CLIENT)
576 fast_xmit(rbufp, MODE_SERVER, skeyid,
579 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
581 return; /* rate exceeded */
583 restrict_mask &= ~RES_KOD;
586 * We have tossed out as many buggy packets as possible early in
587 * the game to reduce the exposure to a clogging attack. Now we
588 * have to burn some cycles to find the association and
589 * authenticate the packet if required. Note that we burn only
590 * digest cycles, again to reduce exposure. There may be no
591 * matching association and that's okay.
593 * More on the autokey mambo. Normally the local interface is
594 * found when the association was mobilized with respect to a
595 * designated remote address. We assume packets arriving from
596 * the remote address arrive via this interface and the local
597 * address used to construct the autokey is the unicast address
598 * of the interface. However, if the sender is a broadcaster,
599 * the interface broadcast address is used instead.
600 * Notwithstanding this technobabble, if the sender is a
601 * multicaster, the broadcast address is null, so we use the
602 * unicast address anyway. Don't ask.
604 peer = findpeer(rbufp, hismode, &retcode);
605 dstadr_sin = &rbufp->dstadr->sin;
606 NTOHL_FP(&pkt->org, &p_org);
607 NTOHL_FP(&pkt->rec, &p_rec);
608 NTOHL_FP(&pkt->xmt, &p_xmt);
611 * Authentication is conditioned by three switches:
613 * NOPEER (RES_NOPEER) do not mobilize an association unless
615 * NOTRUST (RES_DONTTRUST) do not allow access unless
616 * authenticated (implies NOPEER)
617 * enable (sys_authenticate) master NOPEER switch, by default
620 * The NOPEER and NOTRUST can be specified on a per-client basis
621 * using the restrict command. The enable switch if on implies
622 * NOPEER for all clients. There are four outcomes:
624 * NONE The packet has no MAC.
625 * OK the packet has a MAC and authentication succeeds
626 * ERROR the packet has a MAC and authentication fails
627 * CRYPTO crypto-NAK. The MAC has four octets only.
629 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
630 * is zero, acceptable outcomes of y are NONE and OK. If x is
631 * one, the only acceptable outcome of y is OK.
635 restrict_mask &= ~RES_MSSNTP;
636 is_authentic = AUTH_NONE; /* not required */
640 "receive: at %ld %s<-%s mode %d len %d\n",
641 current_time, stoa(dstadr_sin),
642 stoa(&rbufp->recv_srcadr), hismode,
645 } else if (has_mac == 4) {
646 restrict_mask &= ~RES_MSSNTP;
647 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
651 "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
652 current_time, stoa(dstadr_sin),
653 stoa(&rbufp->recv_srcadr), hismode, skeyid,
654 authlen + has_mac, is_authentic);
657 #ifdef HAVE_NTP_SIGND
659 * If the signature is 20 bytes long, the last 16 of
660 * which are zero, then this is a Microsoft client
661 * wanting AD-style authentication of the server's
664 * This is described in Microsoft's WSPP docs, in MS-SNTP:
665 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
667 } else if (has_mac == MAX_MD5_LEN && (restrict_mask & RES_MSSNTP) &&
668 (retcode == AM_FXMIT || retcode == AM_NEWPASS) &&
669 (memcmp(zero_key, (char *)pkt + authlen + 4, MAX_MD5_LEN - 4) ==
671 is_authentic = AUTH_NONE;
672 #endif /* HAVE_NTP_SIGND */
675 restrict_mask &= ~RES_MSSNTP;
678 * For autokey modes, generate the session key
679 * and install in the key cache. Use the socket
680 * broadcast or unicast address as appropriate.
682 if (crypto_flags && skeyid > NTP_MAXKEY) {
685 * More on the autokey dance (AKD). A cookie is
686 * constructed from public and private values.
687 * For broadcast packets, the cookie is public
688 * (zero). For packets that match no
689 * association, the cookie is hashed from the
690 * addresses and private value. For server
691 * packets, the cookie was previously obtained
692 * from the server. For symmetric modes, the
693 * cookie was previously constructed using an
694 * agreement protocol; however, should PKI be
695 * unavailable, we construct a fake agreement as
696 * the EXOR of the peer and host cookies.
698 * hismode ephemeral persistent
699 * =======================================
702 * client sys cookie 0%
703 * server 0% sys cookie
709 if (has_mac < (int)MAX_MD5_LEN) {
713 if (hismode == MODE_BROADCAST) {
716 * For broadcaster, use the interface
717 * broadcast address when available;
718 * otherwise, use the unicast address
719 * found when the association was
720 * mobilized. However, if this is from
721 * the wildcard interface, game over.
723 if (crypto_flags && rbufp->dstadr ==
724 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
726 return; /* no wildcard */
729 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
731 &rbufp->dstadr->bcast;
732 } else if (peer == NULL) {
733 pkeyid = session_key(
734 &rbufp->recv_srcadr, dstadr_sin, 0,
737 pkeyid = peer->pcookie;
741 * The session key includes both the public
742 * values and cookie. In case of an extension
743 * field, the cookie used for authentication
744 * purposes is zero. Note the hash is saved for
745 * use later in the autokey mambo.
747 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
748 session_key(&rbufp->recv_srcadr,
749 dstadr_sin, skeyid, 0, 2);
750 tkeyid = session_key(
751 &rbufp->recv_srcadr, dstadr_sin,
754 tkeyid = session_key(
755 &rbufp->recv_srcadr, dstadr_sin,
763 * Compute the cryptosum. Note a clogging attack may
764 * succeed in bloating the key cache. If an autokey,
765 * purge it immediately, since we won't be needing it
766 * again. If the packet is authentic, it can mobilize an
767 * association. Note that there is no key zero.
769 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
771 is_authentic = AUTH_ERROR;
773 is_authentic = AUTH_OK;
775 if (crypto_flags && skeyid > NTP_MAXKEY)
776 authtrust(skeyid, 0);
781 "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
782 current_time, stoa(dstadr_sin),
783 stoa(&rbufp->recv_srcadr), hismode, skeyid,
784 authlen + has_mac, is_authentic);
789 * The association matching rules are implemented by a set of
790 * routines and an association table. A packet matching an
791 * association is processed by the peer process for that
792 * association. If there are no errors, an ephemeral association
793 * is mobilized: a broadcast packet mobilizes a broadcast client
794 * aassociation; a manycast server packet mobilizes a manycast
795 * client association; a symmetric active packet mobilizes a
796 * symmetric passive association.
801 * This is a client mode packet not matching any association. If
802 * an ordinary client, simply toss a server mode packet back
803 * over the fence. If a manycast client, we have to work a
809 * If authentication OK, send a server reply; otherwise,
812 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
813 if (AUTH(restrict_mask & RES_DONTTRUST,
815 fast_xmit(rbufp, MODE_SERVER, skeyid,
817 } else if (is_authentic == AUTH_ERROR) {
818 fast_xmit(rbufp, MODE_SERVER, 0,
828 * This must be manycast. Do not respond if not
829 * configured as a manycast server.
831 if (!sys_manycastserver) {
833 return; /* not enabled */
838 * Do not respond if not the same group.
840 if (group_test(groupname, NULL)) {
847 * Do not respond if we are not synchronized or our
848 * stratum is greater than the manycaster or the
849 * manycaster has already synchronized to us.
851 if (sys_leap == LEAP_NOTINSYNC || sys_stratum >=
852 hisstratum || (!sys_cohort && sys_stratum ==
853 hisstratum + 1) || rbufp->dstadr->addr_refid ==
856 return; /* no help */
860 * Respond only if authentication succeeds. Don't do a
861 * crypto-NAK, as that would not be useful.
863 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
864 fast_xmit(rbufp, MODE_SERVER, skeyid,
869 * This is a server mode packet returned in response to a client
870 * mode packet sent to a multicast group address (for
871 * manycastclient) or to a unicast address (for pool). The
872 * origin timestamp is a good nonce to reliably associate the
873 * reply with what was sent. If there is no match, that's
874 * curious and could be an intruder attempting to clog, so we
877 * If the packet is authentic and the manycastclient or pool
878 * association is found, we mobilize a client association and
879 * copy pertinent variables from the manycastclient or pool
880 * association to the new client association. If not, just
883 * There is an implosion hazard at the manycast client, since
884 * the manycast servers send the server packet immediately. If
885 * the guy is already here, don't fire up a duplicate.
891 * Do not respond if not the same group.
893 if (group_test(groupname, NULL)) {
898 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
900 return; /* not enabled */
902 if (!AUTH((!(peer2->cast_flags & MDF_POOL) &&
903 sys_authenticate) | (restrict_mask & (RES_NOPEER |
904 RES_DONTTRUST)), is_authentic)) {
906 return; /* access denied */
910 * Do not respond if unsynchronized or stratum is below
911 * the floor or at or above the ceiling.
913 if (hisleap == LEAP_NOTINSYNC || hisstratum <
914 sys_floor || hisstratum >= sys_ceiling) {
916 return; /* no help */
918 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
919 MODE_CLIENT, hisversion, peer2->minpoll,
920 peer2->maxpoll, FLAG_PREEMPT |
921 (FLAG_IBURST & peer2->flags), MDF_UCAST |
922 MDF_UCLNT, 0, skeyid, sys_ident);
925 return; /* ignore duplicate */
929 * After each ephemeral pool association is spun,
930 * accelerate the next poll for the pool solicitor so
931 * the pool will fill promptly.
933 if (peer2->cast_flags & MDF_POOL)
934 peer2->nextdate = current_time + 1;
937 * Further processing of the solicitation response would
938 * simply detect its origin timestamp as bogus for the
939 * brand-new association (it matches the prototype
940 * association) and tinker with peer->nextdate delaying
943 return; /* solicitation response handled */
946 * This is the first packet received from a broadcast server. If
947 * the packet is authentic and we are enabled as broadcast
948 * client, mobilize a broadcast client association. We don't
949 * kiss any frogs here.
955 * Do not respond if not the same group.
957 if (group_test(groupname, sys_ident)) {
962 if (sys_bclient == 0) {
964 return; /* not enabled */
966 if (!AUTH(sys_authenticate | (restrict_mask &
967 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
969 return; /* access denied */
973 * Do not respond if unsynchronized or stratum is below
974 * the floor or at or above the ceiling.
976 if (hisleap == LEAP_NOTINSYNC || hisstratum <
977 sys_floor || hisstratum >= sys_ceiling) {
979 return; /* no help */
984 * Do not respond if Autokey and the opcode is not a
985 * CRYPTO_ASSOC response with association ID.
987 if (crypto_flags && skeyid > NTP_MAXKEY && (opcode &
988 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
990 return; /* protocol error */
995 * Broadcasts received via a multicast address may
996 * arrive after a unicast volley has begun
997 * with the same remote address. newpeer() will not
998 * find duplicate associations on other local endpoints
999 * if a non-NULL endpoint is supplied. multicastclient
1000 * ephemeral associations are unique across all local
1003 if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1004 match_ep = rbufp->dstadr;
1009 * Determine whether to execute the initial volley.
1011 if (sys_bdelay != 0) {
1014 * If a two-way exchange is not possible,
1015 * neither is Autokey.
1017 if (crypto_flags && skeyid > NTP_MAXKEY) {
1019 return; /* no autokey */
1021 #endif /* AUTOKEY */
1024 * Do not execute the volley. Start out in
1025 * broadcast client mode.
1027 peer = newpeer(&rbufp->recv_srcadr, NULL,
1028 match_ep, MODE_BCLIENT, hisversion,
1029 pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1030 MDF_BCLNT, 0, skeyid, sys_ident);
1033 return; /* ignore duplicate */
1036 peer->delay = sys_bdelay;
1042 * Execute the initial volley in order to calibrate the
1043 * propagation delay and run the Autokey protocol.
1045 * Note that the minpoll is taken from the broadcast
1046 * packet, normally 6 (64 s) and that the poll interval
1047 * is fixed at this value.
1049 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1050 MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1051 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1052 0, skeyid, sys_ident);
1055 return; /* ignore duplicate */
1058 if (skeyid > NTP_MAXKEY)
1059 crypto_recv(peer, rbufp);
1060 #endif /* AUTOKEY */
1062 return; /* hooray */
1065 * This is the first packet received from a symmetric active
1066 * peer. If the packet is authentic and the first he sent,
1067 * mobilize a passive association. If not, kiss the frog.
1073 * Do not respond if not the same group.
1075 if (group_test(groupname, sys_ident)) {
1079 #endif /* AUTOKEY */
1080 if (!AUTH(sys_authenticate | (restrict_mask &
1081 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1084 * If authenticated but cannot mobilize an
1085 * association, send a symmetric passive
1086 * response without mobilizing an association.
1087 * This is for drat broken Windows clients. See
1088 * Microsoft KB 875424 for preferred workaround.
1090 if (AUTH(restrict_mask & RES_DONTTRUST,
1092 fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1094 return; /* hooray */
1096 if (is_authentic == AUTH_ERROR) {
1097 fast_xmit(rbufp, MODE_ACTIVE, 0,
1105 * Do not respond if synchronized and if stratum is
1106 * below the floor or at or above the ceiling. Note,
1107 * this allows an unsynchronized peer to synchronize to
1108 * us. It would be very strange if he did and then was
1109 * nipped, but that could only happen if we were
1110 * operating at the top end of the range. It also means
1111 * we will spin an ephemeral association in response to
1112 * MODE_ACTIVE KoDs, which will time out eventually.
1114 if (hisleap != LEAP_NOTINSYNC && (hisstratum <
1115 sys_floor || hisstratum >= sys_ceiling)) {
1117 return; /* no help */
1121 * The message is correctly authenticated and allowed.
1122 * Mobilize a symmetric passive association.
1124 if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1125 rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1126 NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1127 sys_ident)) == NULL) {
1129 return; /* ignore duplicate */
1135 * Process regular packet. Nothing special.
1141 * Do not respond if not the same group.
1143 if (group_test(groupname, peer->ident)) {
1147 #endif /* AUTOKEY */
1151 * A passive packet matches a passive association. This is
1152 * usually the result of reconfiguring a client on the fly. As
1153 * this association might be legitimate and this packet an
1154 * attempt to deny service, just ignore it.
1161 * For everything else there is the bit bucket.
1170 * If the association is configured for Autokey, the packet must
1171 * have a public key ID; if not, the packet must have a
1174 if (is_authentic != AUTH_CRYPTO && (((peer->flags &
1175 FLAG_SKEY) && skeyid <= NTP_MAXKEY) || (!(peer->flags &
1176 FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1180 #endif /* AUTOKEY */
1182 peer->flash &= ~PKT_TEST_MASK;
1183 if (peer->flags & FLAG_XBOGUS) {
1184 peer->flags &= ~FLAG_XBOGUS;
1185 peer->flash |= TEST3;
1189 * Next comes a rigorous schedule of timestamp checking. If the
1190 * transmit timestamp is zero, the server has not initialized in
1191 * interleaved modes or is horribly broken.
1193 if (L_ISZERO(&p_xmt)) {
1194 peer->flash |= TEST3; /* unsynch */
1197 * If the transmit timestamp duplicates a previous one, the
1198 * packet is a replay. This prevents the bad guys from replaying
1199 * the most recent packet, authenticated or not.
1201 } else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1202 peer->flash |= TEST1; /* duplicate */
1207 * If this is a broadcast mode packet, skip further checking. If
1208 * an initial volley, bail out now and let the client do its
1209 * stuff. If the origin timestamp is nonzero, this is an
1210 * interleaved broadcast. so restart the protocol.
1212 } else if (hismode == MODE_BROADCAST) {
1213 if (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) {
1214 peer->flags |= FLAG_XB;
1216 peer->borg = rbufp->recv_time;
1217 report_event(PEVNT_XLEAVE, peer, NULL);
1222 * Check for bogus packet in basic mode. If found, switch to
1223 * interleaved mode and resynchronize, but only after confirming
1224 * the packet is not bogus in symmetric interleaved mode.
1226 } else if (peer->flip == 0) {
1227 if (!L_ISEQU(&p_org, &peer->aorg)) {
1229 peer->flash |= TEST2; /* bogus */
1230 if (!L_ISZERO(&peer->dst) && L_ISEQU(&p_org,
1233 report_event(PEVNT_XLEAVE, peer, NULL);
1240 * Check for valid nonzero timestamp fields.
1242 } else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) ||
1243 L_ISZERO(&peer->dst)) {
1244 peer->flash |= TEST3; /* unsynch */
1247 * Check for bogus packet in interleaved symmetric mode. This
1248 * can happen if a packet is lost, duplicated or crossed. If
1249 * found, flip and resynchronize.
1251 } else if (!L_ISZERO(&peer->dst) && !L_ISEQU(&p_org,
1254 peer->flags |= FLAG_XBOGUS;
1255 peer->flash |= TEST2; /* bogus */
1259 * If this is a crypto_NAK, the server cannot authenticate a
1260 * client packet. The server might have just changed keys. Clear
1261 * the association and restart the protocol.
1263 if (is_authentic == AUTH_CRYPTO) {
1264 report_event(PEVNT_AUTH, peer, "crypto_NAK");
1265 peer->flash |= TEST5; /* bad auth */
1267 if (peer->flags & FLAG_PREEMPT) {
1273 peer_clear(peer, "AUTH");
1274 #endif /* AUTOKEY */
1278 * If the digest fails or it's missing for authenticated
1279 * associations, the client cannot authenticate a server
1280 * reply to a client packet previously sent. The loopback check
1281 * is designed to avoid a bait-and-switch attack, which was
1282 * possible in past versions. If symmetric modes, return a
1283 * crypto-NAK. The peer should restart the protocol.
1285 } else if (!AUTH(peer->keyid || has_mac ||
1286 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1287 report_event(PEVNT_AUTH, peer, "digest");
1288 peer->flash |= TEST5; /* bad auth */
1291 (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE))
1292 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1293 if (peer->flags & FLAG_PREEMPT) {
1299 peer_clear(peer, "AUTH");
1300 #endif /* AUTOKEY */
1305 * Update the state variables.
1307 if (peer->flip == 0) {
1308 if (hismode != MODE_BROADCAST)
1310 peer->dst = rbufp->recv_time;
1315 * Set the peer ppoll to the maximum of the packet ppoll and the
1316 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1317 * this maximum and advance the headway to give the sender some
1318 * headroom. Very intricate.
1320 peer->ppoll = max(peer->minpoll, pkt->ppoll);
1321 if (hismode == MODE_SERVER && hisleap == LEAP_NOTINSYNC &&
1322 hisstratum == STRATUM_UNSPEC && memcmp(&pkt->refid,
1325 report_event(PEVNT_RATE, peer, NULL);
1326 if (pkt->ppoll > peer->minpoll)
1327 peer->minpoll = peer->ppoll;
1328 peer->burst = peer->retry = 0;
1329 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1330 poll_update(peer, pkt->ppoll);
1331 return; /* kiss-o'-death */
1335 * That was hard and I am sweaty, but the packet is squeaky
1336 * clean. Get on with real work.
1338 peer->timereceived = current_time;
1339 if (is_authentic == AUTH_OK)
1340 peer->flags |= FLAG_AUTHENTIC;
1342 peer->flags &= ~FLAG_AUTHENTIC;
1346 * More autokey dance. The rules of the cha-cha are as follows:
1348 * 1. If there is no key or the key is not auto, do nothing.
1350 * 2. If this packet is in response to the one just previously
1351 * sent or from a broadcast server, do the extension fields.
1352 * Otherwise, assume bogosity and bail out.
1354 * 3. If an extension field contains a verified signature, it is
1355 * self-authenticated and we sit the dance.
1357 * 4. If this is a server reply, check only to see that the
1358 * transmitted key ID matches the received key ID.
1360 * 5. Check to see that one or more hashes of the current key ID
1361 * matches the previous key ID or ultimate original key ID
1362 * obtained from the broadcaster or symmetric peer. If no
1363 * match, sit the dance and call for new autokey values.
1365 * In case of crypto error, fire the orchestra, stop dancing and
1366 * restart the protocol.
1368 if (peer->flags & FLAG_SKEY) {
1370 * Decrement remaining autokey hashes. This isn't
1371 * perfect if a packet is lost, but results in no harm.
1373 ap = (struct autokey *)peer->recval.ptr;
1378 peer->flash |= TEST8;
1379 rval = crypto_recv(peer, rbufp);
1380 if (rval == XEVNT_OK) {
1383 if (rval == XEVNT_ERR) {
1384 report_event(PEVNT_RESTART, peer,
1386 peer_clear(peer, "CRYP");
1387 peer->flash |= TEST9; /* bad crypt */
1388 if (peer->flags & FLAG_PREEMPT)
1395 * If server mode, verify the receive key ID matches
1396 * the transmit key ID.
1398 if (hismode == MODE_SERVER) {
1399 if (skeyid == peer->keyid)
1400 peer->flash &= ~TEST8;
1403 * If an extension field is present, verify only that it
1404 * has been correctly signed. We don't need a sequence
1405 * check here, but the sequence continues.
1407 } else if (!(peer->flash & TEST8)) {
1408 peer->pkeyid = skeyid;
1411 * Now the fun part. Here, skeyid is the current ID in
1412 * the packet, pkeyid is the ID in the last packet and
1413 * tkeyid is the hash of skeyid. If the autokey values
1414 * have not been received, this is an automatic error.
1415 * If so, check that the tkeyid matches pkeyid. If not,
1416 * hash tkeyid and try again. If the number of hashes
1417 * exceeds the number remaining in the sequence, declare
1418 * a successful failure and refresh the autokey values.
1420 } else if (ap != NULL) {
1423 for (i = 0; ; i++) {
1424 if (tkeyid == peer->pkeyid ||
1425 tkeyid == ap->key) {
1426 peer->flash &= ~TEST8;
1427 peer->pkeyid = skeyid;
1436 tkeyid = session_key(
1437 &rbufp->recv_srcadr, dstadr_sin,
1440 if (peer->flash & TEST8)
1441 report_event(PEVNT_AUTH, peer, "keylist");
1443 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
1444 peer->flash |= TEST8; /* bad autokey */
1447 * The maximum lifetime of the protocol is about one
1448 * week before restarting the Autokey protocol to
1449 * refresh certificates and leapseconds values.
1451 if (current_time > peer->refresh) {
1452 report_event(PEVNT_RESTART, peer,
1454 peer_clear(peer, "TIME");
1458 #endif /* AUTOKEY */
1461 * The dance is complete and the flash bits have been lit. Toss
1462 * the packet over the fence for processing, which may light up
1465 process_packet(peer, pkt, rbufp->recv_length);
1468 * In interleaved mode update the state variables. Also adjust the
1469 * transmit phase to avoid crossover.
1471 if (peer->flip != 0) {
1473 peer->dst = rbufp->recv_time;
1474 if (peer->nextdate - current_time < (1U << min(peer->ppoll,
1484 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1485 * specification. Or almost, at least. If we're in here we have a
1486 * reasonable expectation that we will be having a long term
1487 * relationship with this host.
1491 register struct peer *peer,
1492 register struct pkt *pkt,
1497 double p_offset, p_del, p_disp;
1498 l_fp p_rec, p_xmt, p_org, p_reftime, ci;
1499 u_char pmode, pleap, pversion, pstratum;
1500 char statstr[NTP_MAXSTRLEN];
1503 double etemp, ftemp, td;
1508 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1510 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
1511 NTOHL_FP(&pkt->reftime, &p_reftime);
1512 NTOHL_FP(&pkt->org, &p_org);
1513 NTOHL_FP(&pkt->rec, &p_rec);
1514 NTOHL_FP(&pkt->xmt, &p_xmt);
1515 pmode = PKT_MODE(pkt->li_vn_mode);
1516 pleap = PKT_LEAP(pkt->li_vn_mode);
1517 pversion = PKT_VERSION(pkt->li_vn_mode);
1518 pstratum = PKT_TO_STRATUM(pkt->stratum);
1521 * Capture the header values in the client/peer association..
1523 record_raw_stats(&peer->srcadr, peer->dstadr ?
1524 &peer->dstadr->sin : NULL,
1525 &p_org, &p_rec, &p_xmt, &peer->dst,
1526 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
1527 p_del, p_disp, pkt->refid);
1529 peer->stratum = min(pstratum, STRATUM_UNSPEC);
1530 peer->pmode = pmode;
1531 peer->precision = pkt->precision;
1532 peer->rootdelay = p_del;
1533 peer->rootdisp = p_disp;
1534 peer->refid = pkt->refid; /* network byte order */
1535 peer->reftime = p_reftime;
1538 * First, if either burst mode is armed, enable the burst.
1539 * Compute the headway for the next packet and delay if
1540 * necessary to avoid exceeding the threshold.
1542 if (peer->retry > 0) {
1545 peer->burst = min(1 << (peer->hpoll -
1546 peer->minpoll), NTP_SHIFT) - 1;
1548 peer->burst = NTP_IBURST - 1;
1549 if (peer->burst > 0)
1550 peer->nextdate = current_time;
1552 poll_update(peer, peer->hpoll);
1555 * Verify the server is synchronized; that is, the leap bits,
1556 * stratum and root distance are valid.
1558 if (pleap == LEAP_NOTINSYNC || /* test 6 */
1559 pstratum < sys_floor || pstratum >= sys_ceiling)
1560 peer->flash |= TEST6; /* bad synch or strat */
1561 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
1562 peer->flash |= TEST7; /* bad header */
1565 * If any tests fail at this point, the packet is discarded.
1566 * Note that some flashers may have already been set in the
1567 * receive() routine.
1569 if (peer->flash & PKT_TEST_MASK) {
1570 peer->seldisptoolarge++;
1573 printf("packet: flash header %04x\n",
1580 * If the peer was previously unreachable, raise a trap. In any
1581 * case, mark it reachable.
1584 report_event(PEVNT_REACH, peer, NULL);
1585 peer->timereachable = current_time;
1590 * For a client/server association, calculate the clock offset,
1591 * roundtrip delay and dispersion. The equations are reordered
1592 * from the spec for more efficient use of temporaries. For a
1593 * broadcast association, offset the last measurement by the
1594 * computed delay during the client/server volley. Note the
1595 * computation of dispersion includes the system precision plus
1596 * that due to the frequency error since the origin time.
1598 * It is very important to respect the hazards of overflow. The
1599 * only permitted operation on raw timestamps is subtraction,
1600 * where the result is a signed quantity spanning from 68 years
1601 * in the past to 68 years in the future. To avoid loss of
1602 * precision, these calculations are done using 64-bit integer
1603 * arithmetic. However, the offset and delay calculations are
1604 * sums and differences of these first-order differences, which
1605 * if done using 64-bit integer arithmetic, would be valid over
1606 * only half that span. Since the typical first-order
1607 * differences are usually very small, they are converted to 64-
1608 * bit doubles and all remaining calculations done in floating-
1609 * double arithmetic. This preserves the accuracy while
1610 * retaining the 68-year span.
1612 * There are three interleaving schemes, basic, interleaved
1613 * symmetric and interleaved broadcast. The timestamps are
1614 * idioscyncratically different. See the onwire briefing/white
1615 * paper at www.eecis.udel.edu/~mills for details.
1617 * Interleaved symmetric mode
1618 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
1621 if (peer->flip != 0) {
1622 ci = p_xmt; /* t3 - t4 */
1623 L_SUB(&ci, &peer->dst);
1625 ci = p_rec; /* t2 - t1 */
1627 L_SUB(&ci, &peer->borg);
1629 L_SUB(&ci, &peer->aorg);
1632 p_offset = (t21 + t34) / 2.;
1633 if (p_del < 0 || p_del > 1.) {
1634 snprintf(statstr, sizeof(statstr),
1635 "t21 %.6f t34 %.6f", t21, t34);
1636 report_event(PEVNT_XERR, peer, statstr);
1643 } else if (peer->pmode == MODE_BROADCAST) {
1646 * Interleaved broadcast mode. Use interleaved timestamps.
1647 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
1649 if (peer->flags & FLAG_XB) {
1650 ci = p_org; /* delay */
1651 L_SUB(&ci, &peer->aorg);
1653 ci = p_org; /* t2 - t1 */
1654 L_SUB(&ci, &peer->borg);
1657 peer->borg = peer->dst;
1658 if (t34 < 0 || t34 > 1.) {
1659 snprintf(statstr, sizeof(statstr),
1660 "offset %.6f delay %.6f", t21, t34);
1661 report_event(PEVNT_XERR, peer, statstr);
1668 * Basic broadcast - use direct timestamps.
1669 * t3 = p_xmt, t4 = peer->dst
1672 ci = p_xmt; /* t3 - t4 */
1673 L_SUB(&ci, &peer->dst);
1679 * When calibration is complete and the clock is
1680 * synchronized, the bias is calculated as the difference
1681 * between the unicast timestamp and the broadcast
1682 * timestamp. This works for both basic and interleaved
1685 if (FLAG_BC_VOL & peer->flags) {
1686 peer->flags &= ~FLAG_BC_VOL;
1687 peer->delay = fabs(peer->offset - p_offset) * 2;
1689 p_del = peer->delay;
1690 p_offset += p_del / 2;
1694 * Basic mode, otherwise known as the old fashioned way.
1696 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
1699 ci = p_xmt; /* t3 - t4 */
1700 L_SUB(&ci, &peer->dst);
1702 ci = p_rec; /* t2 - t1 */
1705 p_del = fabs(t21 - t34);
1706 p_offset = (t21 + t34) / 2.;
1708 p_del = max(p_del, LOGTOD(sys_precision));
1709 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
1714 * This code calculates the outbound and inbound data rates by
1715 * measuring the differences between timestamps at different
1716 * packet lengths. This is helpful in cases of large asymmetric
1717 * delays commonly experienced on deep space communication
1720 if (peer->t21_last > 0 && peer->t34_bytes > 0) {
1721 itemp = peer->t21_bytes - peer->t21_last;
1723 etemp = t21 - peer->t21;
1724 if (fabs(etemp) > 1e-6) {
1725 ftemp = itemp / etemp;
1730 itemp = len - peer->t34_bytes;
1732 etemp = -t34 - peer->t34;
1733 if (fabs(etemp) > 1e-6) {
1734 ftemp = itemp / etemp;
1742 * The following section compensates for different data rates on
1743 * the outbound (d21) and inbound (t34) directions. To do this,
1744 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
1745 * the roundtrip delay. Then it calculates the correction as a
1749 peer->t21_last = peer->t21_bytes;
1751 peer->t34_bytes = len;
1754 printf("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
1755 peer->t21_bytes, peer->t34, peer->t34_bytes);
1757 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
1758 if (peer->pmode != MODE_BROADCAST)
1759 td = (peer->r34 / (peer->r21 + peer->r34) -
1765 * Unfortunately, in many cases the errors are
1766 * unacceptable, so for the present the rates are not
1767 * used. In future, we might find conditions where the
1768 * calculations are useful, so this should be considered
1769 * a work in progress.
1775 printf("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
1776 p_del, peer->r21 / 1e3, peer->r34 / 1e3,
1783 * That was awesome. Now hand off to the clock filter.
1785 clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
1788 * If we are in broadcast calibrate mode, return to broadcast
1789 * client mode when the client is fit and the autokey dance is
1792 if ((FLAG_BC_VOL & peer->flags) && MODE_CLIENT == peer->hmode &&
1793 !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
1795 if (peer->flags & FLAG_SKEY) {
1796 if (!(~peer->crypto & CRYPTO_FLAG_ALL))
1797 peer->hmode = MODE_BCLIENT;
1799 peer->hmode = MODE_BCLIENT;
1801 #else /* !AUTOKEY follows */
1802 peer->hmode = MODE_BCLIENT;
1803 #endif /* !AUTOKEY */
1809 * clock_update - Called at system process update intervals.
1813 struct peer *peer /* peer structure pointer */
1818 #ifdef HAVE_LIBSCF_H
1820 #endif /* HAVE_LIBSCF_H */
1823 * Update the system state variables. We do this very carefully,
1824 * as the poll interval might need to be clamped differently.
1827 sys_epoch = peer->epoch;
1828 if (sys_poll < peer->minpoll)
1829 sys_poll = peer->minpoll;
1830 if (sys_poll > peer->maxpoll)
1831 sys_poll = peer->maxpoll;
1832 poll_update(peer, sys_poll);
1833 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
1834 if (peer->stratum == STRATUM_REFCLOCK ||
1835 peer->stratum == STRATUM_UNSPEC)
1836 sys_refid = peer->refid;
1838 sys_refid = addr2refid(&peer->srcadr);
1840 * Root Dispersion (E) is defined (in RFC 5905) as:
1842 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
1845 * p.epsilon_r is the PollProc's root dispersion
1846 * p.epsilon is the PollProc's dispersion
1847 * p.psi is the PollProc's jitter
1848 * THETA is the combined offset
1850 * NB: Think Hard about where these numbers come from and
1851 * what they mean. When did peer->update happen? Has anything
1852 * interesting happened since then? What values are the most
1855 * DLM thinks this equation is probably the best of all worse choices.
1857 dtemp = peer->rootdisp
1860 + clock_phi * (current_time - peer->update)
1863 if (dtemp > sys_mindisp)
1864 sys_rootdisp = dtemp;
1866 sys_rootdisp = sys_mindisp;
1867 sys_rootdelay = peer->delay + peer->rootdelay;
1868 sys_reftime = peer->dst;
1873 "clock_update: at %lu sample %lu associd %d\n",
1874 current_time, peer->epoch, peer->associd);
1878 * Comes now the moment of truth. Crank the clock discipline and
1879 * see what comes out.
1881 switch (local_clock(peer, sys_offset)) {
1884 * Clock exceeds panic threshold. Life as we know it ends.
1887 #ifdef HAVE_LIBSCF_H
1889 * For Solaris enter the maintenance mode.
1891 if ((fmri = getenv("SMF_FMRI")) != NULL) {
1892 if (smf_maintain_instance(fmri, 0) < 0) {
1893 printf("smf_maintain_instance: %s\n",
1894 scf_strerror(scf_error()));
1898 * Sleep until SMF kills us.
1903 #endif /* HAVE_LIBSCF_H */
1908 * Clock was stepped. Flush all time values of all peers.
1912 sys_leap = LEAP_NOTINSYNC;
1913 sys_stratum = STRATUM_UNSPEC;
1914 memcpy(&sys_refid, "STEP", 4);
1917 L_CLR(&sys_reftime);
1918 sys_jitter = LOGTOD(sys_precision);
1919 leapsec_reset_frame();
1923 * Clock was slewed. Handle the leapsecond stuff.
1928 * If this is the first time the clock is set, reset the
1929 * leap bits. If crypto, the timer will goose the setup
1932 if (sys_leap == LEAP_NOTINSYNC) {
1933 sys_leap = LEAP_NOWARNING;
1937 #endif /* AUTOKEY */
1939 * If our parent process is waiting for the
1940 * first clock sync, send them home satisfied.
1942 #ifdef HAVE_WORKING_FORK
1943 if (waitsync_fd_to_close != -1) {
1944 close(waitsync_fd_to_close);
1945 waitsync_fd_to_close = -1;
1946 DPRINTF(1, ("notified parent --wait-sync is done\n"));
1948 #endif /* HAVE_WORKING_FORK */
1953 * If there is no leap second pending and the number of
1954 * survivor leap bits is greater than half the number of
1955 * survivors, try to schedule a leap for the end of the
1956 * current month. (This only works if no leap second for
1957 * that range is in the table, so doing this more than
1958 * once is mostly harmless.)
1960 if (leapsec == LSPROX_NOWARN) {
1961 if (leap_vote_ins > leap_vote_del
1962 && leap_vote_ins > sys_survivors / 2) {
1964 leapsec_add_dyn(TRUE, now.l_ui, NULL);
1966 if (leap_vote_del > leap_vote_ins
1967 && leap_vote_del > sys_survivors / 2) {
1969 leapsec_add_dyn(FALSE, now.l_ui, NULL);
1975 * Popcorn spike or step threshold exceeded. Pretend it never
1985 * poll_update - update peer poll interval
1989 struct peer *peer, /* peer structure pointer */
1997 * This routine figures out when the next poll should be sent.
1998 * That turns out to be wickedly complicated. One problem is
1999 * that sometimes the time for the next poll is in the past when
2000 * the poll interval is reduced. We watch out for races here
2001 * between the receive process and the poll process.
2003 * Clamp the poll interval between minpoll and maxpoll.
2005 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2009 * If during the crypto protocol the poll interval has changed,
2010 * the lifetimes in the key list are probably bogus. Purge the
2011 * the key list and regenerate it later.
2013 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2015 #endif /* AUTOKEY */
2016 peer->hpoll = hpoll;
2019 * There are three variables important for poll scheduling, the
2020 * current time (current_time), next scheduled time (nextdate)
2021 * and the earliest time (utemp). The earliest time is 2 s
2022 * seconds, but could be more due to rate management. When
2023 * sending in a burst, use the earliest time. When not in a
2024 * burst but with a reply pending, send at the earliest time
2025 * unless the next scheduled time has not advanced. This can
2026 * only happen if multiple replies are pending in the same
2027 * response interval. Otherwise, send at the later of the next
2028 * scheduled time and the earliest time.
2030 * Now we figure out if there is an override. If a burst is in
2031 * progress and we get called from the receive process, just
2032 * slink away. If called from the poll process, delay 1 s for a
2033 * reference clock, otherwise 2 s.
2035 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2036 (1 << peer->minpoll), ntp_minpkt);
2037 if (peer->burst > 0) {
2038 if (peer->nextdate > current_time)
2041 else if (peer->flags & FLAG_REFCLOCK)
2042 peer->nextdate = current_time + RESP_DELAY;
2043 #endif /* REFCLOCK */
2045 peer->nextdate = utemp;
2049 * If a burst is not in progress and a crypto response message
2050 * is pending, delay 2 s, but only if this is a new interval.
2052 } else if (peer->cmmd != NULL) {
2053 if (peer->nextdate > current_time) {
2054 if (peer->nextdate + ntp_minpkt != utemp)
2055 peer->nextdate = utemp;
2057 peer->nextdate = utemp;
2059 #endif /* AUTOKEY */
2062 * The ordinary case. If a retry, use minpoll; if unreachable,
2063 * use host poll; otherwise, use the minimum of host and peer
2064 * polls; In other words, oversampling is okay but
2065 * understampling is evil. Use the maximum of this value and the
2066 * headway. If the average headway is greater than the headway
2067 * threshold, increase the headway by the minimum interval.
2070 if (peer->retry > 0)
2071 hpoll = peer->minpoll;
2072 else if (!(peer->reach))
2073 hpoll = peer->hpoll;
2075 hpoll = min(peer->ppoll, peer->hpoll);
2077 if (peer->flags & FLAG_REFCLOCK)
2080 #endif /* REFCLOCK */
2081 next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2083 next += peer->outdate;
2085 peer->nextdate = next;
2087 peer->nextdate = utemp;
2088 if (peer->throttle > (1 << peer->minpoll))
2089 peer->nextdate += ntp_minpkt;
2091 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2092 current_time, ntoa(&peer->srcadr), peer->hpoll,
2093 peer->burst, peer->retry, peer->throttle,
2094 utemp - current_time, peer->nextdate -
2100 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
2105 struct peer *peer, /* peer structure */
2106 const char *ident /* tally lights */
2113 * If cryptographic credentials have been acquired, toss them to
2114 * Valhalla. Note that autokeys are ephemeral, in that they are
2115 * tossed immediately upon use. Therefore, the keylist can be
2116 * purged anytime without needing to preserve random keys. Note
2117 * that, if the peer is purged, the cryptographic variables are
2118 * purged, too. This makes it much harder to sneak in some
2119 * unauthenticated data in the clock filter.
2122 if (peer->iffval != NULL)
2123 BN_free(peer->iffval);
2124 value_free(&peer->cookval);
2125 value_free(&peer->recval);
2126 value_free(&peer->encrypt);
2127 value_free(&peer->sndval);
2128 if (peer->cmmd != NULL)
2130 if (peer->subject != NULL)
2131 free(peer->subject);
2132 if (peer->issuer != NULL)
2134 #endif /* AUTOKEY */
2137 * Clear all values, including the optional crypto values above.
2139 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
2140 peer->ppoll = peer->maxpoll;
2141 peer->hpoll = peer->minpoll;
2142 peer->disp = MAXDISPERSE;
2143 peer->flash = peer_unfit(peer);
2144 peer->jitter = LOGTOD(sys_precision);
2147 * If interleave mode, initialize the alternate origin switch.
2149 if (peer->flags & FLAG_XLEAVE)
2151 for (u = 0; u < NTP_SHIFT; u++) {
2152 peer->filter_order[u] = u;
2153 peer->filter_disp[u] = MAXDISPERSE;
2156 if (!(peer->flags & FLAG_REFCLOCK)) {
2158 peer->leap = LEAP_NOTINSYNC;
2159 peer->stratum = STRATUM_UNSPEC;
2160 memcpy(&peer->refid, ident, 4);
2166 * During initialization use the association count to spread out
2167 * the polls at one-second intervals. Passive associations'
2168 * first poll is delayed by the "discard minimum" to avoid rate
2169 * limiting. Other post-startup new or cleared associations
2170 * randomize the first poll over the minimum poll interval to
2173 peer->nextdate = peer->update = peer->outdate = current_time;
2175 peer->nextdate += peer_associations;
2176 } else if (MODE_PASSIVE == peer->hmode) {
2177 peer->nextdate += ntp_minpkt;
2179 peer->nextdate += ntp_random() % peer->minpoll;
2182 peer->refresh = current_time + (1 << NTP_REFRESH);
2183 #endif /* AUTOKEY */
2187 "peer_clear: at %ld next %ld associd %d refid %s\n",
2188 current_time, peer->nextdate, peer->associd,
2195 * clock_filter - add incoming clock sample to filter register and run
2196 * the filter procedure to find the best sample.
2200 struct peer *peer, /* peer structure pointer */
2201 double sample_offset, /* clock offset */
2202 double sample_delay, /* roundtrip delay */
2203 double sample_disp /* dispersion */
2206 double dst[NTP_SHIFT]; /* distance vector */
2207 int ord[NTP_SHIFT]; /* index vector */
2209 double dtemp, etemp;
2213 * A sample consists of the offset, delay, dispersion and epoch
2214 * of arrival. The offset and delay are determined by the on-
2215 * wire protocol. The dispersion grows from the last outbound
2216 * packet to the arrival of this one increased by the sum of the
2217 * peer precision and the system precision as required by the
2218 * error budget. First, shift the new arrival into the shift
2219 * register discarding the oldest one.
2221 j = peer->filter_nextpt;
2222 peer->filter_offset[j] = sample_offset;
2223 peer->filter_delay[j] = sample_delay;
2224 peer->filter_disp[j] = sample_disp;
2225 peer->filter_epoch[j] = current_time;
2226 j = (j + 1) % NTP_SHIFT;
2227 peer->filter_nextpt = j;
2230 * Update dispersions since the last update and at the same
2231 * time initialize the distance and index lists. Since samples
2232 * become increasingly uncorrelated beyond the Allan intercept,
2233 * only under exceptional cases will an older sample be used.
2234 * Therefore, the distance list uses a compound metric. If the
2235 * dispersion is greater than the maximum dispersion, clamp the
2236 * distance at that value. If the time since the last update is
2237 * less than the Allan intercept use the delay; otherwise, use
2238 * the sum of the delay and dispersion.
2240 dtemp = clock_phi * (current_time - peer->update);
2241 peer->update = current_time;
2242 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2244 peer->filter_disp[j] += dtemp;
2245 if (peer->filter_disp[j] >= MAXDISPERSE) {
2246 peer->filter_disp[j] = MAXDISPERSE;
2247 dst[i] = MAXDISPERSE;
2248 } else if (peer->update - peer->filter_epoch[j] >
2249 (u_long)ULOGTOD(allan_xpt)) {
2250 dst[i] = peer->filter_delay[j] +
2251 peer->filter_disp[j];
2253 dst[i] = peer->filter_delay[j];
2256 j = (j + 1) % NTP_SHIFT;
2260 * If the clock has stabilized, sort the samples by distance.
2262 if (freq_cnt == 0) {
2263 for (i = 1; i < NTP_SHIFT; i++) {
2264 for (j = 0; j < i; j++) {
2265 if (dst[j] > dst[i]) {
2278 * Copy the index list to the association structure so ntpq
2279 * can see it later. Prune the distance list to leave only
2280 * samples less than the maximum dispersion, which disfavors
2281 * uncorrelated samples older than the Allan intercept. To
2282 * further improve the jitter estimate, of the remainder leave
2283 * only samples less than the maximum distance, but keep at
2284 * least two samples for jitter calculation.
2287 for (i = 0; i < NTP_SHIFT; i++) {
2288 peer->filter_order[i] = (u_char) ord[i];
2289 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
2296 * Compute the dispersion and jitter. The dispersion is weighted
2297 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2298 * to 1.0. The jitter is the RMS differences relative to the
2299 * lowest delay sample.
2301 peer->disp = peer->jitter = 0;
2303 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2305 peer->disp = NTP_FWEIGHT * (peer->disp +
2306 peer->filter_disp[j]);
2308 peer->jitter += DIFF(peer->filter_offset[j],
2309 peer->filter_offset[k]);
2313 * If no acceptable samples remain in the shift register,
2314 * quietly tiptoe home leaving only the dispersion. Otherwise,
2315 * save the offset, delay and jitter. Note the jitter must not
2316 * be less than the precision.
2322 etemp = fabs(peer->offset - peer->filter_offset[k]);
2323 peer->offset = peer->filter_offset[k];
2324 peer->delay = peer->filter_delay[k];
2326 peer->jitter /= m - 1;
2327 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
2330 * If the the new sample and the current sample are both valid
2331 * and the difference between their offsets exceeds CLOCK_SGATE
2332 * (3) times the jitter and the interval between them is less
2333 * than twice the host poll interval, consider the new sample
2334 * a popcorn spike and ignore it.
2336 if (peer->disp < sys_maxdist && peer->filter_disp[k] <
2337 sys_maxdist && etemp > CLOCK_SGATE * peer->jitter &&
2338 peer->filter_epoch[k] - peer->epoch < 2. *
2339 ULOGTOD(peer->hpoll)) {
2340 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
2341 report_event(PEVNT_POPCORN, peer, tbuf);
2346 * A new minimum sample is useful only if it is later than the
2347 * last one used. In this design the maximum lifetime of any
2348 * sample is not greater than eight times the poll interval, so
2349 * the maximum interval between minimum samples is eight
2352 if (peer->filter_epoch[k] <= peer->epoch) {
2355 printf("clock_filter: old sample %lu\n", current_time -
2356 peer->filter_epoch[k]);
2360 peer->epoch = peer->filter_epoch[k];
2363 * The mitigated sample statistics are saved for later
2364 * processing. If not synchronized or not in a burst, tickle the
2365 * clock select algorithm.
2367 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
2368 peer->offset, peer->delay, peer->disp, peer->jitter);
2372 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
2373 m, peer->offset, peer->delay, peer->disp,
2376 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
2382 * clock_select - find the pick-of-the-litter clock
2384 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
2385 * be enabled, even if declared falseticker, (2) only the prefer peer
2386 * can be selected as the system peer, (3) if the external source is
2387 * down, the system leap bits are set to 11 and the stratum set to
2401 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
2402 struct endpoint endp;
2403 struct peer *osys_peer;
2404 struct peer *sys_prefer = NULL; /* prefer peer */
2405 struct peer *typesystem = NULL;
2406 struct peer *typeorphan = NULL;
2408 struct peer *typeacts = NULL;
2409 struct peer *typelocal = NULL;
2410 struct peer *typepps = NULL;
2411 #endif /* REFCLOCK */
2412 static struct endpoint *endpoint = NULL;
2413 static int *indx = NULL;
2414 static peer_select *peers = NULL;
2415 static u_int endpoint_size = 0;
2416 static u_int peers_size = 0;
2417 static u_int indx_size = 0;
2421 * Initialize and create endpoint, index and peer lists big
2422 * enough to handle all associations.
2424 osys_peer = sys_peer;
2427 sys_leap = LEAP_NOTINSYNC;
2428 sys_stratum = STRATUM_UNSPEC;
2429 memcpy(&sys_refid, "DOWN", 4);
2430 #endif /* LOCKCLOCK */
2433 * Allocate dynamic space depending on the number of
2437 for (peer = peer_list; peer != NULL; peer = peer->p_link)
2439 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
2440 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
2441 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
2442 octets = endpoint_size + peers_size + indx_size;
2443 endpoint = erealloc(endpoint, octets);
2444 peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
2445 indx = INC_ALIGNED_PTR(peers, peers_size);
2448 * Initially, we populate the island with all the rifraff peers
2449 * that happen to be lying around. Those with seriously
2450 * defective clocks are immediately booted off the island. Then,
2451 * the falsetickers are culled and put to sea. The truechimers
2452 * remaining are subject to repeated rounds where the most
2453 * unpopular at each round is kicked off. When the population
2454 * has dwindled to sys_minclock, the survivors split a million
2455 * bucks and collectively crank the chimes.
2457 nlist = nl2 = 0; /* none yet */
2458 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
2459 peer->new_status = CTL_PST_SEL_REJECT;
2462 * Leave the island immediately if the peer is
2463 * unfit to synchronize.
2465 if (peer_unfit(peer))
2469 * If this peer is an orphan parent, elect the
2470 * one with the lowest metric defined as the
2471 * IPv4 address or the first 64 bits of the
2472 * hashed IPv6 address. To ensure convergence
2473 * on the same selected orphan, consider as
2474 * well that this system may have the lowest
2475 * metric and be the orphan parent. If this
2476 * system wins, sys_peer will be NULL to trigger
2477 * orphan mode in timer().
2479 if (peer->stratum == sys_orphan) {
2483 if (peer->dstadr != NULL)
2484 localmet = ntohl(peer->dstadr->addr_refid);
2486 localmet = U_INT32_MAX;
2487 peermet = ntohl(addr2refid(&peer->srcadr));
2488 if (peermet < localmet && peermet < orphmet) {
2496 * If this peer could have the orphan parent
2497 * as a synchronization ancestor, exclude it
2498 * from selection to avoid forming a
2499 * synchronization loop within the orphan mesh,
2500 * triggering stratum climb to infinity
2501 * instability. Peers at stratum higher than
2502 * the orphan stratum could have the orphan
2503 * parent in ancestry so are excluded.
2504 * See http://bugs.ntp.org/2050
2506 if (peer->stratum > sys_orphan)
2510 * The following are special cases. We deal
2513 if (!(peer->flags & FLAG_PREFER)) {
2514 switch (peer->refclktype) {
2515 case REFCLK_LOCALCLOCK:
2516 if (current_time > orphwait &&
2522 if (current_time > orphwait &&
2528 #endif /* REFCLOCK */
2531 * If we get this far, the peer can stay on the
2532 * island, but does not yet have the immunity
2535 peer->new_status = CTL_PST_SEL_SANE;
2536 f = root_distance(peer);
2537 peers[nlist].peer = peer;
2538 peers[nlist].error = peer->jitter;
2539 peers[nlist].synch = f;
2543 * Insert each interval endpoint on the unsorted
2547 endpoint[nl2].type = -1; /* lower end */
2548 endpoint[nl2].val = e - f;
2550 endpoint[nl2].type = 1; /* upper end */
2551 endpoint[nl2].val = e + f;
2555 * Construct sorted indx[] of endpoint[] indexes ordered by
2558 for (i = 0; i < nl2; i++)
2560 for (i = 0; i < nl2; i++) {
2561 endp = endpoint[indx[i]];
2564 for (j = i + 1; j < nl2; j++) {
2565 endp = endpoint[indx[j]];
2577 for (i = 0; i < nl2; i++)
2578 DPRINTF(3, ("select: endpoint %2d %.6f\n",
2579 endpoint[indx[i]].type, endpoint[indx[i]].val));
2582 * This is the actual algorithm that cleaves the truechimers
2583 * from the falsetickers. The original algorithm was described
2584 * in Keith Marzullo's dissertation, but has been modified for
2587 * Briefly put, we first assume there are no falsetickers, then
2588 * scan the candidate list first from the low end upwards and
2589 * then from the high end downwards. The scans stop when the
2590 * number of intersections equals the number of candidates less
2591 * the number of falsetickers. If this doesn't happen for a
2592 * given number of falsetickers, we bump the number of
2593 * falsetickers and try again. If the number of falsetickers
2594 * becomes equal to or greater than half the number of
2595 * candidates, the Albanians have won the Byzantine wars and
2596 * correct synchronization is not possible.
2598 * Here, nlist is the number of candidates and allow is the
2599 * number of falsetickers. Upon exit, the truechimers are the
2600 * survivors with offsets not less than low and not greater than
2601 * high. There may be none of them.
2605 for (allow = 0; 2 * allow < nlist; allow++) {
2608 * Bound the interval (low, high) as the smallest
2609 * interval containing points from the most sources.
2612 for (i = 0; i < nl2; i++) {
2613 low = endpoint[indx[i]].val;
2614 n -= endpoint[indx[i]].type;
2615 if (n >= nlist - allow)
2619 for (j = nl2 - 1; j >= 0; j--) {
2620 high = endpoint[indx[j]].val;
2621 n += endpoint[indx[j]].type;
2622 if (n >= nlist - allow)
2627 * If an interval containing truechimers is found, stop.
2628 * If not, increase the number of falsetickers and go
2636 * Clustering algorithm. Whittle candidate list of falsetickers,
2637 * who leave the island immediately. The TRUE peer is always a
2638 * truechimer. We must leave at least one peer to collect the
2641 * We assert the correct time is contained in the interval, but
2642 * the best offset estimate for the interval might not be
2643 * contained in the interval. For this purpose, a truechimer is
2644 * defined as the midpoint of an interval that overlaps the
2645 * intersection interval.
2648 for (i = 0; i < nlist; i++) {
2651 peer = peers[i].peer;
2653 if ((high <= low || peer->offset + h < low ||
2654 peer->offset - h > high) && !(peer->flags & FLAG_TRUE))
2659 * Eligible PPS peers must survive the intersection
2660 * algorithm. Use the first one found, but don't
2661 * include any of them in the cluster population.
2663 if (peer->flags & FLAG_PPS) {
2664 if (typepps == NULL)
2666 if (!(peer->flags & FLAG_TSTAMP_PPS))
2669 #endif /* REFCLOCK */
2672 peers[j] = peers[i];
2678 * If no survivors remain at this point, check if the modem
2679 * driver, local driver or orphan parent in that order. If so,
2680 * nominate the first one found as the only survivor.
2681 * Otherwise, give up and leave the island to the rats.
2685 peers[0].synch = sys_mindisp;
2687 if (typeacts != NULL) {
2688 peers[0].peer = typeacts;
2690 } else if (typelocal != NULL) {
2691 peers[0].peer = typelocal;
2694 #endif /* REFCLOCK */
2695 if (typeorphan != NULL) {
2696 peers[0].peer = typeorphan;
2702 * Mark the candidates at this point as truechimers.
2704 for (i = 0; i < nlist; i++) {
2705 peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
2706 DPRINTF(2, ("select: survivor %s %f\n",
2707 stoa(&peers[i].peer->srcadr), peers[i].synch));
2711 * Now, vote outlyers off the island by select jitter weighted
2712 * by root distance. Continue voting as long as there are more
2713 * than sys_minclock survivors and the select jitter of the peer
2714 * with the worst metric is greater than the minimum peer
2715 * jitter. Stop if we are about to discard a TRUE or PREFER
2716 * peer, who of course have the immunity idol.
2723 for (i = 0; i < nlist; i++) {
2724 if (peers[i].error < d)
2726 peers[i].seljit = 0;
2729 for (j = 0; j < nlist; j++)
2730 f += DIFF(peers[j].peer->offset,
2731 peers[i].peer->offset);
2732 peers[i].seljit = SQRT(f / (nlist - 1));
2734 if (peers[i].seljit * peers[i].synch > e) {
2735 g = peers[i].seljit;
2736 e = peers[i].seljit * peers[i].synch;
2740 g = max(g, LOGTOD(sys_precision));
2741 if (nlist <= max(1, sys_minclock) || g <= d ||
2742 ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
2745 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
2746 ntoa(&peers[k].peer->srcadr), g, d));
2747 if (nlist > sys_maxclock)
2748 peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
2749 for (j = k + 1; j < nlist; j++)
2750 peers[j - 1] = peers[j];
2755 * What remains is a list usually not greater than sys_minclock
2756 * peers. Note that unsynchronized peers cannot survive this
2757 * far. Count and mark these survivors.
2759 * While at it, count the number of leap warning bits found.
2760 * This will be used later to vote the system leap warning bit.
2761 * If a leap warning bit is found on a reference clock, the vote
2764 * Choose the system peer using a hybrid metric composed of the
2765 * selection jitter scaled by the root distance augmented by
2766 * stratum scaled by sys_mindisp (.001 by default). The goal of
2767 * the small stratum factor is to avoid clockhop between a
2768 * reference clock and a network peer which has a refclock and
2769 * is using an older ntpd, which does not floor sys_rootdisp at
2772 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
2773 * in selecting the system peer, using a weight of 1 second of
2774 * additional root distance per stratum. This heavy bias is no
2775 * longer appropriate, as the scaled root distance provides a
2776 * more rational metric carrying the cumulative error budget.
2782 for (i = 0; i < nlist; i++) {
2783 peer = peers[i].peer;
2785 peer->new_status = CTL_PST_SEL_SYNCCAND;
2787 if (peer->leap == LEAP_ADDSECOND) {
2788 if (peer->flags & FLAG_REFCLOCK)
2789 leap_vote_ins = nlist;
2790 else if (leap_vote_ins < nlist)
2793 if (peer->leap == LEAP_DELSECOND) {
2794 if (peer->flags & FLAG_REFCLOCK)
2795 leap_vote_del = nlist;
2796 else if (leap_vote_del < nlist)
2799 if (peer->flags & FLAG_PREFER)
2801 speermet = peers[i].seljit * peers[i].synch +
2802 peer->stratum * sys_mindisp;
2810 * Unless there are at least sys_misane survivors, leave the
2811 * building dark. Otherwise, do a clockhop dance. Ordinarily,
2812 * use the selected survivor speer. However, if the current
2813 * system peer is not speer, stay with the current system peer
2814 * as long as it doesn't get too old or too ugly.
2816 if (nlist > 0 && nlist >= sys_minsane) {
2819 typesystem = peers[speer].peer;
2820 if (osys_peer == NULL || osys_peer == typesystem) {
2822 } else if ((x = fabs(typesystem->offset -
2823 osys_peer->offset)) < sys_mindisp) {
2824 if (sys_clockhop == 0)
2825 sys_clockhop = sys_mindisp;
2828 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
2829 j, x, sys_clockhop));
2830 if (fabs(x) < sys_clockhop)
2831 typesystem = osys_peer;
2840 * Mitigation rules of the game. We have the pick of the
2841 * litter in typesystem if any survivors are left. If
2842 * there is a prefer peer, use its offset and jitter.
2843 * Otherwise, use the combined offset and jitter of all kitters.
2845 if (typesystem != NULL) {
2846 if (sys_prefer == NULL) {
2847 typesystem->new_status = CTL_PST_SEL_SYSPEER;
2848 clock_combine(peers, sys_survivors, speer);
2850 typesystem = sys_prefer;
2852 typesystem->new_status = CTL_PST_SEL_SYSPEER;
2853 sys_offset = typesystem->offset;
2854 sys_jitter = typesystem->jitter;
2856 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
2857 sys_offset, sys_jitter));
2861 * If a PPS driver is lit and the combined offset is less than
2862 * 0.4 s, select the driver as the PPS peer and use its offset
2863 * and jitter. However, if this is the atom driver, use it only
2864 * if there is a prefer peer or there are no survivors and none
2867 if (typepps != NULL && fabs(sys_offset) < 0.4 &&
2868 (typepps->refclktype != REFCLK_ATOM_PPS ||
2869 (typepps->refclktype == REFCLK_ATOM_PPS && (sys_prefer !=
2870 NULL || (typesystem == NULL && sys_minsane == 0))))) {
2871 typesystem = typepps;
2873 typesystem->new_status = CTL_PST_SEL_PPS;
2874 sys_offset = typesystem->offset;
2875 sys_jitter = typesystem->jitter;
2876 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
2877 sys_offset, sys_jitter));
2879 #endif /* REFCLOCK */
2882 * If there are no survivors at this point, there is no
2883 * system peer. If so and this is an old update, keep the
2884 * current statistics, but do not update the clock.
2886 if (typesystem == NULL) {
2887 if (osys_peer != NULL) {
2888 if (sys_orphwait > 0)
2889 orphwait = current_time + sys_orphwait;
2890 report_event(EVNT_NOPEER, NULL, NULL);
2893 for (peer = peer_list; peer != NULL; peer = peer->p_link)
2894 peer->status = peer->new_status;
2899 * Do not use old data, as this may mess up the clock discipline
2902 if (typesystem->epoch <= sys_epoch)
2906 * We have found the alpha male. Wind the clock.
2908 if (osys_peer != typesystem)
2909 report_event(PEVNT_NEWPEER, typesystem, NULL);
2910 for (peer = peer_list; peer != NULL; peer = peer->p_link)
2911 peer->status = peer->new_status;
2912 clock_update(typesystem);
2918 peer_select * peers, /* survivor list */
2919 int npeers, /* number of survivors */
2920 int syspeer /* index of sys.peer */
2927 for (i = 0; i < npeers; i++) {
2928 x = 1. / peers[i].synch;
2930 z += x * peers[i].peer->offset;
2931 w += x * DIFF(peers[i].peer->offset,
2932 peers[syspeer].peer->offset);
2935 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
2940 * root_distance - compute synchronization distance from peer to root
2944 struct peer *peer /* peer structure pointer */
2950 * Root Distance (LAMBDA) is defined as:
2951 * (delta + DELTA)/2 + epsilon + EPSILON + phi
2954 * delta is the round-trip delay
2955 * DELTA is the root delay
2956 * epsilon is the remote server precision + local precision
2957 * + (15 usec each second)
2958 * EPSILON is the root dispersion
2959 * phi is the peer jitter statistic
2961 * NB: Think hard about why we are using these values, and what
2962 * the alternatives are, and the various pros/cons.
2964 * DLM thinks these are probably the best choices from any of the
2965 * other worse choices.
2967 dtemp = (peer->delay + peer->rootdelay) / 2
2968 + LOGTOD(peer->precision)
2969 + LOGTOD(sys_precision)
2970 + clock_phi * (current_time - peer->update)
2974 * Careful squeak here. The value returned must be greater than
2975 * the minimum root dispersion in order to avoid clockhop with
2976 * highly precise reference clocks. Note that the root distance
2977 * cannot exceed the sys_maxdist, as this is the cutoff by the
2978 * selection algorithm.
2980 if (dtemp < sys_mindisp)
2981 dtemp = sys_mindisp;
2987 * peer_xmit - send packet for persistent association.
2991 struct peer *peer /* peer structure pointer */
2994 struct pkt xpkt; /* transmit packet */
2995 size_t sendlen, authlen;
2996 keyid_t xkeyid = 0; /* transmit key ID */
2997 l_fp xmt_tx, xmt_ty;
2999 if (!peer->dstadr) /* drop peers without interface */
3002 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3004 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3005 xpkt.ppoll = peer->hpoll;
3006 xpkt.precision = sys_precision;
3007 xpkt.refid = sys_refid;
3008 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3009 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3010 HTONL_FP(&sys_reftime, &xpkt.reftime);
3011 HTONL_FP(&peer->rec, &xpkt.org);
3012 HTONL_FP(&peer->dst, &xpkt.rec);
3015 * If the received packet contains a MAC, the transmitted packet
3016 * is authenticated and contains a MAC. If not, the transmitted
3017 * packet is not authenticated.
3019 * It is most important when autokey is in use that the local
3020 * interface IP address be known before the first packet is
3021 * sent. Otherwise, it is not possible to compute a correct MAC
3022 * the recipient will accept. Thus, the I/O semantics have to do
3023 * a little more work. In particular, the wildcard interface
3024 * might not be usable.
3026 sendlen = LEN_PKT_NOMAC;
3028 if (!(peer->flags & FLAG_SKEY) && peer->keyid == 0) {
3029 #else /* !AUTOKEY follows */
3030 if (peer->keyid == 0) {
3031 #endif /* !AUTOKEY */
3034 * Transmit a-priori timestamps
3036 get_systime(&xmt_tx);
3037 if (peer->flip == 0) { /* basic mode */
3038 peer->aorg = xmt_tx;
3039 HTONL_FP(&xmt_tx, &xpkt.xmt);
3040 } else { /* interleaved modes */
3041 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3042 HTONL_FP(&xmt_tx, &xpkt.xmt);
3044 HTONL_FP(&peer->borg,
3047 HTONL_FP(&peer->aorg,
3049 } else { /* symmetric */
3051 HTONL_FP(&peer->borg,
3054 HTONL_FP(&peer->aorg,
3058 peer->t21_bytes = sendlen;
3059 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3062 peer->throttle += (1 << peer->minpoll) - 2;
3065 * Capture a-posteriori timestamps
3067 get_systime(&xmt_ty);
3068 if (peer->flip != 0) { /* interleaved modes */
3070 peer->aorg = xmt_ty;
3072 peer->borg = xmt_ty;
3073 peer->flip = -peer->flip;
3075 L_SUB(&xmt_ty, &xmt_tx);
3076 LFPTOD(&xmt_ty, peer->xleave);
3079 printf("transmit: at %ld %s->%s mode %d len %zu\n",
3080 current_time, peer->dstadr ?
3081 stoa(&peer->dstadr->sin) : "-",
3082 stoa(&peer->srcadr), peer->hmode, sendlen);
3088 * Authentication is enabled, so the transmitted packet must be
3089 * authenticated. If autokey is enabled, fuss with the various
3090 * modes; otherwise, symmetric key cryptography is used.
3093 if (peer->flags & FLAG_SKEY) {
3094 struct exten *exten; /* extension field */
3097 * The Public Key Dance (PKD): Cryptographic credentials
3098 * are contained in extension fields, each including a
3099 * 4-octet length/code word followed by a 4-octet
3100 * association ID and optional additional data. Optional
3101 * data includes a 4-octet data length field followed by
3102 * the data itself. Request messages are sent from a
3103 * configured association; response messages can be sent
3104 * from a configured association or can take the fast
3105 * path without ever matching an association. Response
3106 * messages have the same code as the request, but have
3107 * a response bit and possibly an error bit set. In this
3108 * implementation, a message may contain no more than
3109 * one command and one or more responses.
3111 * Cryptographic session keys include both a public and
3112 * a private componet. Request and response messages
3113 * using extension fields are always sent with the
3114 * private component set to zero. Packets without
3115 * extension fields indlude the private component when
3116 * the session key is generated.
3121 * Allocate and initialize a keylist if not
3122 * already done. Then, use the list in inverse
3123 * order, discarding keys once used. Keep the
3124 * latest key around until the next one, so
3125 * clients can use client/server packets to
3126 * compute propagation delay.
3128 * Note that once a key is used from the list,
3129 * it is retained in the key cache until the
3130 * next key is used. This is to allow a client
3131 * to retrieve the encrypted session key
3132 * identifier to verify authenticity.
3134 * If for some reason a key is no longer in the
3135 * key cache, a birthday has happened or the key
3136 * has expired, so the pseudo-random sequence is
3137 * broken. In that case, purge the keylist and
3140 if (peer->keynumber == 0)
3141 make_keylist(peer, peer->dstadr);
3144 xkeyid = peer->keylist[peer->keynumber];
3145 if (authistrusted(xkeyid))
3150 peer->keyid = xkeyid;
3152 switch (peer->hmode) {
3155 * In broadcast server mode the autokey values are
3156 * required by the broadcast clients. Push them when a
3157 * new keylist is generated; otherwise, push the
3158 * association message so the client can request them at
3161 case MODE_BROADCAST:
3162 if (peer->flags & FLAG_ASSOC)
3163 exten = crypto_args(peer, CRYPTO_AUTO |
3164 CRYPTO_RESP, peer->associd, NULL);
3166 exten = crypto_args(peer, CRYPTO_ASSOC |
3167 CRYPTO_RESP, peer->associd, NULL);
3171 * In symmetric modes the parameter, certificate,
3172 * identity, cookie and autokey exchanges are
3173 * required. The leapsecond exchange is optional. But, a
3174 * peer will not believe the other peer until the other
3175 * peer has synchronized, so the certificate exchange
3176 * might loop until then. If a peer finds a broken
3177 * autokey sequence, it uses the autokey exchange to
3178 * retrieve the autokey values. In any case, if a new
3179 * keylist is generated, the autokey values are pushed.
3185 * Parameter, certificate and identity.
3188 exten = crypto_args(peer, CRYPTO_ASSOC,
3189 peer->associd, hostval.ptr);
3190 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3191 exten = crypto_args(peer, CRYPTO_CERT,
3192 peer->associd, peer->issuer);
3193 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3194 exten = crypto_args(peer,
3195 crypto_ident(peer), peer->associd,
3199 * Cookie and autokey. We request the cookie
3200 * only when the this peer and the other peer
3201 * are synchronized. But, this peer needs the
3202 * autokey values when the cookie is zero. Any
3203 * time we regenerate the key list, we offer the
3204 * autokey values without being asked. If for
3205 * some reason either peer finds a broken
3206 * autokey sequence, the autokey exchange is
3207 * used to retrieve the autokey values.
3209 else if (sys_leap != LEAP_NOTINSYNC &&
3210 peer->leap != LEAP_NOTINSYNC &&
3211 !(peer->crypto & CRYPTO_FLAG_COOK))
3212 exten = crypto_args(peer, CRYPTO_COOK,
3213 peer->associd, NULL);
3214 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3215 exten = crypto_args(peer, CRYPTO_AUTO,
3216 peer->associd, NULL);
3217 else if (peer->flags & FLAG_ASSOC &&
3218 peer->crypto & CRYPTO_FLAG_SIGN)
3219 exten = crypto_args(peer, CRYPTO_AUTO |
3220 CRYPTO_RESP, peer->assoc, NULL);
3223 * Wait for clock sync, then sign the
3224 * certificate and retrieve the leapsecond
3227 else if (sys_leap == LEAP_NOTINSYNC)
3230 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3231 exten = crypto_args(peer, CRYPTO_SIGN,
3232 peer->associd, hostval.ptr);
3233 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3234 exten = crypto_args(peer, CRYPTO_LEAP,
3235 peer->associd, NULL);
3239 * In client mode the parameter, certificate, identity,
3240 * cookie and sign exchanges are required. The
3241 * leapsecond exchange is optional. If broadcast client
3242 * mode the same exchanges are required, except that the
3243 * autokey exchange is substitutes for the cookie
3244 * exchange, since the cookie is always zero. If the
3245 * broadcast client finds a broken autokey sequence, it
3246 * uses the autokey exchange to retrieve the autokey
3252 * Parameter, certificate and identity.
3255 exten = crypto_args(peer, CRYPTO_ASSOC,
3256 peer->associd, hostval.ptr);
3257 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3258 exten = crypto_args(peer, CRYPTO_CERT,
3259 peer->associd, peer->issuer);
3260 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3261 exten = crypto_args(peer,
3262 crypto_ident(peer), peer->associd,
3266 * Cookie and autokey. These are requests, but
3267 * we use the peer association ID with autokey
3268 * rather than our own.
3270 else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3271 exten = crypto_args(peer, CRYPTO_COOK,
3272 peer->associd, NULL);
3273 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3274 exten = crypto_args(peer, CRYPTO_AUTO,
3278 * Wait for clock sync, then sign the
3279 * certificate and retrieve the leapsecond
3282 else if (sys_leap == LEAP_NOTINSYNC)
3285 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3286 exten = crypto_args(peer, CRYPTO_SIGN,
3287 peer->associd, hostval.ptr);
3288 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3289 exten = crypto_args(peer, CRYPTO_LEAP,
3290 peer->associd, NULL);
3295 * Add a queued extension field if present. This is
3296 * always a request message, so the reply ID is already
3297 * in the message. If an error occurs, the error bit is
3298 * lit in the response.
3300 if (peer->cmmd != NULL) {
3303 temp32 = CRYPTO_RESP;
3304 peer->cmmd->opcode |= htonl(temp32);
3305 sendlen += crypto_xmit(peer, &xpkt, NULL,
3306 sendlen, peer->cmmd, 0);
3312 * Add an extension field created above. All but the
3313 * autokey response message are request messages.
3315 if (exten != NULL) {
3316 if (exten->opcode != 0)
3317 sendlen += crypto_xmit(peer, &xpkt,
3318 NULL, sendlen, exten, 0);
3323 * Calculate the next session key. Since extension
3324 * fields are present, the cookie value is zero.
3326 if (sendlen > (int)LEN_PKT_NOMAC) {
3327 session_key(&peer->dstadr->sin, &peer->srcadr,
3331 #endif /* AUTOKEY */
3334 * Transmit a-priori timestamps
3336 get_systime(&xmt_tx);
3337 if (peer->flip == 0) { /* basic mode */
3338 peer->aorg = xmt_tx;
3339 HTONL_FP(&xmt_tx, &xpkt.xmt);
3340 } else { /* interleaved modes */
3341 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3342 HTONL_FP(&xmt_tx, &xpkt.xmt);
3344 HTONL_FP(&peer->borg, &xpkt.org);
3346 HTONL_FP(&peer->aorg, &xpkt.org);
3347 } else { /* symmetric */
3349 HTONL_FP(&peer->borg, &xpkt.xmt);
3351 HTONL_FP(&peer->aorg, &xpkt.xmt);
3354 xkeyid = peer->keyid;
3355 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3357 report_event(PEVNT_AUTH, peer, "no key");
3358 peer->flash |= TEST5; /* auth error */
3364 if (xkeyid > NTP_MAXKEY)
3365 authtrust(xkeyid, 0);
3366 #endif /* AUTOKEY */
3367 if (sendlen > sizeof(xpkt)) {
3368 msyslog(LOG_ERR, "proto: buffer overflow %zu", sendlen);
3371 peer->t21_bytes = sendlen;
3372 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
3375 peer->throttle += (1 << peer->minpoll) - 2;
3378 * Capture a-posteriori timestamps
3380 get_systime(&xmt_ty);
3381 if (peer->flip != 0) { /* interleaved modes */
3383 peer->aorg = xmt_ty;
3385 peer->borg = xmt_ty;
3386 peer->flip = -peer->flip;
3388 L_SUB(&xmt_ty, &xmt_tx);
3389 LFPTOD(&xmt_ty, peer->xleave);
3393 printf("transmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
3394 current_time, latoa(peer->dstadr),
3395 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
3398 #else /* !AUTOKEY follows */
3401 printf("transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3402 current_time, peer->dstadr ?
3403 ntoa(&peer->dstadr->sin) : "-",
3404 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen);
3406 #endif /* !AUTOKEY */
3411 * fast_xmit - Send packet for nonpersistent association. Note that
3412 * neither the source or destination can be a broadcast address.
3416 struct recvbuf *rbufp, /* receive packet pointer */
3417 int xmode, /* receive mode */
3418 keyid_t xkeyid, /* transmit key ID */
3419 int flags /* restrict mask */
3422 struct pkt xpkt; /* transmit packet structure */
3423 struct pkt *rpkt; /* receive packet structure */
3424 l_fp xmt_tx, xmt_ty;
3431 * Initialize transmit packet header fields from the receive
3432 * buffer provided. We leave the fields intact as received, but
3433 * set the peer poll at the maximum of the receive peer poll and
3434 * the system minimum poll (ntp_minpoll). This is for KoD rate
3435 * control and not strictly specification compliant, but doesn't
3438 * If the gazinta was from a multicast address, the gazoutta
3439 * must go out another way.
3441 rpkt = &rbufp->recv_pkt;
3442 if (rbufp->dstadr->flags & INT_MCASTOPEN)
3443 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
3446 * If this is a kiss-o'-death (KoD) packet, show leap
3447 * unsynchronized, stratum zero, reference ID the four-character
3448 * kiss code and system root delay. Note we don't reveal the
3449 * local time, so these packets can't be used for
3452 if (flags & RES_KOD) {
3454 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
3455 PKT_VERSION(rpkt->li_vn_mode), xmode);
3456 xpkt.stratum = STRATUM_PKT_UNSPEC;
3457 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3458 xpkt.precision = rpkt->precision;
3459 memcpy(&xpkt.refid, "RATE", 4);
3460 xpkt.rootdelay = rpkt->rootdelay;
3461 xpkt.rootdisp = rpkt->rootdisp;
3462 xpkt.reftime = rpkt->reftime;
3463 xpkt.org = rpkt->xmt;
3464 xpkt.rec = rpkt->xmt;
3465 xpkt.xmt = rpkt->xmt;
3468 * This is a normal packet. Use the system variables.
3471 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
3472 PKT_VERSION(rpkt->li_vn_mode), xmode);
3473 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3474 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3475 xpkt.precision = sys_precision;
3476 xpkt.refid = sys_refid;
3477 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3478 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3479 HTONL_FP(&sys_reftime, &xpkt.reftime);
3480 xpkt.org = rpkt->xmt;
3481 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
3482 get_systime(&xmt_tx);
3483 HTONL_FP(&xmt_tx, &xpkt.xmt);
3486 #ifdef HAVE_NTP_SIGND
3487 if (flags & RES_MSSNTP) {
3488 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
3491 #endif /* HAVE_NTP_SIGND */
3494 * If the received packet contains a MAC, the transmitted packet
3495 * is authenticated and contains a MAC. If not, the transmitted
3496 * packet is not authenticated.
3498 sendlen = LEN_PKT_NOMAC;
3499 if (rbufp->recv_length == sendlen) {
3500 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
3505 "transmit: at %ld %s->%s mode %d len %d\n",
3506 current_time, stoa(&rbufp->dstadr->sin),
3507 stoa(&rbufp->recv_srcadr), xmode, sendlen);
3513 * The received packet contains a MAC, so the transmitted packet
3514 * must be authenticated. For symmetric key cryptography, use
3515 * the predefined and trusted symmetric keys to generate the
3516 * cryptosum. For autokey cryptography, use the server private
3517 * value to generate the cookie, which is unique for every
3518 * source-destination-key ID combination.
3521 if (xkeyid > NTP_MAXKEY) {
3525 * The only way to get here is a reply to a legitimate
3526 * client request message, so the mode must be
3527 * MODE_SERVER. If an extension field is present, there
3528 * can be only one and that must be a command. Do what
3529 * needs, but with private value of zero so the poor
3530 * jerk can decode it. If no extension field is present,
3531 * use the cookie to generate the session key.
3533 cookie = session_key(&rbufp->recv_srcadr,
3534 &rbufp->dstadr->sin, 0, sys_private, 0);
3535 if (rbufp->recv_length > sendlen + (int)MAX_MAC_LEN) {
3536 session_key(&rbufp->dstadr->sin,
3537 &rbufp->recv_srcadr, xkeyid, 0, 2);
3538 temp32 = CRYPTO_RESP;
3539 rpkt->exten[0] |= htonl(temp32);
3540 sendlen += crypto_xmit(NULL, &xpkt, rbufp,
3541 sendlen, (struct exten *)rpkt->exten,
3544 session_key(&rbufp->dstadr->sin,
3545 &rbufp->recv_srcadr, xkeyid, cookie, 2);
3548 #endif /* AUTOKEY */
3549 get_systime(&xmt_tx);
3550 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3552 if (xkeyid > NTP_MAXKEY)
3553 authtrust(xkeyid, 0);
3554 #endif /* AUTOKEY */
3555 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
3556 get_systime(&xmt_ty);
3557 L_SUB(&xmt_ty, &xmt_tx);
3558 sys_authdelay = xmt_ty;
3562 "transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3563 current_time, ntoa(&rbufp->dstadr->sin),
3564 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen);
3570 * pool_xmit - resolve hostname or send unicast solicitation for pool.
3574 struct peer *pool /* pool solicitor association */
3578 struct pkt xpkt; /* transmit packet structure */
3579 struct addrinfo hints;
3581 struct interface * lcladr;
3582 sockaddr_u * rmtadr;
3587 if (NULL == pool->ai) {
3588 if (pool->addrs != NULL) {
3589 /* free() is used with copy_addrinfo_list() */
3594 hints.ai_family = AF(&pool->srcadr);
3595 hints.ai_socktype = SOCK_DGRAM;
3596 hints.ai_protocol = IPPROTO_UDP;
3597 /* ignore getaddrinfo_sometime() errors, we will retry */
3598 rc = getaddrinfo_sometime(
3603 &pool_name_resolved,
3604 (void *)(intptr_t)pool->associd);
3606 DPRINTF(1, ("pool DNS lookup %s started\n",
3610 "unable to start pool DNS %s %m",
3616 /* copy_addrinfo_list ai_addr points to a sockaddr_u */
3617 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
3618 pool->ai = pool->ai->ai_next;
3619 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
3620 } while (p != NULL && pool->ai != NULL);
3622 return; /* out of addresses, re-query DNS next poll */
3623 restrict_mask = restrictions(rmtadr);
3624 if (RES_FLAGS & restrict_mask)
3625 restrict_source(rmtadr, 0,
3626 current_time + POOL_SOLICIT_WINDOW + 1);
3627 lcladr = findinterface(rmtadr);
3628 memset(&xpkt, 0, sizeof(xpkt));
3629 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
3631 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3632 xpkt.ppoll = pool->hpoll;
3633 xpkt.precision = sys_precision;
3634 xpkt.refid = sys_refid;
3635 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3636 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3637 HTONL_FP(&sys_reftime, &xpkt.reftime);
3638 get_systime(&xmt_tx);
3639 pool->aorg = xmt_tx;
3640 HTONL_FP(&xmt_tx, &xpkt.xmt);
3641 sendpkt(rmtadr, lcladr, sys_ttl[pool->ttl], &xpkt,
3644 pool->throttle += (1 << pool->minpoll) - 2;
3647 printf("transmit: at %ld %s->%s pool\n",
3648 current_time, latoa(lcladr), stoa(rmtadr));
3650 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
3657 * group_test - test if this is the same group
3659 * host assoc return action
3660 * none none 0 mobilize *
3661 * none group 0 mobilize *
3662 * group none 0 mobilize *
3663 * group group 1 mobilize
3664 * group different 1 ignore
3665 * * ignore if notrust
3675 if (strcmp(grp, sys_groupname) == 0)
3681 if (strcmp(grp, ident) == 0)
3686 #endif /* AUTOKEY */
3695 const char * service,
3696 const struct addrinfo * hints,
3697 const struct addrinfo * res
3700 struct peer * pool; /* pool solicitor association */
3705 "error resolving pool %s: %s (%d)",
3706 name, gai_strerror(rescode), rescode);
3710 assoc = (associd_t)(intptr_t)context;
3711 pool = findpeerbyassoc(assoc);
3714 "Could not find assoc %u for pool DNS %s",
3718 DPRINTF(1, ("pool DNS %s completed\n", name));
3719 pool->addrs = copy_addrinfo_list(res);
3720 pool->ai = pool->addrs;
3729 * key_expire - purge the key list
3733 struct peer *peer /* peer structure pointer */
3738 if (peer->keylist != NULL) {
3739 for (i = 0; i <= peer->keynumber; i++)
3740 authtrust(peer->keylist[i], 0);
3741 free(peer->keylist);
3742 peer->keylist = NULL;
3744 value_free(&peer->sndval);
3745 peer->keynumber = 0;
3746 peer->flags &= ~FLAG_ASSOC;
3749 printf("key_expire: at %lu associd %d\n", current_time,
3753 #endif /* AUTOKEY */
3757 * local_refid(peer) - check peer refid to avoid selecting peers
3758 * currently synced to this ntpd.
3767 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
3768 unicast_ep = p->dstadr;
3770 unicast_ep = findinterface(&p->srcadr);
3772 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
3780 * Determine if the peer is unfit for synchronization
3782 * A peer is unfit for synchronization if
3783 * > TEST10 bad leap or stratum below floor or at or above ceiling
3784 * > TEST11 root distance exceeded for remote peer
3785 * > TEST12 a direct or indirect synchronization loop would form
3786 * > TEST13 unreachable or noselect
3788 int /* FALSE if fit, TRUE if unfit */
3790 struct peer *peer /* peer structure pointer */
3796 * A stratum error occurs if (1) the server has never been
3797 * synchronized, (2) the server stratum is below the floor or
3798 * greater than or equal to the ceiling.
3800 if (peer->leap == LEAP_NOTINSYNC || peer->stratum < sys_floor ||
3801 peer->stratum >= sys_ceiling)
3802 rval |= TEST10; /* bad synch or stratum */
3805 * A distance error for a remote peer occurs if the root
3806 * distance is greater than or equal to the distance threshold
3807 * plus the increment due to one host poll interval.
3809 if (!(peer->flags & FLAG_REFCLOCK) && root_distance(peer) >=
3810 sys_maxdist + clock_phi * ULOGTOD(peer->hpoll))
3811 rval |= TEST11; /* distance exceeded */
3814 * A loop error occurs if the remote peer is synchronized to the
3815 * local peer or if the remote peer is synchronized to the same
3816 * server as the local peer but only if the remote peer is
3817 * neither a reference clock nor an orphan.
3819 if (peer->stratum > 1 && local_refid(peer))
3820 rval |= TEST12; /* synchronization loop */
3823 * An unreachable error occurs if the server is unreachable or
3824 * the noselect bit is set.
3826 if (!peer->reach || (peer->flags & FLAG_NOSELECT))
3827 rval |= TEST13; /* unreachable */
3829 peer->flash &= ~PEER_TEST_MASK;
3830 peer->flash |= rval;
3836 * Find the precision of this particular machine
3838 #define MINSTEP 20e-9 /* minimum clock increment (s) */
3839 #define MAXSTEP 1 /* maximum clock increment (s) */
3840 #define MINCHANGES 12 /* minimum number of step samples */
3841 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */
3844 * This routine measures the system precision defined as the minimum of
3845 * a sequence of differences between successive readings of the system
3846 * clock. However, if a difference is less than MINSTEP, the clock has
3847 * been read more than once during a clock tick and the difference is
3848 * ignored. We set MINSTEP greater than zero in case something happens
3849 * like a cache miss, and to tolerate underlying system clocks which
3850 * ensure each reading is strictly greater than prior readings while
3851 * using an underlying stepping (not interpolated) clock.
3853 * sys_tick and sys_precision represent the time to read the clock for
3854 * systems with high-precision clocks, and the tick interval or step
3855 * size for lower-precision stepping clocks.
3857 * This routine also measures the time to read the clock on stepping
3858 * system clocks by counting the number of readings between changes of
3859 * the underlying clock. With either type of clock, the minimum time
3860 * to read the clock is saved as sys_fuzz, and used to ensure the
3861 * get_systime() readings always increase and are fuzzed below sys_fuzz.
3864 measure_precision(void)
3867 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
3868 * is effectively disabled. trunc_os_clock is FALSE to disable
3869 * get_ostime() simulation of a low-precision system clock.
3872 trunc_os_clock = FALSE;
3873 measured_tick = measure_tick_fuzz();
3874 set_sys_tick_precision(measured_tick);
3875 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
3876 sys_tick * 1e6, sys_precision);
3877 if (sys_fuzz < sys_tick) {
3878 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
3885 * measure_tick_fuzz()
3887 * measures the minimum time to read the clock (stored in sys_fuzz)
3888 * and returns the tick, the larger of the minimum increment observed
3889 * between successive clock readings and the time to read the clock.
3892 measure_tick_fuzz(void)
3894 l_fp minstep; /* MINSTEP as l_fp */
3895 l_fp val; /* current seconds fraction */
3896 l_fp last; /* last seconds fraction */
3897 l_fp ldiff; /* val - last */
3898 double tick; /* computed tick value */
3903 int i; /* log2 precision */
3909 DTOLFP(MINSTEP, &minstep);
3911 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
3914 L_SUB(&ldiff, &last);
3916 if (L_ISGT(&ldiff, &minstep)) {
3917 max_repeats = max(repeats, max_repeats);
3920 LFPTOD(&ldiff, diff);
3921 tick = min(diff, tick);
3926 if (changes < MINCHANGES) {
3927 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
3931 if (0 == max_repeats) {
3934 set_sys_fuzz(tick / max_repeats);
3942 set_sys_tick_precision(
3950 "unsupported tick %.3f > 1s ignored", tick);
3953 if (tick < measured_tick) {
3955 "proto: tick %.3f less than measured tick %.3f, ignored",
3956 tick, measured_tick);
3958 } else if (tick > measured_tick) {
3959 trunc_os_clock = TRUE;
3961 "proto: truncating system clock to multiples of %.9f",
3967 * Find the nearest power of two.
3969 for (i = 0; tick <= 1; i--)
3971 if (tick - 1 > 1 - tick / 2)
3974 sys_precision = (s_char)i;
3979 * init_proto - initialize the protocol module's data
3988 * Fill in the sys_* stuff. Default is don't listen to
3989 * broadcasting, require authentication.
3991 sys_leap = LEAP_NOTINSYNC;
3992 sys_stratum = STRATUM_UNSPEC;
3993 memcpy(&sys_refid, "INIT", 4);
3997 L_CLR(&sys_reftime);
3999 measure_precision();
4000 get_systime(&dummy);
4002 sys_manycastserver = 0;
4005 sys_authenticate = 1;
4006 sys_stattime = current_time;
4007 orphwait = current_time + sys_orphwait;
4009 for (i = 0; i < MAX_TTL; i++) {
4010 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4019 * proto_config - configure the protocol module
4030 * Figure out what he wants to change, then do it
4032 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4033 item, value, dvalue));
4038 * enable and disable commands - arguments are Boolean.
4040 case PROTO_AUTHENTICATE: /* authentication (auth) */
4041 sys_authenticate = value;
4044 case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4045 sys_bclient = (int)value;
4046 if (sys_bclient == 0)
4053 case PROTO_CAL: /* refclock calibrate (calibrate) */
4056 #endif /* REFCLOCK */
4058 case PROTO_KERNEL: /* kernel discipline (kernel) */
4062 case PROTO_MONITOR: /* monitoring (monitor) */
4069 case PROTO_NTP: /* NTP discipline (ntp) */
4073 case PROTO_MODE7: /* mode7 management (ntpdc) */
4077 case PROTO_PPS: /* PPS discipline (pps) */
4078 hardpps_enable = value;
4081 case PROTO_FILEGEN: /* statistics (stats) */
4082 stats_control = value;
4086 * tos command - arguments are double, sometimes cast to int
4088 case PROTO_BEACON: /* manycast beacon (beacon) */
4089 sys_beacon = (int)dvalue;
4092 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
4093 sys_bdelay = dvalue;
4096 case PROTO_CEILING: /* stratum ceiling (ceiling) */
4097 sys_ceiling = (int)dvalue;
4100 case PROTO_COHORT: /* cohort switch (cohort) */
4101 sys_cohort = (int)dvalue;
4104 case PROTO_FLOOR: /* stratum floor (floor) */
4105 sys_floor = (int)dvalue;
4108 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
4109 sys_maxclock = (int)dvalue;
4112 case PROTO_MAXDIST: /* select threshold (maxdist) */
4113 sys_maxdist = dvalue;
4116 case PROTO_CALLDELAY: /* modem call delay (mdelay) */
4117 break; /* NOT USED */
4119 case PROTO_MINCLOCK: /* minimum candidates (minclock) */
4120 sys_minclock = (int)dvalue;
4123 case PROTO_MINDISP: /* minimum distance (mindist) */
4124 sys_mindisp = dvalue;
4127 case PROTO_MINSANE: /* minimum survivors (minsane) */
4128 sys_minsane = (int)dvalue;
4131 case PROTO_ORPHAN: /* orphan stratum (orphan) */
4132 sys_orphan = (int)dvalue;
4135 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */
4136 orphwait -= sys_orphwait;
4137 sys_orphwait = (int)dvalue;
4138 orphwait += sys_orphwait;
4142 * Miscellaneous commands
4144 case PROTO_MULTICAST_ADD: /* add group address */
4146 io_multicast_add(svalue);
4150 case PROTO_MULTICAST_DEL: /* delete group address */
4152 io_multicast_del(svalue);
4157 "proto: unsupported option %d", item);
4163 * proto_clr_stats - clear protocol stat counters
4166 proto_clr_stats(void)
4168 sys_stattime = current_time;
4177 sys_limitrejected = 0;