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"
17 #include "refidsmear.h"
18 #include "lib_strbuf.h"
28 /* [Bug 3031] define automatic broadcastdelay cutoff preset */
29 #ifndef BDELAY_DEFAULT
30 # define BDELAY_DEFAULT (-0.050)
34 * This macro defines the authentication state. If x is 1 authentication
35 * is required; othewise it is optional.
37 #define AUTH(x, y) ((x) ? (y) == AUTH_OK \
38 : (y) == AUTH_OK || (y) == AUTH_NONE)
40 #define AUTH_NONE 0 /* authentication not required */
41 #define AUTH_OK 1 /* authentication OK */
42 #define AUTH_ERROR 2 /* authentication error */
43 #define AUTH_CRYPTO 3 /* crypto_NAK */
46 * Set up Kiss Code values
50 NOKISS, /* No Kiss Code */
51 RATEKISS, /* Rate limit Kiss Code */
52 DENYKISS, /* Deny Kiss */
53 RSTRKISS, /* Restricted Kiss */
54 XKISS, /* Experimental Kiss */
55 UNKNOWNKISS /* Unknown Kiss Code */
58 enum nak_error_codes {
59 NONAK, /* No NAK seen */
60 INVALIDNAK, /* NAK cannot be used */
61 VALIDNAK /* NAK is valid */
65 * traffic shaping parameters
67 #define NTP_IBURST 6 /* packets in iburst */
68 #define RESP_DELAY 1 /* refclock burst delay (s) */
71 * pool soliciting restriction duration (s)
73 #define POOL_SOLICIT_WINDOW 8
76 * peer_select groups statistics for a peer used by clock_select() and
79 typedef struct peer_select_tag {
81 double synch; /* sync distance */
82 double error; /* jitter */
83 double seljit; /* selection jitter */
87 * System variables are declared here. Unless specified otherwise, all
88 * times are in seconds.
90 u_char sys_leap; /* system leap indicator, use set_sys_leap() to change this */
91 u_char xmt_leap; /* leap indicator sent in client requests, set up by set_sys_leap() */
92 u_char sys_stratum; /* system stratum */
93 s_char sys_precision; /* local clock precision (log2 s) */
94 double sys_rootdelay; /* roundtrip delay to primary source */
95 double sys_rootdisp; /* dispersion to primary source */
96 u_int32 sys_refid; /* reference id (network byte order) */
97 l_fp sys_reftime; /* last update time */
98 struct peer *sys_peer; /* current peer */
101 struct leap_smear_info leap_smear;
103 int leap_sec_in_progress;
106 * Rate controls. Leaky buckets are used to throttle the packet
107 * transmission rates in order to protect busy servers such as at NIST
108 * and USNO. There is a counter for each association and another for KoD
109 * packets. The association counter decrements each second, but not
110 * below zero. Each time a packet is sent the counter is incremented by
111 * a configurable value representing the average interval between
112 * packets. A packet is delayed as long as the counter is greater than
113 * zero. Note this does not affect the time value computations.
116 * Nonspecified system state variables
118 int sys_bclient; /* broadcast client enable */
119 double sys_bdelay; /* broadcast client default delay */
120 int sys_authenticate; /* requre authentication for config */
121 l_fp sys_authdelay; /* authentication delay */
122 double sys_offset; /* current local clock offset */
123 double sys_mindisp = MINDISPERSE; /* minimum distance (s) */
124 double sys_maxdist = MAXDISTANCE; /* selection threshold */
125 double sys_jitter; /* system jitter */
126 u_long sys_epoch; /* last clock update time */
127 static double sys_clockhop; /* clockhop threshold */
128 static int leap_vote_ins; /* leap consensus for insert */
129 static int leap_vote_del; /* leap consensus for delete */
130 keyid_t sys_private; /* private value for session seed */
131 int sys_manycastserver; /* respond to manycast client pkts */
132 int ntp_mode7; /* respond to ntpdc (mode7) */
133 int peer_ntpdate; /* active peers in ntpdate mode */
134 int sys_survivors; /* truest of the truechimers */
135 char *sys_ident = NULL; /* identity scheme */
138 * TOS and multicast mapping stuff
140 int sys_floor = 0; /* cluster stratum floor */
141 int sys_ceiling = STRATUM_UNSPEC - 1; /* cluster stratum ceiling */
142 int sys_minsane = 1; /* minimum candidates */
143 int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
144 int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
145 int sys_cohort = 0; /* cohort switch */
146 int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
147 int sys_orphwait = NTP_ORPHWAIT; /* orphan wait */
148 int sys_beacon = BEACON; /* manycast beacon interval */
149 int sys_ttlmax; /* max ttl mapping vector index */
150 u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
153 * Statistics counters - first the good, then the bad
155 u_long sys_stattime; /* elapsed time */
156 u_long sys_received; /* packets received */
157 u_long sys_processed; /* packets for this host */
158 u_long sys_newversion; /* current version */
159 u_long sys_oldversion; /* old version */
160 u_long sys_restricted; /* access denied */
161 u_long sys_badlength; /* bad length or format */
162 u_long sys_badauth; /* bad authentication */
163 u_long sys_declined; /* declined */
164 u_long sys_limitrejected; /* rate exceeded */
165 u_long sys_kodsent; /* KoD sent */
168 * Mechanism knobs: how soon do we unpeer()?
170 * The default way is "on-receipt". If this was a packet from a
171 * well-behaved source, on-receipt will offer the fastest recovery.
172 * If this was from a DoS attack, the default way makes it easier
173 * for a bad-guy to DoS us. So look and see what bites you harder
174 * and choose according to your environment.
176 int unpeer_crypto_early = 1; /* bad crypto (TEST9) */
177 int unpeer_crypto_nak_early = 1; /* crypto_NAK (TEST5) */
178 int unpeer_digest_early = 1; /* bad digest (TEST5) */
180 int dynamic_interleave = DYNAMIC_INTERLEAVE; /* Bug 2978 mitigation */
182 int kiss_code_check(u_char hisleap, u_char hisstratum, u_char hismode, u_int32 refid);
183 enum nak_error_codes valid_NAK(struct peer *peer, struct recvbuf *rbufp, u_char hismode);
184 static double root_distance (struct peer *);
185 static void clock_combine (peer_select *, int, int);
186 static void peer_xmit (struct peer *);
187 static void fast_xmit (struct recvbuf *, int, keyid_t, int);
188 static void pool_xmit (struct peer *);
189 static void clock_update (struct peer *);
190 static void measure_precision(void);
191 static double measure_tick_fuzz(void);
192 static int local_refid (struct peer *);
193 static int peer_unfit (struct peer *);
195 static int group_test (char *, char *);
198 void pool_name_resolved (int, int, void *, const char *,
199 const char *, const struct addrinfo *,
200 const struct addrinfo *);
203 const char * amtoa (int am);
211 sys_leap = new_sys_leap;
215 * Under certain conditions we send faked leap bits to clients, so
216 * eventually change xmt_leap below, but never change LEAP_NOTINSYNC.
218 if (xmt_leap != LEAP_NOTINSYNC) {
219 if (leap_sec_in_progress) {
220 /* always send "not sync" */
221 xmt_leap = LEAP_NOTINSYNC;
226 * If leap smear is enabled in general we must
227 * never send a leap second warning to clients,
228 * so make sure we only send "in sync".
230 if (leap_smear.enabled)
231 xmt_leap = LEAP_NOWARNING;
233 #endif /* LEAP_SMEAR */
250 if ( hismode == MODE_SERVER
251 && hisleap == LEAP_NOTINSYNC
252 && hisstratum == STRATUM_UNSPEC) {
253 if(memcmp(&refid,"RATE", 4) == 0) {
255 } else if(memcmp(&refid,"DENY", 4) == 0) {
257 } else if(memcmp(&refid,"RSTR", 4) == 0) {
259 } else if(memcmp(&refid,"X", 1) == 0) {
262 return (UNKNOWNKISS);
271 * Check that NAK is valid
276 struct recvbuf *rbufp,
280 int base_packet_length = MIN_V4_PKT_LEN;
286 * Check to see if there is something beyond the basic packet
288 if (rbufp->recv_length == base_packet_length) {
292 remainder_size = rbufp->recv_length - base_packet_length;
294 * Is this a potential NAK?
296 if (remainder_size != 4) {
301 * Only server responses can contain NAK's
304 if (hismode != MODE_SERVER &&
305 hismode != MODE_ACTIVE &&
306 hismode != MODE_PASSIVE
312 * Make sure that the extra field in the packet is all zeros
314 rpkt = &rbufp->recv_pkt;
315 keyid = ntohl(((u_int32 *)rpkt)[base_packet_length / 4]);
321 * Only valid if peer uses a key
323 if (peer->keyid > 0 || peer->flags & FLAG_SKEY) {
333 * transmit - transmit procedure called by poll timeout
337 struct peer *peer /* peer structure pointer */
343 * The polling state machine. There are two kinds of machines,
344 * those that never expect a reply (broadcast and manycast
345 * server modes) and those that do (all other modes). The dance
351 * In broadcast mode the poll interval is never changed from
354 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
355 peer->outdate = current_time;
356 if (sys_leap != LEAP_NOTINSYNC)
358 poll_update(peer, hpoll);
363 * In manycast mode we start with unity ttl. The ttl is
364 * increased by one for each poll until either sys_maxclock
365 * servers have been found or the maximum ttl is reached. When
366 * sys_maxclock servers are found we stop polling until one or
367 * more servers have timed out or until less than sys_minclock
368 * associations turn up. In this case additional better servers
369 * are dragged in and preempt the existing ones. Once every
370 * sys_beacon seconds we are to transmit unconditionally, but
371 * this code is not quite right -- peer->unreach counts polls
372 * and is being compared with sys_beacon, so the beacons happen
373 * every sys_beacon polls.
375 if (peer->cast_flags & MDF_ACAST) {
376 peer->outdate = current_time;
377 if (peer->unreach > sys_beacon) {
381 } else if ( sys_survivors < sys_minclock
382 || peer_associations < sys_maxclock) {
383 if (peer->ttl < (u_int32)sys_ttlmax)
388 poll_update(peer, hpoll);
393 * Pool associations transmit unicast solicitations when there
394 * are less than a hard limit of 2 * sys_maxclock associations,
395 * and either less than sys_minclock survivors or less than
396 * sys_maxclock associations. The hard limit prevents unbounded
397 * growth in associations if the system clock or network quality
398 * result in survivor count dipping below sys_minclock often.
399 * This was observed testing with pool, where sys_maxclock == 12
400 * resulted in 60 associations without the hard limit. A
401 * similar hard limit on manycastclient ephemeral associations
402 * may be appropriate.
404 if (peer->cast_flags & MDF_POOL) {
405 peer->outdate = current_time;
406 if ( (peer_associations <= 2 * sys_maxclock)
407 && ( peer_associations < sys_maxclock
408 || sys_survivors < sys_minclock))
410 poll_update(peer, hpoll);
415 * In unicast modes the dance is much more intricate. It is
416 * designed to back off whenever possible to minimize network
419 if (peer->burst == 0) {
423 * Update the reachability status. If not heard for
424 * three consecutive polls, stuff infinity in the clock
427 oreach = peer->reach;
428 peer->outdate = current_time;
434 * Here the peer is unreachable. If it was
435 * previously reachable raise a trap. Send a
438 clock_filter(peer, 0., 0., MAXDISPERSE);
441 report_event(PEVNT_UNREACH, peer, NULL);
443 if ( (peer->flags & FLAG_IBURST)
445 peer->retry = NTP_RETRY;
449 * Here the peer is reachable. Send a burst if
450 * enabled and the peer is fit. Reset unreach
451 * for persistent and ephemeral associations.
452 * Unreach is also reset for survivors in
456 if (!(peer->flags & FLAG_PREEMPT))
458 if ( (peer->flags & FLAG_BURST)
460 && !peer_unfit(peer))
461 peer->retry = NTP_RETRY;
465 * Watch for timeout. If ephemeral, toss the rascal;
466 * otherwise, bump the poll interval. Note the
467 * poll_update() routine will clamp it to maxpoll.
468 * If preemptible and we have more peers than maxclock,
469 * and this peer has the minimum score of preemptibles,
472 if (peer->unreach >= NTP_UNREACH) {
474 /* ephemeral: no FLAG_CONFIG nor FLAG_PREEMPT */
475 if (!(peer->flags & (FLAG_CONFIG | FLAG_PREEMPT))) {
476 report_event(PEVNT_RESTART, peer, "timeout");
477 peer_clear(peer, "TIME");
481 if ( (peer->flags & FLAG_PREEMPT)
482 && (peer_associations > sys_maxclock)
483 && score_all(peer)) {
484 report_event(PEVNT_RESTART, peer, "timeout");
485 peer_clear(peer, "TIME");
492 if (peer->burst == 0) {
495 * If ntpdate mode and the clock has not been
496 * set and all peers have completed the burst,
497 * we declare a successful failure.
501 if (peer_ntpdate == 0) {
503 "ntpd: no servers found");
506 "ntpd: no servers found\n");
516 * Do not transmit if in broadcast client mode.
518 if (peer->hmode != MODE_BCLIENT)
520 poll_update(peer, hpoll);
534 case AM_ERR: return "AM_ERR";
535 case AM_NOMATCH: return "AM_NOMATCH";
536 case AM_PROCPKT: return "AM_PROCPKT";
537 case AM_BCST: return "AM_BCST";
538 case AM_FXMIT: return "AM_FXMIT";
539 case AM_MANYCAST: return "AM_MANYCAST";
540 case AM_NEWPASS: return "AM_NEWPASS";
541 case AM_NEWBCL: return "AM_NEWBCL";
542 case AM_POSSBCL: return "AM_POSSBCL";
545 snprintf(bp, LIB_BUFLENGTH, "AM_#%d", am);
552 * receive - receive procedure called for each packet received
556 struct recvbuf *rbufp
559 register struct peer *peer; /* peer structure pointer */
560 register struct pkt *pkt; /* receive packet pointer */
561 u_char hisversion; /* packet version */
562 u_char hisleap; /* packet leap indicator */
563 u_char hismode; /* packet mode */
564 u_char hisstratum; /* packet stratum */
565 u_short restrict_mask; /* restrict bits */
566 const char *hm_str; /* hismode string */
567 const char *am_str; /* association match string */
568 int kissCode = NOKISS; /* Kiss Code */
569 int has_mac; /* length of MAC field */
570 int authlen; /* offset of MAC field */
571 int is_authentic = 0; /* cryptosum ok */
572 int crypto_nak_test; /* result of crypto-NAK check */
573 int retcode = AM_NOMATCH; /* match code */
574 keyid_t skeyid = 0; /* key IDs */
575 u_int32 opcode = 0; /* extension field opcode */
576 sockaddr_u *dstadr_sin; /* active runway */
577 struct peer *peer2; /* aux peer structure pointer */
578 endpt *match_ep; /* newpeer() local address */
579 l_fp p_org; /* origin timestamp */
580 l_fp p_rec; /* receive timestamp */
581 l_fp p_xmt; /* transmit timestamp */
583 char hostname[NTP_MAXSTRLEN + 1];
584 char *groupname = NULL;
585 struct autokey *ap; /* autokey structure pointer */
586 int rval; /* cookie snatcher */
587 keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
589 #ifdef HAVE_NTP_SIGND
590 static unsigned char zero_key[16];
591 #endif /* HAVE_NTP_SIGND */
594 * Monitor the packet and get restrictions. Note that the packet
595 * length for control and private mode packets must be checked
596 * by the service routines. Some restrictions have to be handled
597 * later in order to generate a kiss-o'-death packet.
600 * Bogus port check is before anything, since it probably
601 * reveals a clogging attack.
604 if (0 == SRCPORT(&rbufp->recv_srcadr)) {
606 return; /* bogus port */
608 restrict_mask = restrictions(&rbufp->recv_srcadr);
609 pkt = &rbufp->recv_pkt;
610 DPRINTF(2, ("receive: at %ld %s<-%s flags %x restrict %03x org %#010x.%08x xmt %#010x.%08x\n",
611 current_time, stoa(&rbufp->dstadr->sin),
612 stoa(&rbufp->recv_srcadr), rbufp->dstadr->flags,
613 restrict_mask, ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
614 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
615 hisversion = PKT_VERSION(pkt->li_vn_mode);
616 hisleap = PKT_LEAP(pkt->li_vn_mode);
617 hismode = (int)PKT_MODE(pkt->li_vn_mode);
618 hisstratum = PKT_TO_STRATUM(pkt->stratum);
619 if (restrict_mask & RES_IGNORE) {
621 return; /* ignore everything */
623 if (hismode == MODE_PRIVATE) {
624 if (!ntp_mode7 || (restrict_mask & RES_NOQUERY)) {
626 return; /* no query private */
628 process_private(rbufp, ((restrict_mask &
629 RES_NOMODIFY) == 0));
632 if (hismode == MODE_CONTROL) {
633 if (restrict_mask & RES_NOQUERY) {
635 return; /* no query control */
637 process_control(rbufp, restrict_mask);
640 if (restrict_mask & RES_DONTSERVE) {
642 return; /* no time serve */
646 * This is for testing. If restricted drop ten percent of
649 if (restrict_mask & RES_FLAKE) {
650 if ((double)ntp_random() / 0x7fffffff < .1) {
652 return; /* no flakeway */
657 * Version check must be after the query packets, since they
658 * intentionally use an early version.
660 if (hisversion == NTP_VERSION) {
661 sys_newversion++; /* new version */
662 } else if ( !(restrict_mask & RES_VERSION)
663 && hisversion >= NTP_OLDVERSION) {
664 sys_oldversion++; /* previous version */
667 return; /* old version */
671 * Figure out his mode and validate the packet. This has some
672 * legacy raunch that probably should be removed. In very early
673 * NTP versions mode 0 was equivalent to what later versions
674 * would interpret as client mode.
676 if (hismode == MODE_UNSPEC) {
677 if (hisversion == NTP_OLDVERSION) {
678 hismode = MODE_CLIENT;
681 return; /* invalid mode */
686 * Parse the extension field if present. We figure out whether
687 * an extension field is present by measuring the MAC size. If
688 * the number of words following the packet header is 0, no MAC
689 * is present and the packet is not authenticated. If 1, the
690 * packet is a crypto-NAK; if 3, the packet is authenticated
691 * with DES; if 5, the packet is authenticated with MD5; if 6,
692 * the packet is authenticated with SHA. If 2 or * 4, the packet
693 * is a runt and discarded forthwith. If greater than 6, an
694 * extension field is present, so we subtract the length of the
695 * field and go around again.
698 authlen = LEN_PKT_NOMAC;
699 has_mac = rbufp->recv_length - authlen;
700 while (has_mac > 0) {
707 if (has_mac % 4 != 0 || has_mac < (int)MIN_MAC_LEN) {
709 return; /* bad length */
711 if (has_mac <= (int)MAX_MAC_LEN) {
712 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
716 opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
717 len = opcode & 0xffff;
720 || (int)len + authlen > rbufp->recv_length) {
722 return; /* bad length */
726 * Extract calling group name for later. If
727 * sys_groupname is non-NULL, there must be
728 * a group name provided to elicit a response.
730 if ( (opcode & 0x3fff0000) == CRYPTO_ASSOC
731 && sys_groupname != NULL) {
732 ep = (struct exten *)&((u_int32 *)pkt)[authlen / 4];
733 hostlen = ntohl(ep->vallen);
734 if ( hostlen >= sizeof(hostname)
736 offsetof(struct exten, pkt)) {
738 return; /* bad length */
740 memcpy(hostname, &ep->pkt, hostlen);
741 hostname[hostlen] = '\0';
742 groupname = strchr(hostname, '@');
743 if (groupname == NULL) {
756 * If has_mac is < 0 we had a malformed packet.
760 return; /* bad length */
764 * If authentication required, a MAC must be present.
766 if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
768 return; /* access denied */
772 * Update the MRU list and finger the cloggers. It can be a
773 * little expensive, so turn it off for production use.
774 * RES_LIMITED and RES_KOD will be cleared in the returned
775 * restrict_mask unless one or both actions are warranted.
777 restrict_mask = ntp_monitor(rbufp, restrict_mask);
778 if (restrict_mask & RES_LIMITED) {
780 if ( !(restrict_mask & RES_KOD)
781 || MODE_BROADCAST == hismode
782 || MODE_SERVER == hismode) {
783 if (MODE_SERVER == hismode)
784 DPRINTF(1, ("Possibly self-induced rate limiting of MODE_SERVER from %s\n",
785 stoa(&rbufp->recv_srcadr)));
786 return; /* rate exceeded */
788 if (hismode == MODE_CLIENT)
789 fast_xmit(rbufp, MODE_SERVER, skeyid,
792 fast_xmit(rbufp, MODE_ACTIVE, skeyid,
794 return; /* rate exceeded */
796 restrict_mask &= ~RES_KOD;
799 * We have tossed out as many buggy packets as possible early in
800 * the game to reduce the exposure to a clogging attack. Now we
801 * have to burn some cycles to find the association and
802 * authenticate the packet if required. Note that we burn only
803 * digest cycles, again to reduce exposure. There may be no
804 * matching association and that's okay.
806 * More on the autokey mambo. Normally the local interface is
807 * found when the association was mobilized with respect to a
808 * designated remote address. We assume packets arriving from
809 * the remote address arrive via this interface and the local
810 * address used to construct the autokey is the unicast address
811 * of the interface. However, if the sender is a broadcaster,
812 * the interface broadcast address is used instead.
813 * Notwithstanding this technobabble, if the sender is a
814 * multicaster, the broadcast address is null, so we use the
815 * unicast address anyway. Don't ask.
817 peer = findpeer(rbufp, hismode, &retcode);
818 dstadr_sin = &rbufp->dstadr->sin;
819 NTOHL_FP(&pkt->org, &p_org);
820 NTOHL_FP(&pkt->rec, &p_rec);
821 NTOHL_FP(&pkt->xmt, &p_xmt);
822 hm_str = modetoa(hismode);
823 am_str = amtoa(retcode);
826 * Authentication is conditioned by three switches:
828 * NOPEER (RES_NOPEER) do not mobilize an association unless
830 * NOTRUST (RES_DONTTRUST) do not allow access unless
831 * authenticated (implies NOPEER)
832 * enable (sys_authenticate) master NOPEER switch, by default
835 * The NOPEER and NOTRUST can be specified on a per-client basis
836 * using the restrict command. The enable switch if on implies
837 * NOPEER for all clients. There are four outcomes:
839 * NONE The packet has no MAC.
840 * OK the packet has a MAC and authentication succeeds
841 * ERROR the packet has a MAC and authentication fails
842 * CRYPTO crypto-NAK. The MAC has four octets only.
844 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
845 * is zero, acceptable outcomes of y are NONE and OK. If x is
846 * one, the only acceptable outcome of y is OK.
848 crypto_nak_test = valid_NAK(peer, rbufp, hismode);
851 * Drop any invalid crypto-NAKs
853 if (crypto_nak_test == INVALIDNAK) {
854 report_event(PEVNT_AUTH, peer, "Invalid_NAK");
858 msyslog(LOG_ERR, "Invalid-NAK error at %ld %s<-%s",
859 current_time, stoa(dstadr_sin), stoa(&rbufp->recv_srcadr));
864 restrict_mask &= ~RES_MSSNTP;
865 is_authentic = AUTH_NONE; /* not required */
866 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s len %d org %#010x.%08x xmt %#010x.%08x NOMAC\n",
867 current_time, stoa(dstadr_sin),
868 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
870 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
871 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
872 } else if (crypto_nak_test == VALIDNAK) {
873 restrict_mask &= ~RES_MSSNTP;
874 is_authentic = AUTH_CRYPTO; /* crypto-NAK */
875 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x MAC4\n",
876 current_time, stoa(dstadr_sin),
877 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
878 skeyid, authlen + has_mac, is_authentic,
879 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
880 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
882 #ifdef HAVE_NTP_SIGND
884 * If the signature is 20 bytes long, the last 16 of
885 * which are zero, then this is a Microsoft client
886 * wanting AD-style authentication of the server's
889 * This is described in Microsoft's WSPP docs, in MS-SNTP:
890 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
892 } else if ( has_mac == MAX_MD5_LEN
893 && (restrict_mask & RES_MSSNTP)
894 && (retcode == AM_FXMIT || retcode == AM_NEWPASS)
895 && (memcmp(zero_key, (char *)pkt + authlen + 4,
896 MAX_MD5_LEN - 4) == 0)) {
897 is_authentic = AUTH_NONE;
898 #endif /* HAVE_NTP_SIGND */
901 restrict_mask &= ~RES_MSSNTP;
904 * For autokey modes, generate the session key
905 * and install in the key cache. Use the socket
906 * broadcast or unicast address as appropriate.
908 if (crypto_flags && skeyid > NTP_MAXKEY) {
911 * More on the autokey dance (AKD). A cookie is
912 * constructed from public and private values.
913 * For broadcast packets, the cookie is public
914 * (zero). For packets that match no
915 * association, the cookie is hashed from the
916 * addresses and private value. For server
917 * packets, the cookie was previously obtained
918 * from the server. For symmetric modes, the
919 * cookie was previously constructed using an
920 * agreement protocol; however, should PKI be
921 * unavailable, we construct a fake agreement as
922 * the EXOR of the peer and host cookies.
924 * hismode ephemeral persistent
925 * =======================================
928 * client sys cookie 0%
929 * server 0% sys cookie
935 if (has_mac < (int)MAX_MD5_LEN) {
939 if (hismode == MODE_BROADCAST) {
942 * For broadcaster, use the interface
943 * broadcast address when available;
944 * otherwise, use the unicast address
945 * found when the association was
946 * mobilized. However, if this is from
947 * the wildcard interface, game over.
951 ANY_INTERFACE_CHOOSE(&rbufp->recv_srcadr)) {
953 return; /* no wildcard */
956 if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
958 &rbufp->dstadr->bcast;
959 } else if (peer == NULL) {
960 pkeyid = session_key(
961 &rbufp->recv_srcadr, dstadr_sin, 0,
964 pkeyid = peer->pcookie;
968 * The session key includes both the public
969 * values and cookie. In case of an extension
970 * field, the cookie used for authentication
971 * purposes is zero. Note the hash is saved for
972 * use later in the autokey mambo.
974 if (authlen > (int)LEN_PKT_NOMAC && pkeyid != 0) {
975 session_key(&rbufp->recv_srcadr,
976 dstadr_sin, skeyid, 0, 2);
977 tkeyid = session_key(
978 &rbufp->recv_srcadr, dstadr_sin,
981 tkeyid = session_key(
982 &rbufp->recv_srcadr, dstadr_sin,
990 * Compute the cryptosum. Note a clogging attack may
991 * succeed in bloating the key cache. If an autokey,
992 * purge it immediately, since we won't be needing it
993 * again. If the packet is authentic, it can mobilize an
994 * association. Note that there is no key zero.
996 if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
998 is_authentic = AUTH_ERROR;
1000 is_authentic = AUTH_OK;
1002 if (crypto_flags && skeyid > NTP_MAXKEY)
1003 authtrust(skeyid, 0);
1004 #endif /* AUTOKEY */
1005 DPRINTF(2, ("receive: at %ld %s<-%s mode %d/%s:%s keyid %08x len %d auth %d org %#010x.%08x xmt %#010x.%08x\n",
1006 current_time, stoa(dstadr_sin),
1007 stoa(&rbufp->recv_srcadr), hismode, hm_str, am_str,
1008 skeyid, authlen + has_mac, is_authentic,
1009 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1010 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf)));
1014 * The association matching rules are implemented by a set of
1015 * routines and an association table. A packet matching an
1016 * association is processed by the peer process for that
1017 * association. If there are no errors, an ephemeral association
1018 * is mobilized: a broadcast packet mobilizes a broadcast client
1019 * aassociation; a manycast server packet mobilizes a manycast
1020 * client association; a symmetric active packet mobilizes a
1021 * symmetric passive association.
1026 * This is a client mode packet not matching any association. If
1027 * an ordinary client, simply toss a server mode packet back
1028 * over the fence. If a manycast client, we have to work a
1034 * If authentication OK, send a server reply; otherwise,
1035 * send a crypto-NAK.
1037 if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
1038 if (AUTH(restrict_mask & RES_DONTTRUST,
1040 fast_xmit(rbufp, MODE_SERVER, skeyid,
1042 } else if (is_authentic == AUTH_ERROR) {
1043 fast_xmit(rbufp, MODE_SERVER, 0,
1049 return; /* hooray */
1053 * This must be manycast. Do not respond if not
1054 * configured as a manycast server.
1056 if (!sys_manycastserver) {
1058 return; /* not enabled */
1063 * Do not respond if not the same group.
1065 if (group_test(groupname, NULL)) {
1069 #endif /* AUTOKEY */
1072 * Do not respond if we are not synchronized or our
1073 * stratum is greater than the manycaster or the
1074 * manycaster has already synchronized to us.
1076 if ( sys_leap == LEAP_NOTINSYNC
1077 || sys_stratum >= hisstratum
1078 || (!sys_cohort && sys_stratum == hisstratum + 1)
1079 || rbufp->dstadr->addr_refid == pkt->refid) {
1081 return; /* no help */
1085 * Respond only if authentication succeeds. Don't do a
1086 * crypto-NAK, as that would not be useful.
1088 if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
1089 fast_xmit(rbufp, MODE_SERVER, skeyid,
1091 return; /* hooray */
1094 * This is a server mode packet returned in response to a client
1095 * mode packet sent to a multicast group address (for
1096 * manycastclient) or to a unicast address (for pool). The
1097 * origin timestamp is a good nonce to reliably associate the
1098 * reply with what was sent. If there is no match, that's
1099 * curious and could be an intruder attempting to clog, so we
1102 * If the packet is authentic and the manycastclient or pool
1103 * association is found, we mobilize a client association and
1104 * copy pertinent variables from the manycastclient or pool
1105 * association to the new client association. If not, just
1106 * ignore the packet.
1108 * There is an implosion hazard at the manycast client, since
1109 * the manycast servers send the server packet immediately. If
1110 * the guy is already here, don't fire up a duplicate.
1116 * Do not respond if not the same group.
1118 if (group_test(groupname, NULL)) {
1122 #endif /* AUTOKEY */
1123 if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
1125 return; /* not enabled */
1127 if (!AUTH( (!(peer2->cast_flags & MDF_POOL)
1128 && sys_authenticate)
1129 || (restrict_mask & (RES_NOPEER |
1130 RES_DONTTRUST)), is_authentic)) {
1132 return; /* access denied */
1136 * Do not respond if unsynchronized or stratum is below
1137 * the floor or at or above the ceiling.
1139 if ( hisleap == LEAP_NOTINSYNC
1140 || hisstratum < sys_floor
1141 || hisstratum >= sys_ceiling) {
1143 return; /* no help */
1145 peer = newpeer(&rbufp->recv_srcadr, NULL, rbufp->dstadr,
1146 MODE_CLIENT, hisversion, peer2->minpoll,
1147 peer2->maxpoll, FLAG_PREEMPT |
1148 (FLAG_IBURST & peer2->flags), MDF_UCAST |
1149 MDF_UCLNT, 0, skeyid, sys_ident);
1152 return; /* ignore duplicate */
1156 * After each ephemeral pool association is spun,
1157 * accelerate the next poll for the pool solicitor so
1158 * the pool will fill promptly.
1160 if (peer2->cast_flags & MDF_POOL)
1161 peer2->nextdate = current_time + 1;
1164 * Further processing of the solicitation response would
1165 * simply detect its origin timestamp as bogus for the
1166 * brand-new association (it matches the prototype
1167 * association) and tinker with peer->nextdate delaying
1170 return; /* solicitation response handled */
1173 * This is the first packet received from a broadcast server. If
1174 * the packet is authentic and we are enabled as broadcast
1175 * client, mobilize a broadcast client association. We don't
1176 * kiss any frogs here.
1182 * Do not respond if not the same group.
1184 if (group_test(groupname, sys_ident)) {
1188 #endif /* AUTOKEY */
1189 if (sys_bclient == 0) {
1191 return; /* not enabled */
1193 if (!AUTH(sys_authenticate | (restrict_mask &
1194 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1196 return; /* access denied */
1200 * Do not respond if unsynchronized or stratum is below
1201 * the floor or at or above the ceiling.
1203 if ( hisleap == LEAP_NOTINSYNC
1204 || hisstratum < sys_floor
1205 || hisstratum >= sys_ceiling) {
1207 return; /* no help */
1212 * Do not respond if Autokey and the opcode is not a
1213 * CRYPTO_ASSOC response with association ID.
1215 if ( crypto_flags && skeyid > NTP_MAXKEY
1216 && (opcode & 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
1218 return; /* protocol error */
1220 #endif /* AUTOKEY */
1223 * Broadcasts received via a multicast address may
1224 * arrive after a unicast volley has begun
1225 * with the same remote address. newpeer() will not
1226 * find duplicate associations on other local endpoints
1227 * if a non-NULL endpoint is supplied. multicastclient
1228 * ephemeral associations are unique across all local
1231 if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
1232 match_ep = rbufp->dstadr;
1237 * Determine whether to execute the initial volley.
1239 if (sys_bdelay > 0.0) {
1242 * If a two-way exchange is not possible,
1243 * neither is Autokey.
1245 if (crypto_flags && skeyid > NTP_MAXKEY) {
1247 return; /* no autokey */
1249 #endif /* AUTOKEY */
1252 * Do not execute the volley. Start out in
1253 * broadcast client mode.
1255 peer = newpeer(&rbufp->recv_srcadr, NULL,
1256 match_ep, MODE_BCLIENT, hisversion,
1257 pkt->ppoll, pkt->ppoll, FLAG_PREEMPT,
1258 MDF_BCLNT, 0, skeyid, sys_ident);
1261 return; /* ignore duplicate */
1264 peer->delay = sys_bdelay;
1271 * Execute the initial volley in order to calibrate the
1272 * propagation delay and run the Autokey protocol.
1274 * Note that the minpoll is taken from the broadcast
1275 * packet, normally 6 (64 s) and that the poll interval
1276 * is fixed at this value.
1278 peer = newpeer(&rbufp->recv_srcadr, NULL, match_ep,
1279 MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
1280 FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
1281 0, skeyid, sys_ident);
1284 return; /* ignore duplicate */
1288 if (skeyid > NTP_MAXKEY)
1289 crypto_recv(peer, rbufp);
1290 #endif /* AUTOKEY */
1292 return; /* hooray */
1295 * This is the first packet received from a symmetric active
1296 * peer. If the packet is authentic and the first he sent,
1297 * mobilize a passive association. If not, kiss the frog.
1303 * Do not respond if not the same group.
1305 if (group_test(groupname, sys_ident)) {
1309 #endif /* AUTOKEY */
1310 if (!AUTH(sys_authenticate | (restrict_mask &
1311 (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
1314 * If authenticated but cannot mobilize an
1315 * association, send a symmetric passive
1316 * response without mobilizing an association.
1317 * This is for drat broken Windows clients. See
1318 * Microsoft KB 875424 for preferred workaround.
1320 if (AUTH(restrict_mask & RES_DONTTRUST,
1322 fast_xmit(rbufp, MODE_PASSIVE, skeyid,
1324 return; /* hooray */
1326 if (is_authentic == AUTH_ERROR) {
1327 fast_xmit(rbufp, MODE_ACTIVE, 0,
1333 * If we got here, the packet isn't part of an
1334 * existing association, it isn't correctly
1335 * authenticated, and it didn't meet either of
1336 * the previous two special cases so we should
1337 * just drop it on the floor. For example,
1338 * crypto-NAKs (is_authentic == AUTH_CRYPTO)
1339 * will make it this far. This is just
1340 * debug-printed and not logged to avoid log
1343 DPRINTF(2, ("receive: at %ld refusing to mobilize passive association"
1344 " with unknown peer %s mode %d/%s:%s keyid %08x len %d auth %d\n",
1345 current_time, stoa(&rbufp->recv_srcadr),
1346 hismode, hm_str, am_str, skeyid,
1347 (authlen + has_mac), is_authentic));
1353 * Do not respond if synchronized and if stratum is
1354 * below the floor or at or above the ceiling. Note,
1355 * this allows an unsynchronized peer to synchronize to
1356 * us. It would be very strange if he did and then was
1357 * nipped, but that could only happen if we were
1358 * operating at the top end of the range. It also means
1359 * we will spin an ephemeral association in response to
1360 * MODE_ACTIVE KoDs, which will time out eventually.
1362 if ( hisleap != LEAP_NOTINSYNC
1363 && (hisstratum < sys_floor || hisstratum >= sys_ceiling)) {
1365 return; /* no help */
1369 * The message is correctly authenticated and allowed.
1370 * Mobilize a symmetric passive association.
1372 if ((peer = newpeer(&rbufp->recv_srcadr, NULL,
1373 rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
1374 NTP_MAXDPOLL, 0, MDF_UCAST, 0, skeyid,
1375 sys_ident)) == NULL) {
1377 return; /* ignore duplicate */
1383 * Process regular packet. Nothing special.
1389 * Do not respond if not the same group.
1391 if (group_test(groupname, peer->ident)) {
1395 #endif /* AUTOKEY */
1397 if (MODE_BROADCAST == hismode) {
1402 DPRINTF(2, ("receive: PROCPKT/BROADCAST: prev pkt %ld seconds ago, ppoll: %d, %d secs\n",
1403 (current_time - peer->timelastrec),
1404 peer->ppoll, (1 << peer->ppoll)
1406 /* Things we can check:
1408 * Did the poll interval change?
1409 * Is the poll interval in the packet in-range?
1410 * Did this packet arrive too soon?
1411 * Is the timestamp in this packet monotonic
1412 * with respect to the previous packet?
1415 /* This is noteworthy, not error-worthy */
1416 if (pkt->ppoll != peer->ppoll) {
1417 msyslog(LOG_INFO, "receive: broadcast poll from %s changed from %ud to %ud",
1418 stoa(&rbufp->recv_srcadr),
1419 peer->ppoll, pkt->ppoll);
1422 /* This is error-worthy */
1423 if (pkt->ppoll < peer->minpoll ||
1424 pkt->ppoll > peer->maxpoll ) {
1425 msyslog(LOG_INFO, "receive: broadcast poll of %ud from %s is out-of-range (%d to %d)!",
1426 pkt->ppoll, stoa(&rbufp->recv_srcadr),
1427 peer->minpoll, peer->maxpoll);
1431 /* too early? worth an error, too! */
1432 deadband = (1u << pkt->ppoll);
1433 if (FLAG_BC_VOL & peer->flags)
1434 deadband -= 3; /* allow greater fuzz after volley */
1435 if ((current_time - peer->timelastrec) < deadband) {
1436 msyslog(LOG_INFO, "receive: broadcast packet from %s arrived after %lu, not %lu seconds!",
1437 stoa(&rbufp->recv_srcadr),
1438 (current_time - peer->timelastrec),
1443 /* Alert if time from the server is non-monotonic */
1445 L_SUB(&tdiff, &peer->bxmt);
1446 if (tdiff.l_i < 0) {
1447 msyslog(LOG_INFO, "receive: broadcast packet from %s contains non-monotonic timestamp: %#010x.%08x -> %#010x.%08x",
1448 stoa(&rbufp->recv_srcadr),
1449 peer->bxmt.l_ui, peer->bxmt.l_uf,
1450 p_xmt.l_ui, p_xmt.l_uf
1458 peer->timelastrec = current_time;
1467 * A passive packet matches a passive association. This is
1468 * usually the result of reconfiguring a client on the fly. As
1469 * this association might be legitimate and this packet an
1470 * attempt to deny service, just ignore it.
1477 * For everything else there is the bit bucket.
1486 * If the association is configured for Autokey, the packet must
1487 * have a public key ID; if not, the packet must have a
1490 if ( is_authentic != AUTH_CRYPTO
1491 && ( ((peer->flags & FLAG_SKEY) && skeyid <= NTP_MAXKEY)
1492 || (!(peer->flags & FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
1496 #endif /* AUTOKEY */
1499 peer->flash &= ~PKT_TEST_MASK;
1500 if (peer->flags & FLAG_XBOGUS) {
1501 peer->flags &= ~FLAG_XBOGUS;
1502 peer->flash |= TEST3;
1506 * Next comes a rigorous schedule of timestamp checking. If the
1507 * transmit timestamp is zero, the server has not initialized in
1508 * interleaved modes or is horribly broken.
1510 * A KoD packet we pay attention to cannot have a 0 transmit
1513 if (L_ISZERO(&p_xmt)) {
1514 peer->flash |= TEST3; /* unsynch */
1515 if (0 == hisstratum) { /* KoD packet */
1516 peer->bogusorg++; /* for TEST2 or TEST3 */
1518 "receive: Unexpected zero transmit timestamp in KoD from %s",
1519 ntoa(&peer->srcadr));
1524 * If the transmit timestamp duplicates our previous one, the
1525 * packet is a replay. This prevents the bad guys from replaying
1526 * the most recent packet, authenticated or not.
1528 } else if (L_ISEQU(&peer->xmt, &p_xmt)) {
1529 peer->flash |= TEST1; /* duplicate */
1534 * If this is a broadcast mode packet, skip further checking. If
1535 * an initial volley, bail out now and let the client do its
1536 * stuff. If the origin timestamp is nonzero, this is an
1537 * interleaved broadcast. so restart the protocol.
1539 } else if (hismode == MODE_BROADCAST) {
1540 if (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) {
1541 peer->flags |= FLAG_XB;
1543 peer->borg = rbufp->recv_time;
1544 report_event(PEVNT_XLEAVE, peer, NULL);
1549 * Basic KoD validation checking:
1551 * KoD packets are a mixed-blessing. Forged KoD packets
1552 * are DoS attacks. There are rare situations where we might
1553 * get a valid KoD response, though. Since KoD packets are
1554 * a special case that complicate the checks we do next, we
1555 * handle the basic KoD checks here.
1557 * Note that we expect the incoming KoD packet to have its
1558 * (nonzero) org, rec, and xmt timestamps set to the xmt timestamp
1559 * that we have previously sent out. Watch interleave mode.
1561 } else if (0 == hisstratum) {
1562 DEBUG_INSIST(!L_ISZERO(&p_xmt));
1563 if ( L_ISZERO(&p_org) /* We checked p_xmt above */
1564 || L_ISZERO(&p_rec)) {
1567 "receive: KoD packet from %s has a zero org or rec timestamp. Ignoring.",
1568 ntoa(&peer->srcadr));
1572 if ( !L_ISEQU(&p_xmt, &p_org)
1573 || !L_ISEQU(&p_xmt, &p_rec)) {
1576 "receive: KoD packet from %s has inconsistent xmt/org/rec timestamps. Ignoring.",
1577 ntoa(&peer->srcadr));
1581 /* Be conservative */
1582 if (peer->flip == 0 && !L_ISEQU(&p_org, &peer->aorg)) {
1585 "receive: flip 0 KoD origin timestamp %#010x.%08x from %s does not match %#010x.%08x - ignoring.",
1586 p_org.l_ui, p_org.l_uf,
1587 ntoa(&peer->srcadr),
1588 peer->aorg.l_ui, peer->aorg.l_uf);
1590 } else if (peer->flip == 1 && !L_ISEQU(&p_org, &peer->borg)) {
1593 "receive: flip 1 KoD origin timestamp %#010x.%08x from %s does not match interleave %#010x.%08x - ignoring.",
1594 p_org.l_ui, p_org.l_uf,
1595 ntoa(&peer->srcadr),
1596 peer->borg.l_ui, peer->borg.l_uf);
1601 * Basic mode checks:
1603 * If there is no origin timestamp, it's either an initial packet
1604 * or we've already received a response to our query. Of course,
1605 * should 'aorg' be all-zero because this really was the original
1606 * transmit timestamp, we'll ignore this reply. There is a window
1607 * of one nanosecond once every 136 years' time where this is
1608 * possible. We currently ignore this situation.
1610 * Otherwise, check for bogus packet in basic mode.
1611 * If it is bogus, switch to interleaved mode and resynchronize,
1612 * but only after confirming the packet is not bogus in
1613 * symmetric interleaved mode.
1615 * This could also mean somebody is forging packets claiming to
1616 * be from us, attempting to cause our server to KoD us.
1618 } else if (peer->flip == 0) {
1619 INSIST(0 != hisstratum);
1621 } else if (L_ISZERO(&p_org)) {
1623 "receive: Got 0 origin timestamp from %s@%s xmt %#010x.%08x",
1624 hm_str, ntoa(&peer->srcadr),
1625 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1627 } else if (!L_ISEQU(&p_org, &peer->aorg)) {
1628 /* are there cases here where we should bail? */
1629 /* Should we set TEST2 if we decide to try xleave? */
1631 peer->flash |= TEST2; /* bogus */
1633 "receive: Unexpected origin timestamp %#010x.%08x does not match aorg %#010x.%08x from %s@%s xmt %#010x.%08x",
1634 ntohl(pkt->org.l_ui), ntohl(pkt->org.l_uf),
1635 peer->aorg.l_ui, peer->aorg.l_uf,
1636 hm_str, ntoa(&peer->srcadr),
1637 ntohl(pkt->xmt.l_ui), ntohl(pkt->xmt.l_uf));
1638 if ( !L_ISZERO(&peer->dst)
1639 && L_ISEQU(&p_org, &peer->dst)) {
1640 /* Might be the start of an interleave */
1641 if (dynamic_interleave) {
1643 report_event(PEVNT_XLEAVE, peer, NULL);
1646 "receive: Dynamic interleave from %s@%s denied",
1647 hm_str, ntoa(&peer->srcadr));
1655 * Check for valid nonzero timestamp fields.
1657 } else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) ||
1658 L_ISZERO(&peer->dst)) {
1659 peer->flash |= TEST3; /* unsynch */
1662 * Check for bogus packet in interleaved symmetric mode. This
1663 * can happen if a packet is lost, duplicated or crossed. If
1664 * found, flip and resynchronize.
1666 } else if ( !L_ISZERO(&peer->dst)
1667 && !L_ISEQU(&p_org, &peer->dst)) {
1669 peer->flags |= FLAG_XBOGUS;
1670 peer->flash |= TEST2; /* bogus */
1671 return; /* Bogus packet, we are done */
1675 * If this is a crypto_NAK, the server cannot authenticate a
1676 * client packet. The server might have just changed keys. Clear
1677 * the association and restart the protocol.
1679 if (crypto_nak_test == VALIDNAK) {
1680 report_event(PEVNT_AUTH, peer, "crypto_NAK");
1681 peer->flash |= TEST5; /* bad auth */
1683 if (peer->flags & FLAG_PREEMPT) {
1684 if (unpeer_crypto_nak_early) {
1691 peer_clear(peer, "AUTH");
1692 #endif /* AUTOKEY */
1696 * If the digest fails or it's missing for authenticated
1697 * associations, the client cannot authenticate a server
1698 * reply to a client packet previously sent. The loopback check
1699 * is designed to avoid a bait-and-switch attack, which was
1700 * possible in past versions. If symmetric modes, return a
1701 * crypto-NAK. The peer should restart the protocol.
1703 } else if (!AUTH(peer->keyid || has_mac ||
1704 (restrict_mask & RES_DONTTRUST), is_authentic)) {
1705 report_event(PEVNT_AUTH, peer, "digest");
1706 peer->flash |= TEST5; /* bad auth */
1709 && (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE))
1710 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
1711 if (peer->flags & FLAG_PREEMPT) {
1712 if (unpeer_digest_early) {
1719 peer_clear(peer, "AUTH");
1720 #endif /* AUTOKEY */
1725 * Update the state variables.
1727 if (peer->flip == 0) {
1728 if (hismode != MODE_BROADCAST)
1730 peer->dst = rbufp->recv_time;
1735 * Set the peer ppoll to the maximum of the packet ppoll and the
1736 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1737 * this maximum and advance the headway to give the sender some
1738 * headroom. Very intricate.
1742 * Check for any kiss codes. Note this is only used when a server
1743 * responds to a packet request
1746 kissCode = kiss_code_check(hisleap, hisstratum, hismode, pkt->refid);
1749 * Check to see if this is a RATE Kiss Code
1750 * Currently this kiss code will accept whatever poll
1751 * rate that the server sends
1753 peer->ppoll = max(peer->minpoll, pkt->ppoll);
1754 if (kissCode == RATEKISS) {
1755 peer->selbroken++; /* Increment the KoD count */
1756 report_event(PEVNT_RATE, peer, NULL);
1757 if (pkt->ppoll > peer->minpoll)
1758 peer->minpoll = peer->ppoll;
1759 peer->burst = peer->retry = 0;
1760 peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
1761 poll_update(peer, pkt->ppoll);
1762 return; /* kiss-o'-death */
1764 if (kissCode != NOKISS) {
1765 peer->selbroken++; /* Increment the KoD count */
1766 return; /* Drop any other kiss code packets */
1771 * - this is a *cast (uni-, broad-, or m-) server packet
1772 * - and it's symmetric-key authenticated
1773 * then see if the sender's IP is trusted for this keyid.
1774 * If it is, great - nothing special to do here.
1775 * Otherwise, we should report and bail.
1777 * Autokey-authenticated packets are accepted.
1781 case MODE_SERVER: /* server mode */
1782 case MODE_BROADCAST: /* broadcast mode */
1783 case MODE_ACTIVE: /* symmetric active mode */
1784 case MODE_PASSIVE: /* symmetric passive mode */
1785 if ( is_authentic == AUTH_OK
1787 && skeyid <= NTP_MAXKEY
1788 && !authistrustedip(skeyid, &peer->srcadr)) {
1789 report_event(PEVNT_AUTH, peer, "authIP");
1795 case MODE_CLIENT: /* client mode */
1796 #if 0 /* At this point, MODE_CONTROL is overloaded by MODE_BCLIENT */
1797 case MODE_CONTROL: /* control mode */
1799 case MODE_PRIVATE: /* private mode */
1800 case MODE_BCLIENT: /* broadcast client mode */
1803 case MODE_UNSPEC: /* unspecified (old version) */
1806 "receive: Unexpected mode (%d) in packet from %s",
1807 hismode, ntoa(&peer->srcadr));
1813 * That was hard and I am sweaty, but the packet is squeaky
1814 * clean. Get on with real work.
1816 peer->timereceived = current_time;
1817 peer->timelastrec = current_time;
1818 if (is_authentic == AUTH_OK)
1819 peer->flags |= FLAG_AUTHENTIC;
1821 peer->flags &= ~FLAG_AUTHENTIC;
1825 * More autokey dance. The rules of the cha-cha are as follows:
1827 * 1. If there is no key or the key is not auto, do nothing.
1829 * 2. If this packet is in response to the one just previously
1830 * sent or from a broadcast server, do the extension fields.
1831 * Otherwise, assume bogosity and bail out.
1833 * 3. If an extension field contains a verified signature, it is
1834 * self-authenticated and we sit the dance.
1836 * 4. If this is a server reply, check only to see that the
1837 * transmitted key ID matches the received key ID.
1839 * 5. Check to see that one or more hashes of the current key ID
1840 * matches the previous key ID or ultimate original key ID
1841 * obtained from the broadcaster or symmetric peer. If no
1842 * match, sit the dance and call for new autokey values.
1844 * In case of crypto error, fire the orchestra, stop dancing and
1845 * restart the protocol.
1847 if (peer->flags & FLAG_SKEY) {
1849 * Decrement remaining autokey hashes. This isn't
1850 * perfect if a packet is lost, but results in no harm.
1852 ap = (struct autokey *)peer->recval.ptr;
1857 peer->flash |= TEST8;
1858 rval = crypto_recv(peer, rbufp);
1859 if (rval == XEVNT_OK) {
1862 if (rval == XEVNT_ERR) {
1863 report_event(PEVNT_RESTART, peer,
1865 peer_clear(peer, "CRYP");
1866 peer->flash |= TEST9; /* bad crypt */
1867 if (peer->flags & FLAG_PREEMPT) {
1868 if (unpeer_crypto_early) {
1877 * If server mode, verify the receive key ID matches
1878 * the transmit key ID.
1880 if (hismode == MODE_SERVER) {
1881 if (skeyid == peer->keyid)
1882 peer->flash &= ~TEST8;
1885 * If an extension field is present, verify only that it
1886 * has been correctly signed. We don't need a sequence
1887 * check here, but the sequence continues.
1889 } else if (!(peer->flash & TEST8)) {
1890 peer->pkeyid = skeyid;
1893 * Now the fun part. Here, skeyid is the current ID in
1894 * the packet, pkeyid is the ID in the last packet and
1895 * tkeyid is the hash of skeyid. If the autokey values
1896 * have not been received, this is an automatic error.
1897 * If so, check that the tkeyid matches pkeyid. If not,
1898 * hash tkeyid and try again. If the number of hashes
1899 * exceeds the number remaining in the sequence, declare
1900 * a successful failure and refresh the autokey values.
1902 } else if (ap != NULL) {
1905 for (i = 0; ; i++) {
1906 if ( tkeyid == peer->pkeyid
1907 || tkeyid == ap->key) {
1908 peer->flash &= ~TEST8;
1909 peer->pkeyid = skeyid;
1918 tkeyid = session_key(
1919 &rbufp->recv_srcadr, dstadr_sin,
1922 if (peer->flash & TEST8)
1923 report_event(PEVNT_AUTH, peer, "keylist");
1925 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
1926 peer->flash |= TEST8; /* bad autokey */
1929 * The maximum lifetime of the protocol is about one
1930 * week before restarting the Autokey protocol to
1931 * refresh certificates and leapseconds values.
1933 if (current_time > peer->refresh) {
1934 report_event(PEVNT_RESTART, peer,
1936 peer_clear(peer, "TIME");
1940 #endif /* AUTOKEY */
1943 * The dance is complete and the flash bits have been lit. Toss
1944 * the packet over the fence for processing, which may light up
1947 process_packet(peer, pkt, rbufp->recv_length);
1950 * In interleaved mode update the state variables. Also adjust the
1951 * transmit phase to avoid crossover.
1953 if (peer->flip != 0) {
1955 peer->dst = rbufp->recv_time;
1956 if (peer->nextdate - current_time < (1U << min(peer->ppoll,
1966 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1967 * specification. Or almost, at least. If we're in here we have a
1968 * reasonable expectation that we will be having a long term
1969 * relationship with this host.
1973 register struct peer *peer,
1974 register struct pkt *pkt,
1979 double p_offset, p_del, p_disp;
1980 l_fp p_rec, p_xmt, p_org, p_reftime, ci;
1981 u_char pmode, pleap, pversion, pstratum;
1982 char statstr[NTP_MAXSTRLEN];
1985 double etemp, ftemp, td;
1990 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1992 p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
1993 NTOHL_FP(&pkt->reftime, &p_reftime);
1994 NTOHL_FP(&pkt->org, &p_org);
1995 NTOHL_FP(&pkt->rec, &p_rec);
1996 NTOHL_FP(&pkt->xmt, &p_xmt);
1997 pmode = PKT_MODE(pkt->li_vn_mode);
1998 pleap = PKT_LEAP(pkt->li_vn_mode);
1999 pversion = PKT_VERSION(pkt->li_vn_mode);
2000 pstratum = PKT_TO_STRATUM(pkt->stratum);
2003 * Capture the header values in the client/peer association..
2005 record_raw_stats(&peer->srcadr, peer->dstadr ?
2006 &peer->dstadr->sin : NULL,
2007 &p_org, &p_rec, &p_xmt, &peer->dst,
2008 pleap, pversion, pmode, pstratum, pkt->ppoll, pkt->precision,
2009 p_del, p_disp, pkt->refid);
2011 peer->stratum = min(pstratum, STRATUM_UNSPEC);
2012 peer->pmode = pmode;
2013 peer->precision = pkt->precision;
2014 peer->rootdelay = p_del;
2015 peer->rootdisp = p_disp;
2016 peer->refid = pkt->refid; /* network byte order */
2017 peer->reftime = p_reftime;
2020 * First, if either burst mode is armed, enable the burst.
2021 * Compute the headway for the next packet and delay if
2022 * necessary to avoid exceeding the threshold.
2024 if (peer->retry > 0) {
2027 peer->burst = min(1 << (peer->hpoll -
2028 peer->minpoll), NTP_SHIFT) - 1;
2030 peer->burst = NTP_IBURST - 1;
2031 if (peer->burst > 0)
2032 peer->nextdate = current_time;
2034 poll_update(peer, peer->hpoll);
2037 * Verify the server is synchronized; that is, the leap bits,
2038 * stratum and root distance are valid.
2040 if ( pleap == LEAP_NOTINSYNC /* test 6 */
2041 || pstratum < sys_floor || pstratum >= sys_ceiling)
2042 peer->flash |= TEST6; /* bad synch or strat */
2043 if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
2044 peer->flash |= TEST7; /* bad header */
2047 * If any tests fail at this point, the packet is discarded.
2048 * Note that some flashers may have already been set in the
2049 * receive() routine.
2051 if (peer->flash & PKT_TEST_MASK) {
2052 peer->seldisptoolarge++;
2053 DPRINTF(1, ("packet: flash header %04x\n",
2059 * If the peer was previously unreachable, raise a trap. In any
2060 * case, mark it reachable.
2063 report_event(PEVNT_REACH, peer, NULL);
2064 peer->timereachable = current_time;
2069 * For a client/server association, calculate the clock offset,
2070 * roundtrip delay and dispersion. The equations are reordered
2071 * from the spec for more efficient use of temporaries. For a
2072 * broadcast association, offset the last measurement by the
2073 * computed delay during the client/server volley. Note the
2074 * computation of dispersion includes the system precision plus
2075 * that due to the frequency error since the origin time.
2077 * It is very important to respect the hazards of overflow. The
2078 * only permitted operation on raw timestamps is subtraction,
2079 * where the result is a signed quantity spanning from 68 years
2080 * in the past to 68 years in the future. To avoid loss of
2081 * precision, these calculations are done using 64-bit integer
2082 * arithmetic. However, the offset and delay calculations are
2083 * sums and differences of these first-order differences, which
2084 * if done using 64-bit integer arithmetic, would be valid over
2085 * only half that span. Since the typical first-order
2086 * differences are usually very small, they are converted to 64-
2087 * bit doubles and all remaining calculations done in floating-
2088 * double arithmetic. This preserves the accuracy while
2089 * retaining the 68-year span.
2091 * There are three interleaving schemes, basic, interleaved
2092 * symmetric and interleaved broadcast. The timestamps are
2093 * idioscyncratically different. See the onwire briefing/white
2094 * paper at www.eecis.udel.edu/~mills for details.
2096 * Interleaved symmetric mode
2097 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
2100 if (peer->flip != 0) {
2101 ci = p_xmt; /* t3 - t4 */
2102 L_SUB(&ci, &peer->dst);
2104 ci = p_rec; /* t2 - t1 */
2106 L_SUB(&ci, &peer->borg);
2108 L_SUB(&ci, &peer->aorg);
2111 p_offset = (t21 + t34) / 2.;
2112 if (p_del < 0 || p_del > 1.) {
2113 snprintf(statstr, sizeof(statstr),
2114 "t21 %.6f t34 %.6f", t21, t34);
2115 report_event(PEVNT_XERR, peer, statstr);
2122 } else if (peer->pmode == MODE_BROADCAST) {
2125 * Interleaved broadcast mode. Use interleaved timestamps.
2126 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
2128 if (peer->flags & FLAG_XB) {
2129 ci = p_org; /* delay */
2130 L_SUB(&ci, &peer->aorg);
2132 ci = p_org; /* t2 - t1 */
2133 L_SUB(&ci, &peer->borg);
2136 peer->borg = peer->dst;
2137 if (t34 < 0 || t34 > 1.) {
2138 /* drop all if in the initial volley */
2139 if (FLAG_BC_VOL & peer->flags)
2140 goto bcc_init_volley_fail;
2141 snprintf(statstr, sizeof(statstr),
2142 "offset %.6f delay %.6f", t21, t34);
2143 report_event(PEVNT_XERR, peer, statstr);
2150 * Basic broadcast - use direct timestamps.
2151 * t3 = p_xmt, t4 = peer->dst
2154 ci = p_xmt; /* t3 - t4 */
2155 L_SUB(&ci, &peer->dst);
2161 * When calibration is complete and the clock is
2162 * synchronized, the bias is calculated as the difference
2163 * between the unicast timestamp and the broadcast
2164 * timestamp. This works for both basic and interleaved
2166 * [Bug 3031] Don't keep this peer when the delay
2167 * calculation gives reason to suspect clock steps.
2168 * This is assumed for delays > 50ms.
2170 if (FLAG_BC_VOL & peer->flags) {
2171 peer->flags &= ~FLAG_BC_VOL;
2172 peer->delay = fabs(peer->offset - p_offset) * 2;
2173 DPRINTF(2, ("broadcast volley: initial delay=%.6f\n",
2175 if (peer->delay > fabs(sys_bdelay)) {
2176 bcc_init_volley_fail:
2177 DPRINTF(2, ("%s", "broadcast volley: initial delay exceeds limit\n"));
2182 peer->nextdate = current_time + (1u << peer->ppoll) - 2u;
2183 p_del = peer->delay;
2184 p_offset += p_del / 2;
2188 * Basic mode, otherwise known as the old fashioned way.
2190 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
2193 ci = p_xmt; /* t3 - t4 */
2194 L_SUB(&ci, &peer->dst);
2196 ci = p_rec; /* t2 - t1 */
2199 p_del = fabs(t21 - t34);
2200 p_offset = (t21 + t34) / 2.;
2202 p_del = max(p_del, LOGTOD(sys_precision));
2203 p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
2208 * This code calculates the outbound and inbound data rates by
2209 * measuring the differences between timestamps at different
2210 * packet lengths. This is helpful in cases of large asymmetric
2211 * delays commonly experienced on deep space communication
2214 if (peer->t21_last > 0 && peer->t34_bytes > 0) {
2215 itemp = peer->t21_bytes - peer->t21_last;
2217 etemp = t21 - peer->t21;
2218 if (fabs(etemp) > 1e-6) {
2219 ftemp = itemp / etemp;
2224 itemp = len - peer->t34_bytes;
2226 etemp = -t34 - peer->t34;
2227 if (fabs(etemp) > 1e-6) {
2228 ftemp = itemp / etemp;
2236 * The following section compensates for different data rates on
2237 * the outbound (d21) and inbound (t34) directions. To do this,
2238 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
2239 * the roundtrip delay. Then it calculates the correction as a
2243 peer->t21_last = peer->t21_bytes;
2245 peer->t34_bytes = len;
2246 DPRINTF(2, ("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
2247 peer->t21_bytes, peer->t34, peer->t34_bytes));
2248 if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
2249 if (peer->pmode != MODE_BROADCAST)
2250 td = (peer->r34 / (peer->r21 + peer->r34) -
2256 * Unfortunately, in many cases the errors are
2257 * unacceptable, so for the present the rates are not
2258 * used. In future, we might find conditions where the
2259 * calculations are useful, so this should be considered
2260 * a work in progress.
2264 DPRINTF(2, ("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
2265 p_del, peer->r21 / 1e3, peer->r34 / 1e3,
2271 * That was awesome. Now hand off to the clock filter.
2273 clock_filter(peer, p_offset + peer->bias, p_del, p_disp);
2276 * If we are in broadcast calibrate mode, return to broadcast
2277 * client mode when the client is fit and the autokey dance is
2280 if ( (FLAG_BC_VOL & peer->flags)
2281 && MODE_CLIENT == peer->hmode
2282 && !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
2284 if (peer->flags & FLAG_SKEY) {
2285 if (!(~peer->crypto & CRYPTO_FLAG_ALL))
2286 peer->hmode = MODE_BCLIENT;
2288 peer->hmode = MODE_BCLIENT;
2290 #else /* !AUTOKEY follows */
2291 peer->hmode = MODE_BCLIENT;
2292 #endif /* !AUTOKEY */
2298 * clock_update - Called at system process update intervals.
2302 struct peer *peer /* peer structure pointer */
2307 #ifdef HAVE_LIBSCF_H
2309 #endif /* HAVE_LIBSCF_H */
2312 * Update the system state variables. We do this very carefully,
2313 * as the poll interval might need to be clamped differently.
2316 sys_epoch = peer->epoch;
2317 if (sys_poll < peer->minpoll)
2318 sys_poll = peer->minpoll;
2319 if (sys_poll > peer->maxpoll)
2320 sys_poll = peer->maxpoll;
2321 poll_update(peer, sys_poll);
2322 sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
2323 if ( peer->stratum == STRATUM_REFCLOCK
2324 || peer->stratum == STRATUM_UNSPEC)
2325 sys_refid = peer->refid;
2327 sys_refid = addr2refid(&peer->srcadr);
2329 * Root Dispersion (E) is defined (in RFC 5905) as:
2331 * E = p.epsilon_r + p.epsilon + p.psi + PHI*(s.t - p.t) + |THETA|
2334 * p.epsilon_r is the PollProc's root dispersion
2335 * p.epsilon is the PollProc's dispersion
2336 * p.psi is the PollProc's jitter
2337 * THETA is the combined offset
2339 * NB: Think Hard about where these numbers come from and
2340 * what they mean. When did peer->update happen? Has anything
2341 * interesting happened since then? What values are the most
2344 * DLM thinks this equation is probably the best of all worse choices.
2346 dtemp = peer->rootdisp
2349 + clock_phi * (current_time - peer->update)
2352 if (dtemp > sys_mindisp)
2353 sys_rootdisp = dtemp;
2355 sys_rootdisp = sys_mindisp;
2356 sys_rootdelay = peer->delay + peer->rootdelay;
2357 sys_reftime = peer->dst;
2359 DPRINTF(1, ("clock_update: at %lu sample %lu associd %d\n",
2360 current_time, peer->epoch, peer->associd));
2363 * Comes now the moment of truth. Crank the clock discipline and
2364 * see what comes out.
2366 switch (local_clock(peer, sys_offset)) {
2369 * Clock exceeds panic threshold. Life as we know it ends.
2372 #ifdef HAVE_LIBSCF_H
2374 * For Solaris enter the maintenance mode.
2376 if ((fmri = getenv("SMF_FMRI")) != NULL) {
2377 if (smf_maintain_instance(fmri, 0) < 0) {
2378 printf("smf_maintain_instance: %s\n",
2379 scf_strerror(scf_error()));
2383 * Sleep until SMF kills us.
2388 #endif /* HAVE_LIBSCF_H */
2393 * Clock was stepped. Flush all time values of all peers.
2397 set_sys_leap(LEAP_NOTINSYNC);
2398 sys_stratum = STRATUM_UNSPEC;
2399 memcpy(&sys_refid, "STEP", 4);
2402 L_CLR(&sys_reftime);
2403 sys_jitter = LOGTOD(sys_precision);
2404 leapsec_reset_frame();
2408 * Clock was slewed. Handle the leapsecond stuff.
2413 * If this is the first time the clock is set, reset the
2414 * leap bits. If crypto, the timer will goose the setup
2417 if (sys_leap == LEAP_NOTINSYNC) {
2418 set_sys_leap(LEAP_NOWARNING);
2422 #endif /* AUTOKEY */
2424 * If our parent process is waiting for the
2425 * first clock sync, send them home satisfied.
2427 #ifdef HAVE_WORKING_FORK
2428 if (waitsync_fd_to_close != -1) {
2429 close(waitsync_fd_to_close);
2430 waitsync_fd_to_close = -1;
2431 DPRINTF(1, ("notified parent --wait-sync is done\n"));
2433 #endif /* HAVE_WORKING_FORK */
2438 * If there is no leap second pending and the number of
2439 * survivor leap bits is greater than half the number of
2440 * survivors, try to schedule a leap for the end of the
2441 * current month. (This only works if no leap second for
2442 * that range is in the table, so doing this more than
2443 * once is mostly harmless.)
2445 if (leapsec == LSPROX_NOWARN) {
2446 if ( leap_vote_ins > leap_vote_del
2447 && leap_vote_ins > sys_survivors / 2) {
2449 leapsec_add_dyn(TRUE, now.l_ui, NULL);
2451 if ( leap_vote_del > leap_vote_ins
2452 && leap_vote_del > sys_survivors / 2) {
2454 leapsec_add_dyn(FALSE, now.l_ui, NULL);
2460 * Popcorn spike or step threshold exceeded. Pretend it never
2470 * poll_update - update peer poll interval
2474 struct peer *peer, /* peer structure pointer */
2482 * This routine figures out when the next poll should be sent.
2483 * That turns out to be wickedly complicated. One problem is
2484 * that sometimes the time for the next poll is in the past when
2485 * the poll interval is reduced. We watch out for races here
2486 * between the receive process and the poll process.
2488 * Clamp the poll interval between minpoll and maxpoll.
2490 hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
2494 * If during the crypto protocol the poll interval has changed,
2495 * the lifetimes in the key list are probably bogus. Purge the
2496 * the key list and regenerate it later.
2498 if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
2500 #endif /* AUTOKEY */
2501 peer->hpoll = hpoll;
2504 * There are three variables important for poll scheduling, the
2505 * current time (current_time), next scheduled time (nextdate)
2506 * and the earliest time (utemp). The earliest time is 2 s
2507 * seconds, but could be more due to rate management. When
2508 * sending in a burst, use the earliest time. When not in a
2509 * burst but with a reply pending, send at the earliest time
2510 * unless the next scheduled time has not advanced. This can
2511 * only happen if multiple replies are pending in the same
2512 * response interval. Otherwise, send at the later of the next
2513 * scheduled time and the earliest time.
2515 * Now we figure out if there is an override. If a burst is in
2516 * progress and we get called from the receive process, just
2517 * slink away. If called from the poll process, delay 1 s for a
2518 * reference clock, otherwise 2 s.
2520 utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
2521 (1 << peer->minpoll), ntp_minpkt);
2522 if (peer->burst > 0) {
2523 if (peer->nextdate > current_time)
2526 else if (peer->flags & FLAG_REFCLOCK)
2527 peer->nextdate = current_time + RESP_DELAY;
2528 #endif /* REFCLOCK */
2530 peer->nextdate = utemp;
2534 * If a burst is not in progress and a crypto response message
2535 * is pending, delay 2 s, but only if this is a new interval.
2537 } else if (peer->cmmd != NULL) {
2538 if (peer->nextdate > current_time) {
2539 if (peer->nextdate + ntp_minpkt != utemp)
2540 peer->nextdate = utemp;
2542 peer->nextdate = utemp;
2544 #endif /* AUTOKEY */
2547 * The ordinary case. If a retry, use minpoll; if unreachable,
2548 * use host poll; otherwise, use the minimum of host and peer
2549 * polls; In other words, oversampling is okay but
2550 * understampling is evil. Use the maximum of this value and the
2551 * headway. If the average headway is greater than the headway
2552 * threshold, increase the headway by the minimum interval.
2555 if (peer->retry > 0)
2556 hpoll = peer->minpoll;
2557 else if (!(peer->reach))
2558 hpoll = peer->hpoll;
2560 hpoll = min(peer->ppoll, peer->hpoll);
2562 if (peer->flags & FLAG_REFCLOCK)
2565 #endif /* REFCLOCK */
2566 next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
2568 next += peer->outdate;
2570 peer->nextdate = next;
2572 peer->nextdate = utemp;
2573 if (peer->throttle > (1 << peer->minpoll))
2574 peer->nextdate += ntp_minpkt;
2576 DPRINTF(2, ("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
2577 current_time, ntoa(&peer->srcadr), peer->hpoll,
2578 peer->burst, peer->retry, peer->throttle,
2579 utemp - current_time, peer->nextdate -
2585 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
2590 struct peer *peer, /* peer structure */
2591 const char *ident /* tally lights */
2598 * If cryptographic credentials have been acquired, toss them to
2599 * Valhalla. Note that autokeys are ephemeral, in that they are
2600 * tossed immediately upon use. Therefore, the keylist can be
2601 * purged anytime without needing to preserve random keys. Note
2602 * that, if the peer is purged, the cryptographic variables are
2603 * purged, too. This makes it much harder to sneak in some
2604 * unauthenticated data in the clock filter.
2607 if (peer->iffval != NULL)
2608 BN_free(peer->iffval);
2609 value_free(&peer->cookval);
2610 value_free(&peer->recval);
2611 value_free(&peer->encrypt);
2612 value_free(&peer->sndval);
2613 if (peer->cmmd != NULL)
2615 if (peer->subject != NULL)
2616 free(peer->subject);
2617 if (peer->issuer != NULL)
2619 #endif /* AUTOKEY */
2622 * Clear all values, including the optional crypto values above.
2624 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO(peer));
2625 peer->ppoll = peer->maxpoll;
2626 peer->hpoll = peer->minpoll;
2627 peer->disp = MAXDISPERSE;
2628 peer->flash = peer_unfit(peer);
2629 peer->jitter = LOGTOD(sys_precision);
2632 * If interleave mode, initialize the alternate origin switch.
2634 if (peer->flags & FLAG_XLEAVE)
2636 for (u = 0; u < NTP_SHIFT; u++) {
2637 peer->filter_order[u] = u;
2638 peer->filter_disp[u] = MAXDISPERSE;
2641 if (!(peer->flags & FLAG_REFCLOCK)) {
2643 peer->leap = LEAP_NOTINSYNC;
2644 peer->stratum = STRATUM_UNSPEC;
2645 memcpy(&peer->refid, ident, 4);
2651 * During initialization use the association count to spread out
2652 * the polls at one-second intervals. Passive associations'
2653 * first poll is delayed by the "discard minimum" to avoid rate
2654 * limiting. Other post-startup new or cleared associations
2655 * randomize the first poll over the minimum poll interval to
2658 peer->nextdate = peer->update = peer->outdate = current_time;
2660 peer->nextdate += peer_associations;
2661 } else if (MODE_PASSIVE == peer->hmode) {
2662 peer->nextdate += ntp_minpkt;
2664 peer->nextdate += ntp_random() % peer->minpoll;
2667 peer->refresh = current_time + (1 << NTP_REFRESH);
2668 #endif /* AUTOKEY */
2669 DPRINTF(1, ("peer_clear: at %ld next %ld associd %d refid %s\n",
2670 current_time, peer->nextdate, peer->associd,
2676 * clock_filter - add incoming clock sample to filter register and run
2677 * the filter procedure to find the best sample.
2681 struct peer *peer, /* peer structure pointer */
2682 double sample_offset, /* clock offset */
2683 double sample_delay, /* roundtrip delay */
2684 double sample_disp /* dispersion */
2687 double dst[NTP_SHIFT]; /* distance vector */
2688 int ord[NTP_SHIFT]; /* index vector */
2690 double dtemp, etemp;
2694 * A sample consists of the offset, delay, dispersion and epoch
2695 * of arrival. The offset and delay are determined by the on-
2696 * wire protocol. The dispersion grows from the last outbound
2697 * packet to the arrival of this one increased by the sum of the
2698 * peer precision and the system precision as required by the
2699 * error budget. First, shift the new arrival into the shift
2700 * register discarding the oldest one.
2702 j = peer->filter_nextpt;
2703 peer->filter_offset[j] = sample_offset;
2704 peer->filter_delay[j] = sample_delay;
2705 peer->filter_disp[j] = sample_disp;
2706 peer->filter_epoch[j] = current_time;
2707 j = (j + 1) % NTP_SHIFT;
2708 peer->filter_nextpt = j;
2711 * Update dispersions since the last update and at the same
2712 * time initialize the distance and index lists. Since samples
2713 * become increasingly uncorrelated beyond the Allan intercept,
2714 * only under exceptional cases will an older sample be used.
2715 * Therefore, the distance list uses a compound metric. If the
2716 * dispersion is greater than the maximum dispersion, clamp the
2717 * distance at that value. If the time since the last update is
2718 * less than the Allan intercept use the delay; otherwise, use
2719 * the sum of the delay and dispersion.
2721 dtemp = clock_phi * (current_time - peer->update);
2722 peer->update = current_time;
2723 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2725 peer->filter_disp[j] += dtemp;
2726 if (peer->filter_disp[j] >= MAXDISPERSE) {
2727 peer->filter_disp[j] = MAXDISPERSE;
2728 dst[i] = MAXDISPERSE;
2729 } else if (peer->update - peer->filter_epoch[j] >
2730 (u_long)ULOGTOD(allan_xpt)) {
2731 dst[i] = peer->filter_delay[j] +
2732 peer->filter_disp[j];
2734 dst[i] = peer->filter_delay[j];
2737 j = (j + 1) % NTP_SHIFT;
2741 * If the clock has stabilized, sort the samples by distance.
2743 if (freq_cnt == 0) {
2744 for (i = 1; i < NTP_SHIFT; i++) {
2745 for (j = 0; j < i; j++) {
2746 if (dst[j] > dst[i]) {
2759 * Copy the index list to the association structure so ntpq
2760 * can see it later. Prune the distance list to leave only
2761 * samples less than the maximum dispersion, which disfavors
2762 * uncorrelated samples older than the Allan intercept. To
2763 * further improve the jitter estimate, of the remainder leave
2764 * only samples less than the maximum distance, but keep at
2765 * least two samples for jitter calculation.
2768 for (i = 0; i < NTP_SHIFT; i++) {
2769 peer->filter_order[i] = (u_char) ord[i];
2770 if ( dst[i] >= MAXDISPERSE
2771 || (m >= 2 && dst[i] >= sys_maxdist))
2777 * Compute the dispersion and jitter. The dispersion is weighted
2778 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2779 * to 1.0. The jitter is the RMS differences relative to the
2780 * lowest delay sample.
2782 peer->disp = peer->jitter = 0;
2784 for (i = NTP_SHIFT - 1; i >= 0; i--) {
2786 peer->disp = NTP_FWEIGHT * (peer->disp +
2787 peer->filter_disp[j]);
2789 peer->jitter += DIFF(peer->filter_offset[j],
2790 peer->filter_offset[k]);
2794 * If no acceptable samples remain in the shift register,
2795 * quietly tiptoe home leaving only the dispersion. Otherwise,
2796 * save the offset, delay and jitter. Note the jitter must not
2797 * be less than the precision.
2803 etemp = fabs(peer->offset - peer->filter_offset[k]);
2804 peer->offset = peer->filter_offset[k];
2805 peer->delay = peer->filter_delay[k];
2807 peer->jitter /= m - 1;
2808 peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
2811 * If the the new sample and the current sample are both valid
2812 * and the difference between their offsets exceeds CLOCK_SGATE
2813 * (3) times the jitter and the interval between them is less
2814 * than twice the host poll interval, consider the new sample
2815 * a popcorn spike and ignore it.
2817 if ( peer->disp < sys_maxdist
2818 && peer->filter_disp[k] < sys_maxdist
2819 && etemp > CLOCK_SGATE * peer->jitter
2820 && peer->filter_epoch[k] - peer->epoch
2821 < 2. * ULOGTOD(peer->hpoll)) {
2822 snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
2823 report_event(PEVNT_POPCORN, peer, tbuf);
2828 * A new minimum sample is useful only if it is later than the
2829 * last one used. In this design the maximum lifetime of any
2830 * sample is not greater than eight times the poll interval, so
2831 * the maximum interval between minimum samples is eight
2834 if (peer->filter_epoch[k] <= peer->epoch) {
2835 DPRINTF(2, ("clock_filter: old sample %lu\n", current_time -
2836 peer->filter_epoch[k]));
2839 peer->epoch = peer->filter_epoch[k];
2842 * The mitigated sample statistics are saved for later
2843 * processing. If not synchronized or not in a burst, tickle the
2844 * clock select algorithm.
2846 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
2847 peer->offset, peer->delay, peer->disp, peer->jitter);
2848 DPRINTF(1, ("clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
2849 m, peer->offset, peer->delay, peer->disp,
2851 if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
2857 * clock_select - find the pick-of-the-litter clock
2859 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
2860 * be enabled, even if declared falseticker, (2) only the prefer peer
2861 * can be selected as the system peer, (3) if the external source is
2862 * down, the system leap bits are set to 11 and the stratum set to
2876 double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
2877 struct endpoint endp;
2878 struct peer *osys_peer;
2879 struct peer *sys_prefer = NULL; /* prefer peer */
2880 struct peer *typesystem = NULL;
2881 struct peer *typeorphan = NULL;
2883 struct peer *typeacts = NULL;
2884 struct peer *typelocal = NULL;
2885 struct peer *typepps = NULL;
2886 #endif /* REFCLOCK */
2887 static struct endpoint *endpoint = NULL;
2888 static int *indx = NULL;
2889 static peer_select *peers = NULL;
2890 static u_int endpoint_size = 0;
2891 static u_int peers_size = 0;
2892 static u_int indx_size = 0;
2896 * Initialize and create endpoint, index and peer lists big
2897 * enough to handle all associations.
2899 osys_peer = sys_peer;
2902 set_sys_leap(LEAP_NOTINSYNC);
2903 sys_stratum = STRATUM_UNSPEC;
2904 memcpy(&sys_refid, "DOWN", 4);
2905 #endif /* LOCKCLOCK */
2908 * Allocate dynamic space depending on the number of
2912 for (peer = peer_list; peer != NULL; peer = peer->p_link)
2914 endpoint_size = ALIGNED_SIZE(nlist * 2 * sizeof(*endpoint));
2915 peers_size = ALIGNED_SIZE(nlist * sizeof(*peers));
2916 indx_size = ALIGNED_SIZE(nlist * 2 * sizeof(*indx));
2917 octets = endpoint_size + peers_size + indx_size;
2918 endpoint = erealloc(endpoint, octets);
2919 peers = INC_ALIGNED_PTR(endpoint, endpoint_size);
2920 indx = INC_ALIGNED_PTR(peers, peers_size);
2923 * Initially, we populate the island with all the rifraff peers
2924 * that happen to be lying around. Those with seriously
2925 * defective clocks are immediately booted off the island. Then,
2926 * the falsetickers are culled and put to sea. The truechimers
2927 * remaining are subject to repeated rounds where the most
2928 * unpopular at each round is kicked off. When the population
2929 * has dwindled to sys_minclock, the survivors split a million
2930 * bucks and collectively crank the chimes.
2932 nlist = nl2 = 0; /* none yet */
2933 for (peer = peer_list; peer != NULL; peer = peer->p_link) {
2934 peer->new_status = CTL_PST_SEL_REJECT;
2937 * Leave the island immediately if the peer is
2938 * unfit to synchronize.
2940 if (peer_unfit(peer))
2944 * If this peer is an orphan parent, elect the
2945 * one with the lowest metric defined as the
2946 * IPv4 address or the first 64 bits of the
2947 * hashed IPv6 address. To ensure convergence
2948 * on the same selected orphan, consider as
2949 * well that this system may have the lowest
2950 * metric and be the orphan parent. If this
2951 * system wins, sys_peer will be NULL to trigger
2952 * orphan mode in timer().
2954 if (peer->stratum == sys_orphan) {
2958 if (peer->dstadr != NULL)
2959 localmet = ntohl(peer->dstadr->addr_refid);
2961 localmet = U_INT32_MAX;
2962 peermet = ntohl(addr2refid(&peer->srcadr));
2963 if (peermet < localmet && peermet < orphmet) {
2971 * If this peer could have the orphan parent
2972 * as a synchronization ancestor, exclude it
2973 * from selection to avoid forming a
2974 * synchronization loop within the orphan mesh,
2975 * triggering stratum climb to infinity
2976 * instability. Peers at stratum higher than
2977 * the orphan stratum could have the orphan
2978 * parent in ancestry so are excluded.
2979 * See http://bugs.ntp.org/2050
2981 if (peer->stratum > sys_orphan)
2985 * The following are special cases. We deal
2988 if (!(peer->flags & FLAG_PREFER)) {
2989 switch (peer->refclktype) {
2990 case REFCLK_LOCALCLOCK:
2991 if ( current_time > orphwait
2992 && typelocal == NULL)
2997 if ( current_time > orphwait
2998 && typeacts == NULL)
3003 #endif /* REFCLOCK */
3006 * If we get this far, the peer can stay on the
3007 * island, but does not yet have the immunity
3010 peer->new_status = CTL_PST_SEL_SANE;
3011 f = root_distance(peer);
3012 peers[nlist].peer = peer;
3013 peers[nlist].error = peer->jitter;
3014 peers[nlist].synch = f;
3018 * Insert each interval endpoint on the unsorted
3022 endpoint[nl2].type = -1; /* lower end */
3023 endpoint[nl2].val = e - f;
3025 endpoint[nl2].type = 1; /* upper end */
3026 endpoint[nl2].val = e + f;
3030 * Construct sorted indx[] of endpoint[] indexes ordered by
3033 for (i = 0; i < nl2; i++)
3035 for (i = 0; i < nl2; i++) {
3036 endp = endpoint[indx[i]];
3039 for (j = i + 1; j < nl2; j++) {
3040 endp = endpoint[indx[j]];
3052 for (i = 0; i < nl2; i++)
3053 DPRINTF(3, ("select: endpoint %2d %.6f\n",
3054 endpoint[indx[i]].type, endpoint[indx[i]].val));
3057 * This is the actual algorithm that cleaves the truechimers
3058 * from the falsetickers. The original algorithm was described
3059 * in Keith Marzullo's dissertation, but has been modified for
3062 * Briefly put, we first assume there are no falsetickers, then
3063 * scan the candidate list first from the low end upwards and
3064 * then from the high end downwards. The scans stop when the
3065 * number of intersections equals the number of candidates less
3066 * the number of falsetickers. If this doesn't happen for a
3067 * given number of falsetickers, we bump the number of
3068 * falsetickers and try again. If the number of falsetickers
3069 * becomes equal to or greater than half the number of
3070 * candidates, the Albanians have won the Byzantine wars and
3071 * correct synchronization is not possible.
3073 * Here, nlist is the number of candidates and allow is the
3074 * number of falsetickers. Upon exit, the truechimers are the
3075 * survivors with offsets not less than low and not greater than
3076 * high. There may be none of them.
3080 for (allow = 0; 2 * allow < nlist; allow++) {
3083 * Bound the interval (low, high) as the smallest
3084 * interval containing points from the most sources.
3087 for (i = 0; i < nl2; i++) {
3088 low = endpoint[indx[i]].val;
3089 n -= endpoint[indx[i]].type;
3090 if (n >= nlist - allow)
3094 for (j = nl2 - 1; j >= 0; j--) {
3095 high = endpoint[indx[j]].val;
3096 n += endpoint[indx[j]].type;
3097 if (n >= nlist - allow)
3102 * If an interval containing truechimers is found, stop.
3103 * If not, increase the number of falsetickers and go
3111 * Clustering algorithm. Whittle candidate list of falsetickers,
3112 * who leave the island immediately. The TRUE peer is always a
3113 * truechimer. We must leave at least one peer to collect the
3116 * We assert the correct time is contained in the interval, but
3117 * the best offset estimate for the interval might not be
3118 * contained in the interval. For this purpose, a truechimer is
3119 * defined as the midpoint of an interval that overlaps the
3120 * intersection interval.
3123 for (i = 0; i < nlist; i++) {
3126 peer = peers[i].peer;
3129 || peer->offset + h < low
3130 || peer->offset - h > high
3131 ) && !(peer->flags & FLAG_TRUE))
3136 * Eligible PPS peers must survive the intersection
3137 * algorithm. Use the first one found, but don't
3138 * include any of them in the cluster population.
3140 if (peer->flags & FLAG_PPS) {
3141 if (typepps == NULL)
3143 if (!(peer->flags & FLAG_TSTAMP_PPS))
3146 #endif /* REFCLOCK */
3149 peers[j] = peers[i];
3155 * If no survivors remain at this point, check if the modem
3156 * driver, local driver or orphan parent in that order. If so,
3157 * nominate the first one found as the only survivor.
3158 * Otherwise, give up and leave the island to the rats.
3162 peers[0].synch = sys_mindisp;
3164 if (typeacts != NULL) {
3165 peers[0].peer = typeacts;
3167 } else if (typelocal != NULL) {
3168 peers[0].peer = typelocal;
3171 #endif /* REFCLOCK */
3172 if (typeorphan != NULL) {
3173 peers[0].peer = typeorphan;
3179 * Mark the candidates at this point as truechimers.
3181 for (i = 0; i < nlist; i++) {
3182 peers[i].peer->new_status = CTL_PST_SEL_SELCAND;
3183 DPRINTF(2, ("select: survivor %s %f\n",
3184 stoa(&peers[i].peer->srcadr), peers[i].synch));
3188 * Now, vote outliers off the island by select jitter weighted
3189 * by root distance. Continue voting as long as there are more
3190 * than sys_minclock survivors and the select jitter of the peer
3191 * with the worst metric is greater than the minimum peer
3192 * jitter. Stop if we are about to discard a TRUE or PREFER
3193 * peer, who of course have the immunity idol.
3200 for (i = 0; i < nlist; i++) {
3201 if (peers[i].error < d)
3203 peers[i].seljit = 0;
3206 for (j = 0; j < nlist; j++)
3207 f += DIFF(peers[j].peer->offset,
3208 peers[i].peer->offset);
3209 peers[i].seljit = SQRT(f / (nlist - 1));
3211 if (peers[i].seljit * peers[i].synch > e) {
3212 g = peers[i].seljit;
3213 e = peers[i].seljit * peers[i].synch;
3217 g = max(g, LOGTOD(sys_precision));
3218 if ( nlist <= max(1, sys_minclock)
3220 || ((FLAG_TRUE | FLAG_PREFER) & peers[k].peer->flags))
3223 DPRINTF(3, ("select: drop %s seljit %.6f jit %.6f\n",
3224 ntoa(&peers[k].peer->srcadr), g, d));
3225 if (nlist > sys_maxclock)
3226 peers[k].peer->new_status = CTL_PST_SEL_EXCESS;
3227 for (j = k + 1; j < nlist; j++)
3228 peers[j - 1] = peers[j];
3233 * What remains is a list usually not greater than sys_minclock
3234 * peers. Note that unsynchronized peers cannot survive this
3235 * far. Count and mark these survivors.
3237 * While at it, count the number of leap warning bits found.
3238 * This will be used later to vote the system leap warning bit.
3239 * If a leap warning bit is found on a reference clock, the vote
3242 * Choose the system peer using a hybrid metric composed of the
3243 * selection jitter scaled by the root distance augmented by
3244 * stratum scaled by sys_mindisp (.001 by default). The goal of
3245 * the small stratum factor is to avoid clockhop between a
3246 * reference clock and a network peer which has a refclock and
3247 * is using an older ntpd, which does not floor sys_rootdisp at
3250 * In contrast, ntpd 4.2.6 and earlier used stratum primarily
3251 * in selecting the system peer, using a weight of 1 second of
3252 * additional root distance per stratum. This heavy bias is no
3253 * longer appropriate, as the scaled root distance provides a
3254 * more rational metric carrying the cumulative error budget.
3260 for (i = 0; i < nlist; i++) {
3261 peer = peers[i].peer;
3263 peer->new_status = CTL_PST_SEL_SYNCCAND;
3265 if (peer->leap == LEAP_ADDSECOND) {
3266 if (peer->flags & FLAG_REFCLOCK)
3267 leap_vote_ins = nlist;
3268 else if (leap_vote_ins < nlist)
3271 if (peer->leap == LEAP_DELSECOND) {
3272 if (peer->flags & FLAG_REFCLOCK)
3273 leap_vote_del = nlist;
3274 else if (leap_vote_del < nlist)
3277 if (peer->flags & FLAG_PREFER)
3279 speermet = peers[i].seljit * peers[i].synch +
3280 peer->stratum * sys_mindisp;
3288 * Unless there are at least sys_misane survivors, leave the
3289 * building dark. Otherwise, do a clockhop dance. Ordinarily,
3290 * use the selected survivor speer. However, if the current
3291 * system peer is not speer, stay with the current system peer
3292 * as long as it doesn't get too old or too ugly.
3294 if (nlist > 0 && nlist >= sys_minsane) {
3297 typesystem = peers[speer].peer;
3298 if (osys_peer == NULL || osys_peer == typesystem) {
3300 } else if ((x = fabs(typesystem->offset -
3301 osys_peer->offset)) < sys_mindisp) {
3302 if (sys_clockhop == 0)
3303 sys_clockhop = sys_mindisp;
3306 DPRINTF(1, ("select: clockhop %d %.6f %.6f\n",
3307 j, x, sys_clockhop));
3308 if (fabs(x) < sys_clockhop)
3309 typesystem = osys_peer;
3318 * Mitigation rules of the game. We have the pick of the
3319 * litter in typesystem if any survivors are left. If
3320 * there is a prefer peer, use its offset and jitter.
3321 * Otherwise, use the combined offset and jitter of all kitters.
3323 if (typesystem != NULL) {
3324 if (sys_prefer == NULL) {
3325 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3326 clock_combine(peers, sys_survivors, speer);
3328 typesystem = sys_prefer;
3330 typesystem->new_status = CTL_PST_SEL_SYSPEER;
3331 sys_offset = typesystem->offset;
3332 sys_jitter = typesystem->jitter;
3334 DPRINTF(1, ("select: combine offset %.9f jitter %.9f\n",
3335 sys_offset, sys_jitter));
3339 * If a PPS driver is lit and the combined offset is less than
3340 * 0.4 s, select the driver as the PPS peer and use its offset
3341 * and jitter. However, if this is the atom driver, use it only
3342 * if there is a prefer peer or there are no survivors and none
3345 if ( typepps != NULL
3346 && fabs(sys_offset) < 0.4
3347 && ( typepps->refclktype != REFCLK_ATOM_PPS
3348 || ( typepps->refclktype == REFCLK_ATOM_PPS
3349 && ( sys_prefer != NULL
3350 || (typesystem == NULL && sys_minsane == 0))))) {
3351 typesystem = typepps;
3353 typesystem->new_status = CTL_PST_SEL_PPS;
3354 sys_offset = typesystem->offset;
3355 sys_jitter = typesystem->jitter;
3356 DPRINTF(1, ("select: pps offset %.9f jitter %.9f\n",
3357 sys_offset, sys_jitter));
3359 #endif /* REFCLOCK */
3362 * If there are no survivors at this point, there is no
3363 * system peer. If so and this is an old update, keep the
3364 * current statistics, but do not update the clock.
3366 if (typesystem == NULL) {
3367 if (osys_peer != NULL) {
3368 if (sys_orphwait > 0)
3369 orphwait = current_time + sys_orphwait;
3370 report_event(EVNT_NOPEER, NULL, NULL);
3373 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3374 peer->status = peer->new_status;
3379 * Do not use old data, as this may mess up the clock discipline
3382 if (typesystem->epoch <= sys_epoch)
3386 * We have found the alpha male. Wind the clock.
3388 if (osys_peer != typesystem)
3389 report_event(PEVNT_NEWPEER, typesystem, NULL);
3390 for (peer = peer_list; peer != NULL; peer = peer->p_link)
3391 peer->status = peer->new_status;
3392 clock_update(typesystem);
3398 peer_select * peers, /* survivor list */
3399 int npeers, /* number of survivors */
3400 int syspeer /* index of sys.peer */
3407 for (i = 0; i < npeers; i++) {
3408 x = 1. / peers[i].synch;
3410 z += x * peers[i].peer->offset;
3411 w += x * DIFF(peers[i].peer->offset,
3412 peers[syspeer].peer->offset);
3415 sys_jitter = SQRT(w / y + SQUARE(peers[syspeer].seljit));
3420 * root_distance - compute synchronization distance from peer to root
3424 struct peer *peer /* peer structure pointer */
3430 * Root Distance (LAMBDA) is defined as:
3431 * (delta + DELTA)/2 + epsilon + EPSILON + phi
3434 * delta is the round-trip delay
3435 * DELTA is the root delay
3436 * epsilon is the remote server precision + local precision
3437 * + (15 usec each second)
3438 * EPSILON is the root dispersion
3439 * phi is the peer jitter statistic
3441 * NB: Think hard about why we are using these values, and what
3442 * the alternatives are, and the various pros/cons.
3444 * DLM thinks these are probably the best choices from any of the
3445 * other worse choices.
3447 dtemp = (peer->delay + peer->rootdelay) / 2
3448 + LOGTOD(peer->precision)
3449 + LOGTOD(sys_precision)
3450 + clock_phi * (current_time - peer->update)
3454 * Careful squeak here. The value returned must be greater than
3455 * the minimum root dispersion in order to avoid clockhop with
3456 * highly precise reference clocks. Note that the root distance
3457 * cannot exceed the sys_maxdist, as this is the cutoff by the
3458 * selection algorithm.
3460 if (dtemp < sys_mindisp)
3461 dtemp = sys_mindisp;
3467 * peer_xmit - send packet for persistent association.
3471 struct peer *peer /* peer structure pointer */
3474 struct pkt xpkt; /* transmit packet */
3475 size_t sendlen, authlen;
3476 keyid_t xkeyid = 0; /* transmit key ID */
3477 l_fp xmt_tx, xmt_ty;
3479 if (!peer->dstadr) /* drop peers without interface */
3482 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
3484 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3485 xpkt.ppoll = peer->hpoll;
3486 xpkt.precision = sys_precision;
3487 xpkt.refid = sys_refid;
3488 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3489 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3490 HTONL_FP(&sys_reftime, &xpkt.reftime);
3491 HTONL_FP(&peer->rec, &xpkt.org);
3492 HTONL_FP(&peer->dst, &xpkt.rec);
3495 * If the received packet contains a MAC, the transmitted packet
3496 * is authenticated and contains a MAC. If not, the transmitted
3497 * packet is not authenticated.
3499 * It is most important when autokey is in use that the local
3500 * interface IP address be known before the first packet is
3501 * sent. Otherwise, it is not possible to compute a correct MAC
3502 * the recipient will accept. Thus, the I/O semantics have to do
3503 * a little more work. In particular, the wildcard interface
3504 * might not be usable.
3506 sendlen = LEN_PKT_NOMAC;
3509 !(peer->flags & FLAG_SKEY) &&
3510 #endif /* !AUTOKEY */
3514 * Transmit a-priori timestamps
3516 get_systime(&xmt_tx);
3517 if (peer->flip == 0) { /* basic mode */
3518 peer->aorg = xmt_tx;
3519 HTONL_FP(&xmt_tx, &xpkt.xmt);
3520 } else { /* interleaved modes */
3521 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3522 HTONL_FP(&xmt_tx, &xpkt.xmt);
3524 HTONL_FP(&peer->borg,
3527 HTONL_FP(&peer->aorg,
3529 } else { /* symmetric */
3531 HTONL_FP(&peer->borg,
3534 HTONL_FP(&peer->aorg,
3538 peer->t21_bytes = sendlen;
3539 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
3542 peer->throttle += (1 << peer->minpoll) - 2;
3545 * Capture a-posteriori timestamps
3547 get_systime(&xmt_ty);
3548 if (peer->flip != 0) { /* interleaved modes */
3550 peer->aorg = xmt_ty;
3552 peer->borg = xmt_ty;
3553 peer->flip = -peer->flip;
3555 L_SUB(&xmt_ty, &xmt_tx);
3556 LFPTOD(&xmt_ty, peer->xleave);
3557 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d len %zu xmt %#010x.%08x\n",
3559 peer->dstadr ? stoa(&peer->dstadr->sin) : "-",
3560 stoa(&peer->srcadr), peer->hmode, sendlen,
3561 xmt_tx.l_ui, xmt_tx.l_uf));
3566 * Authentication is enabled, so the transmitted packet must be
3567 * authenticated. If autokey is enabled, fuss with the various
3568 * modes; otherwise, symmetric key cryptography is used.
3571 if (peer->flags & FLAG_SKEY) {
3572 struct exten *exten; /* extension field */
3575 * The Public Key Dance (PKD): Cryptographic credentials
3576 * are contained in extension fields, each including a
3577 * 4-octet length/code word followed by a 4-octet
3578 * association ID and optional additional data. Optional
3579 * data includes a 4-octet data length field followed by
3580 * the data itself. Request messages are sent from a
3581 * configured association; response messages can be sent
3582 * from a configured association or can take the fast
3583 * path without ever matching an association. Response
3584 * messages have the same code as the request, but have
3585 * a response bit and possibly an error bit set. In this
3586 * implementation, a message may contain no more than
3587 * one command and one or more responses.
3589 * Cryptographic session keys include both a public and
3590 * a private componet. Request and response messages
3591 * using extension fields are always sent with the
3592 * private component set to zero. Packets without
3593 * extension fields indlude the private component when
3594 * the session key is generated.
3599 * Allocate and initialize a keylist if not
3600 * already done. Then, use the list in inverse
3601 * order, discarding keys once used. Keep the
3602 * latest key around until the next one, so
3603 * clients can use client/server packets to
3604 * compute propagation delay.
3606 * Note that once a key is used from the list,
3607 * it is retained in the key cache until the
3608 * next key is used. This is to allow a client
3609 * to retrieve the encrypted session key
3610 * identifier to verify authenticity.
3612 * If for some reason a key is no longer in the
3613 * key cache, a birthday has happened or the key
3614 * has expired, so the pseudo-random sequence is
3615 * broken. In that case, purge the keylist and
3618 if (peer->keynumber == 0)
3619 make_keylist(peer, peer->dstadr);
3622 xkeyid = peer->keylist[peer->keynumber];
3623 if (authistrusted(xkeyid))
3628 peer->keyid = xkeyid;
3630 switch (peer->hmode) {
3633 * In broadcast server mode the autokey values are
3634 * required by the broadcast clients. Push them when a
3635 * new keylist is generated; otherwise, push the
3636 * association message so the client can request them at
3639 case MODE_BROADCAST:
3640 if (peer->flags & FLAG_ASSOC)
3641 exten = crypto_args(peer, CRYPTO_AUTO |
3642 CRYPTO_RESP, peer->associd, NULL);
3644 exten = crypto_args(peer, CRYPTO_ASSOC |
3645 CRYPTO_RESP, peer->associd, NULL);
3649 * In symmetric modes the parameter, certificate,
3650 * identity, cookie and autokey exchanges are
3651 * required. The leapsecond exchange is optional. But, a
3652 * peer will not believe the other peer until the other
3653 * peer has synchronized, so the certificate exchange
3654 * might loop until then. If a peer finds a broken
3655 * autokey sequence, it uses the autokey exchange to
3656 * retrieve the autokey values. In any case, if a new
3657 * keylist is generated, the autokey values are pushed.
3663 * Parameter, certificate and identity.
3666 exten = crypto_args(peer, CRYPTO_ASSOC,
3667 peer->associd, hostval.ptr);
3668 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3669 exten = crypto_args(peer, CRYPTO_CERT,
3670 peer->associd, peer->issuer);
3671 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3672 exten = crypto_args(peer,
3673 crypto_ident(peer), peer->associd,
3677 * Cookie and autokey. We request the cookie
3678 * only when the this peer and the other peer
3679 * are synchronized. But, this peer needs the
3680 * autokey values when the cookie is zero. Any
3681 * time we regenerate the key list, we offer the
3682 * autokey values without being asked. If for
3683 * some reason either peer finds a broken
3684 * autokey sequence, the autokey exchange is
3685 * used to retrieve the autokey values.
3687 else if ( sys_leap != LEAP_NOTINSYNC
3688 && peer->leap != LEAP_NOTINSYNC
3689 && !(peer->crypto & CRYPTO_FLAG_COOK))
3690 exten = crypto_args(peer, CRYPTO_COOK,
3691 peer->associd, NULL);
3692 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3693 exten = crypto_args(peer, CRYPTO_AUTO,
3694 peer->associd, NULL);
3695 else if ( peer->flags & FLAG_ASSOC
3696 && peer->crypto & CRYPTO_FLAG_SIGN)
3697 exten = crypto_args(peer, CRYPTO_AUTO |
3698 CRYPTO_RESP, peer->assoc, NULL);
3701 * Wait for clock sync, then sign the
3702 * certificate and retrieve the leapsecond
3705 else if (sys_leap == LEAP_NOTINSYNC)
3708 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3709 exten = crypto_args(peer, CRYPTO_SIGN,
3710 peer->associd, hostval.ptr);
3711 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3712 exten = crypto_args(peer, CRYPTO_LEAP,
3713 peer->associd, NULL);
3717 * In client mode the parameter, certificate, identity,
3718 * cookie and sign exchanges are required. The
3719 * leapsecond exchange is optional. If broadcast client
3720 * mode the same exchanges are required, except that the
3721 * autokey exchange is substitutes for the cookie
3722 * exchange, since the cookie is always zero. If the
3723 * broadcast client finds a broken autokey sequence, it
3724 * uses the autokey exchange to retrieve the autokey
3730 * Parameter, certificate and identity.
3733 exten = crypto_args(peer, CRYPTO_ASSOC,
3734 peer->associd, hostval.ptr);
3735 else if (!(peer->crypto & CRYPTO_FLAG_CERT))
3736 exten = crypto_args(peer, CRYPTO_CERT,
3737 peer->associd, peer->issuer);
3738 else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
3739 exten = crypto_args(peer,
3740 crypto_ident(peer), peer->associd,
3744 * Cookie and autokey. These are requests, but
3745 * we use the peer association ID with autokey
3746 * rather than our own.
3748 else if (!(peer->crypto & CRYPTO_FLAG_COOK))
3749 exten = crypto_args(peer, CRYPTO_COOK,
3750 peer->associd, NULL);
3751 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
3752 exten = crypto_args(peer, CRYPTO_AUTO,
3756 * Wait for clock sync, then sign the
3757 * certificate and retrieve the leapsecond
3760 else if (sys_leap == LEAP_NOTINSYNC)
3763 else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
3764 exten = crypto_args(peer, CRYPTO_SIGN,
3765 peer->associd, hostval.ptr);
3766 else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
3767 exten = crypto_args(peer, CRYPTO_LEAP,
3768 peer->associd, NULL);
3773 * Add a queued extension field if present. This is
3774 * always a request message, so the reply ID is already
3775 * in the message. If an error occurs, the error bit is
3776 * lit in the response.
3778 if (peer->cmmd != NULL) {
3781 temp32 = CRYPTO_RESP;
3782 peer->cmmd->opcode |= htonl(temp32);
3783 sendlen += crypto_xmit(peer, &xpkt, NULL,
3784 sendlen, peer->cmmd, 0);
3790 * Add an extension field created above. All but the
3791 * autokey response message are request messages.
3793 if (exten != NULL) {
3794 if (exten->opcode != 0)
3795 sendlen += crypto_xmit(peer, &xpkt,
3796 NULL, sendlen, exten, 0);
3801 * Calculate the next session key. Since extension
3802 * fields are present, the cookie value is zero.
3804 if (sendlen > (int)LEN_PKT_NOMAC) {
3805 session_key(&peer->dstadr->sin, &peer->srcadr,
3809 #endif /* AUTOKEY */
3812 * Transmit a-priori timestamps
3814 get_systime(&xmt_tx);
3815 if (peer->flip == 0) { /* basic mode */
3816 peer->aorg = xmt_tx;
3817 HTONL_FP(&xmt_tx, &xpkt.xmt);
3818 } else { /* interleaved modes */
3819 if (peer->hmode == MODE_BROADCAST) { /* bcst */
3820 HTONL_FP(&xmt_tx, &xpkt.xmt);
3822 HTONL_FP(&peer->borg, &xpkt.org);
3824 HTONL_FP(&peer->aorg, &xpkt.org);
3825 } else { /* symmetric */
3827 HTONL_FP(&peer->borg, &xpkt.xmt);
3829 HTONL_FP(&peer->aorg, &xpkt.xmt);
3832 xkeyid = peer->keyid;
3833 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
3835 report_event(PEVNT_AUTH, peer, "no key");
3836 peer->flash |= TEST5; /* auth error */
3842 if (xkeyid > NTP_MAXKEY)
3843 authtrust(xkeyid, 0);
3844 #endif /* AUTOKEY */
3845 if (sendlen > sizeof(xpkt)) {
3846 msyslog(LOG_ERR, "peer_xmit: buffer overflow %zu", sendlen);
3849 peer->t21_bytes = sendlen;
3850 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
3853 peer->throttle += (1 << peer->minpoll) - 2;
3856 * Capture a-posteriori timestamps
3858 get_systime(&xmt_ty);
3859 if (peer->flip != 0) { /* interleaved modes */
3861 peer->aorg = xmt_ty;
3863 peer->borg = xmt_ty;
3864 peer->flip = -peer->flip;
3866 L_SUB(&xmt_ty, &xmt_tx);
3867 LFPTOD(&xmt_ty, peer->xleave);
3869 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %zu index %d\n",
3870 current_time, latoa(peer->dstadr),
3871 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
3873 #else /* !AUTOKEY follows */
3874 DPRINTF(1, ("peer_xmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3875 current_time, peer->dstadr ?
3876 ntoa(&peer->dstadr->sin) : "-",
3877 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen));
3878 #endif /* !AUTOKEY */
3887 leap_smear_add_offs(
3893 L_ADD(t, &leap_smear.offset);
3898 #endif /* LEAP_SMEAR */
3902 * fast_xmit - Send packet for nonpersistent association. Note that
3903 * neither the source or destination can be a broadcast address.
3907 struct recvbuf *rbufp, /* receive packet pointer */
3908 int xmode, /* receive mode */
3909 keyid_t xkeyid, /* transmit key ID */
3910 int flags /* restrict mask */
3913 struct pkt xpkt; /* transmit packet structure */
3914 struct pkt *rpkt; /* receive packet structure */
3915 l_fp xmt_tx, xmt_ty;
3922 * Initialize transmit packet header fields from the receive
3923 * buffer provided. We leave the fields intact as received, but
3924 * set the peer poll at the maximum of the receive peer poll and
3925 * the system minimum poll (ntp_minpoll). This is for KoD rate
3926 * control and not strictly specification compliant, but doesn't
3929 * If the gazinta was from a multicast address, the gazoutta
3930 * must go out another way.
3932 rpkt = &rbufp->recv_pkt;
3933 if (rbufp->dstadr->flags & INT_MCASTOPEN)
3934 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
3937 * If this is a kiss-o'-death (KoD) packet, show leap
3938 * unsynchronized, stratum zero, reference ID the four-character
3939 * kiss code and system root delay. Note we don't reveal the
3940 * local time, so these packets can't be used for
3943 if (flags & RES_KOD) {
3945 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
3946 PKT_VERSION(rpkt->li_vn_mode), xmode);
3947 xpkt.stratum = STRATUM_PKT_UNSPEC;
3948 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3949 xpkt.precision = rpkt->precision;
3950 memcpy(&xpkt.refid, "RATE", 4);
3951 xpkt.rootdelay = rpkt->rootdelay;
3952 xpkt.rootdisp = rpkt->rootdisp;
3953 xpkt.reftime = rpkt->reftime;
3954 xpkt.org = rpkt->xmt;
3955 xpkt.rec = rpkt->xmt;
3956 xpkt.xmt = rpkt->xmt;
3959 * This is a normal packet. Use the system variables.
3964 * Make copies of the variables which can be affected by smearing.
3967 l_fp this_recv_time;
3971 * If we are inside the leap smear interval we add the current smear offset to
3972 * the packet receive time, to the packet transmit time, and eventually to the
3973 * reftime to make sure the reftime isn't later than the transmit/receive times.
3975 xpkt.li_vn_mode = PKT_LI_VN_MODE(xmt_leap,
3976 PKT_VERSION(rpkt->li_vn_mode), xmode);
3978 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
3979 xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
3980 xpkt.precision = sys_precision;
3981 xpkt.refid = sys_refid;
3982 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
3983 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
3986 this_ref_time = sys_reftime;
3987 if (leap_smear.in_progress) {
3988 leap_smear_add_offs(&this_ref_time, NULL);
3989 xpkt.refid = convertLFPToRefID(leap_smear.offset);
3990 DPRINTF(2, ("fast_xmit: leap_smear.in_progress: refid %8x, smear %s\n",
3992 lfptoa(&leap_smear.offset, 8)
3995 HTONL_FP(&this_ref_time, &xpkt.reftime);
3997 HTONL_FP(&sys_reftime, &xpkt.reftime);
4000 xpkt.org = rpkt->xmt;
4003 this_recv_time = rbufp->recv_time;
4004 if (leap_smear.in_progress)
4005 leap_smear_add_offs(&this_recv_time, NULL);
4006 HTONL_FP(&this_recv_time, &xpkt.rec);
4008 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
4011 get_systime(&xmt_tx);
4013 if (leap_smear.in_progress)
4014 leap_smear_add_offs(&xmt_tx, &this_recv_time);
4016 HTONL_FP(&xmt_tx, &xpkt.xmt);
4019 #ifdef HAVE_NTP_SIGND
4020 if (flags & RES_MSSNTP) {
4021 send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
4024 #endif /* HAVE_NTP_SIGND */
4027 * If the received packet contains a MAC, the transmitted packet
4028 * is authenticated and contains a MAC. If not, the transmitted
4029 * packet is not authenticated.
4031 sendlen = LEN_PKT_NOMAC;
4032 if (rbufp->recv_length == sendlen) {
4033 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
4035 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d len %lu\n",
4036 current_time, stoa(&rbufp->dstadr->sin),
4037 stoa(&rbufp->recv_srcadr), xmode,
4043 * The received packet contains a MAC, so the transmitted packet
4044 * must be authenticated. For symmetric key cryptography, use
4045 * the predefined and trusted symmetric keys to generate the
4046 * cryptosum. For autokey cryptography, use the server private
4047 * value to generate the cookie, which is unique for every
4048 * source-destination-key ID combination.
4051 if (xkeyid > NTP_MAXKEY) {
4055 * The only way to get here is a reply to a legitimate
4056 * client request message, so the mode must be
4057 * MODE_SERVER. If an extension field is present, there
4058 * can be only one and that must be a command. Do what
4059 * needs, but with private value of zero so the poor
4060 * jerk can decode it. If no extension field is present,
4061 * use the cookie to generate the session key.
4063 cookie = session_key(&rbufp->recv_srcadr,
4064 &rbufp->dstadr->sin, 0, sys_private, 0);
4065 if ((size_t)rbufp->recv_length > sendlen + MAX_MAC_LEN) {
4066 session_key(&rbufp->dstadr->sin,
4067 &rbufp->recv_srcadr, xkeyid, 0, 2);
4068 temp32 = CRYPTO_RESP;
4069 rpkt->exten[0] |= htonl(temp32);
4070 sendlen += crypto_xmit(NULL, &xpkt, rbufp,
4071 sendlen, (struct exten *)rpkt->exten,
4074 session_key(&rbufp->dstadr->sin,
4075 &rbufp->recv_srcadr, xkeyid, cookie, 2);
4078 #endif /* AUTOKEY */
4079 get_systime(&xmt_tx);
4080 sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
4082 if (xkeyid > NTP_MAXKEY)
4083 authtrust(xkeyid, 0);
4084 #endif /* AUTOKEY */
4085 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
4086 get_systime(&xmt_ty);
4087 L_SUB(&xmt_ty, &xmt_tx);
4088 sys_authdelay = xmt_ty;
4089 DPRINTF(1, ("fast_xmit: at %ld %s->%s mode %d keyid %08x len %lu\n",
4090 current_time, ntoa(&rbufp->dstadr->sin),
4091 ntoa(&rbufp->recv_srcadr), xmode, xkeyid,
4097 * pool_xmit - resolve hostname or send unicast solicitation for pool.
4101 struct peer *pool /* pool solicitor association */
4105 struct pkt xpkt; /* transmit packet structure */
4106 struct addrinfo hints;
4108 struct interface * lcladr;
4109 sockaddr_u * rmtadr;
4114 if (NULL == pool->ai) {
4115 if (pool->addrs != NULL) {
4116 /* free() is used with copy_addrinfo_list() */
4121 hints.ai_family = AF(&pool->srcadr);
4122 hints.ai_socktype = SOCK_DGRAM;
4123 hints.ai_protocol = IPPROTO_UDP;
4124 /* ignore getaddrinfo_sometime() errors, we will retry */
4125 rc = getaddrinfo_sometime(
4130 &pool_name_resolved,
4131 (void *)(intptr_t)pool->associd);
4133 DPRINTF(1, ("pool DNS lookup %s started\n",
4137 "unable to start pool DNS %s: %m",
4143 /* copy_addrinfo_list ai_addr points to a sockaddr_u */
4144 rmtadr = (sockaddr_u *)(void *)pool->ai->ai_addr;
4145 pool->ai = pool->ai->ai_next;
4146 p = findexistingpeer(rmtadr, NULL, NULL, MODE_CLIENT, 0);
4147 } while (p != NULL && pool->ai != NULL);
4149 return; /* out of addresses, re-query DNS next poll */
4150 restrict_mask = restrictions(rmtadr);
4151 if (RES_FLAGS & restrict_mask)
4152 restrict_source(rmtadr, 0,
4153 current_time + POOL_SOLICIT_WINDOW + 1);
4154 lcladr = findinterface(rmtadr);
4155 memset(&xpkt, 0, sizeof(xpkt));
4156 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, pool->version,
4158 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
4159 xpkt.ppoll = pool->hpoll;
4160 xpkt.precision = sys_precision;
4161 xpkt.refid = sys_refid;
4162 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
4163 xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
4164 HTONL_FP(&sys_reftime, &xpkt.reftime);
4165 get_systime(&xmt_tx);
4166 pool->aorg = xmt_tx;
4167 HTONL_FP(&xmt_tx, &xpkt.xmt);
4168 sendpkt(rmtadr, lcladr, sys_ttl[pool->ttl], &xpkt,
4171 pool->throttle += (1 << pool->minpoll) - 2;
4172 DPRINTF(1, ("pool_xmit: at %ld %s->%s pool\n",
4173 current_time, latoa(lcladr), stoa(rmtadr)));
4174 msyslog(LOG_INFO, "Soliciting pool server %s", stoa(rmtadr));
4181 * group_test - test if this is the same group
4183 * host assoc return action
4184 * none none 0 mobilize *
4185 * none group 0 mobilize *
4186 * group none 0 mobilize *
4187 * group group 1 mobilize
4188 * group different 1 ignore
4189 * * ignore if notrust
4200 if (strcmp(grp, sys_groupname) == 0)
4206 if (strcmp(grp, ident) == 0)
4211 #endif /* AUTOKEY */
4221 const char * service,
4222 const struct addrinfo * hints,
4223 const struct addrinfo * res
4226 struct peer * pool; /* pool solicitor association */
4231 "error resolving pool %s: %s (%d)",
4232 name, gai_strerror(rescode), rescode);
4236 assoc = (associd_t)(intptr_t)context;
4237 pool = findpeerbyassoc(assoc);
4240 "Could not find assoc %u for pool DNS %s",
4244 DPRINTF(1, ("pool DNS %s completed\n", name));
4245 pool->addrs = copy_addrinfo_list(res);
4246 pool->ai = pool->addrs;
4255 * key_expire - purge the key list
4259 struct peer *peer /* peer structure pointer */
4264 if (peer->keylist != NULL) {
4265 for (i = 0; i <= peer->keynumber; i++)
4266 authtrust(peer->keylist[i], 0);
4267 free(peer->keylist);
4268 peer->keylist = NULL;
4270 value_free(&peer->sndval);
4271 peer->keynumber = 0;
4272 peer->flags &= ~FLAG_ASSOC;
4273 DPRINTF(1, ("key_expire: at %lu associd %d\n", current_time,
4276 #endif /* AUTOKEY */
4280 * local_refid(peer) - check peer refid to avoid selecting peers
4281 * currently synced to this ntpd.
4290 if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
4291 unicast_ep = p->dstadr;
4293 unicast_ep = findinterface(&p->srcadr);
4295 if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
4303 * Determine if the peer is unfit for synchronization
4305 * A peer is unfit for synchronization if
4306 * > TEST10 bad leap or stratum below floor or at or above ceiling
4307 * > TEST11 root distance exceeded for remote peer
4308 * > TEST12 a direct or indirect synchronization loop would form
4309 * > TEST13 unreachable or noselect
4311 int /* FALSE if fit, TRUE if unfit */
4313 struct peer *peer /* peer structure pointer */
4319 * A stratum error occurs if (1) the server has never been
4320 * synchronized, (2) the server stratum is below the floor or
4321 * greater than or equal to the ceiling.
4323 if ( peer->leap == LEAP_NOTINSYNC
4324 || peer->stratum < sys_floor
4325 || peer->stratum >= sys_ceiling)
4326 rval |= TEST10; /* bad synch or stratum */
4329 * A distance error for a remote peer occurs if the root
4330 * distance is greater than or equal to the distance threshold
4331 * plus the increment due to one host poll interval.
4333 if ( !(peer->flags & FLAG_REFCLOCK)
4334 && root_distance(peer) >= sys_maxdist
4335 + clock_phi * ULOGTOD(peer->hpoll))
4336 rval |= TEST11; /* distance exceeded */
4339 * A loop error occurs if the remote peer is synchronized to the
4340 * local peer or if the remote peer is synchronized to the same
4341 * server as the local peer but only if the remote peer is
4342 * neither a reference clock nor an orphan.
4344 if (peer->stratum > 1 && local_refid(peer))
4345 rval |= TEST12; /* synchronization loop */
4348 * An unreachable error occurs if the server is unreachable or
4349 * the noselect bit is set.
4351 if (!peer->reach || (peer->flags & FLAG_NOSELECT))
4352 rval |= TEST13; /* unreachable */
4354 peer->flash &= ~PEER_TEST_MASK;
4355 peer->flash |= rval;
4361 * Find the precision of this particular machine
4363 #define MINSTEP 20e-9 /* minimum clock increment (s) */
4364 #define MAXSTEP 1 /* maximum clock increment (s) */
4365 #define MINCHANGES 12 /* minimum number of step samples */
4366 #define MAXLOOPS ((int)(1. / MINSTEP)) /* avoid infinite loop */
4369 * This routine measures the system precision defined as the minimum of
4370 * a sequence of differences between successive readings of the system
4371 * clock. However, if a difference is less than MINSTEP, the clock has
4372 * been read more than once during a clock tick and the difference is
4373 * ignored. We set MINSTEP greater than zero in case something happens
4374 * like a cache miss, and to tolerate underlying system clocks which
4375 * ensure each reading is strictly greater than prior readings while
4376 * using an underlying stepping (not interpolated) clock.
4378 * sys_tick and sys_precision represent the time to read the clock for
4379 * systems with high-precision clocks, and the tick interval or step
4380 * size for lower-precision stepping clocks.
4382 * This routine also measures the time to read the clock on stepping
4383 * system clocks by counting the number of readings between changes of
4384 * the underlying clock. With either type of clock, the minimum time
4385 * to read the clock is saved as sys_fuzz, and used to ensure the
4386 * get_systime() readings always increase and are fuzzed below sys_fuzz.
4389 measure_precision(void)
4392 * With sys_fuzz set to zero, get_systime() fuzzing of low bits
4393 * is effectively disabled. trunc_os_clock is FALSE to disable
4394 * get_ostime() simulation of a low-precision system clock.
4397 trunc_os_clock = FALSE;
4398 measured_tick = measure_tick_fuzz();
4399 set_sys_tick_precision(measured_tick);
4400 msyslog(LOG_INFO, "proto: precision = %.3f usec (%d)",
4401 sys_tick * 1e6, sys_precision);
4402 if (sys_fuzz < sys_tick) {
4403 msyslog(LOG_NOTICE, "proto: fuzz beneath %.3f usec",
4410 * measure_tick_fuzz()
4412 * measures the minimum time to read the clock (stored in sys_fuzz)
4413 * and returns the tick, the larger of the minimum increment observed
4414 * between successive clock readings and the time to read the clock.
4417 measure_tick_fuzz(void)
4419 l_fp minstep; /* MINSTEP as l_fp */
4420 l_fp val; /* current seconds fraction */
4421 l_fp last; /* last seconds fraction */
4422 l_fp ldiff; /* val - last */
4423 double tick; /* computed tick value */
4428 int i; /* log2 precision */
4434 DTOLFP(MINSTEP, &minstep);
4436 for (i = 0; i < MAXLOOPS && changes < MINCHANGES; i++) {
4439 L_SUB(&ldiff, &last);
4441 if (L_ISGT(&ldiff, &minstep)) {
4442 max_repeats = max(repeats, max_repeats);
4445 LFPTOD(&ldiff, diff);
4446 tick = min(diff, tick);
4451 if (changes < MINCHANGES) {
4452 msyslog(LOG_ERR, "Fatal error: precision could not be measured (MINSTEP too large?)");
4456 if (0 == max_repeats) {
4459 set_sys_fuzz(tick / max_repeats);
4467 set_sys_tick_precision(
4475 "unsupported tick %.3f > 1s ignored", tick);
4478 if (tick < measured_tick) {
4480 "proto: tick %.3f less than measured tick %.3f, ignored",
4481 tick, measured_tick);
4483 } else if (tick > measured_tick) {
4484 trunc_os_clock = TRUE;
4486 "proto: truncating system clock to multiples of %.9f",
4492 * Find the nearest power of two.
4494 for (i = 0; tick <= 1; i--)
4496 if (tick - 1 > 1 - tick / 2)
4499 sys_precision = (s_char)i;
4504 * init_proto - initialize the protocol module's data
4513 * Fill in the sys_* stuff. Default is don't listen to
4514 * broadcasting, require authentication.
4516 set_sys_leap(LEAP_NOTINSYNC);
4517 sys_stratum = STRATUM_UNSPEC;
4518 memcpy(&sys_refid, "INIT", 4);
4522 L_CLR(&sys_reftime);
4524 measure_precision();
4525 get_systime(&dummy);
4527 sys_manycastserver = 0;
4529 sys_bdelay = BDELAY_DEFAULT; /*[Bug 3031] delay cutoff */
4530 sys_authenticate = 1;
4531 sys_stattime = current_time;
4532 orphwait = current_time + sys_orphwait;
4534 for (i = 0; i < MAX_TTL; i++) {
4535 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
4544 * proto_config - configure the protocol module
4555 * Figure out what he wants to change, then do it
4557 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
4558 item, value, dvalue));
4563 * enable and disable commands - arguments are Boolean.
4565 case PROTO_AUTHENTICATE: /* authentication (auth) */
4566 sys_authenticate = value;
4569 case PROTO_BROADCLIENT: /* broadcast client (bclient) */
4570 sys_bclient = (int)value;
4571 if (sys_bclient == 0)
4578 case PROTO_CAL: /* refclock calibrate (calibrate) */
4581 #endif /* REFCLOCK */
4583 case PROTO_KERNEL: /* kernel discipline (kernel) */
4587 case PROTO_MONITOR: /* monitoring (monitor) */
4593 msyslog(LOG_WARNING,
4594 "restrict: 'monitor' cannot be disabled while 'limited' is enabled");
4598 case PROTO_NTP: /* NTP discipline (ntp) */
4602 case PROTO_MODE7: /* mode7 management (ntpdc) */
4606 case PROTO_PPS: /* PPS discipline (pps) */
4607 hardpps_enable = value;
4610 case PROTO_FILEGEN: /* statistics (stats) */
4611 stats_control = value;
4615 * tos command - arguments are double, sometimes cast to int
4617 case PROTO_BEACON: /* manycast beacon (beacon) */
4618 sys_beacon = (int)dvalue;
4621 case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
4622 sys_bdelay = (dvalue ? dvalue : BDELAY_DEFAULT);
4625 case PROTO_CEILING: /* stratum ceiling (ceiling) */
4626 sys_ceiling = (int)dvalue;
4629 case PROTO_COHORT: /* cohort switch (cohort) */
4630 sys_cohort = (int)dvalue;
4633 case PROTO_FLOOR: /* stratum floor (floor) */
4634 sys_floor = (int)dvalue;
4637 case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
4638 sys_maxclock = (int)dvalue;
4641 case PROTO_MAXDIST: /* select threshold (maxdist) */
4642 sys_maxdist = dvalue;
4645 case PROTO_CALLDELAY: /* modem call delay (mdelay) */
4646 break; /* NOT USED */
4648 case PROTO_MINCLOCK: /* minimum candidates (minclock) */
4649 sys_minclock = (int)dvalue;
4652 case PROTO_MINDISP: /* minimum distance (mindist) */
4653 sys_mindisp = dvalue;
4656 case PROTO_MINSANE: /* minimum survivors (minsane) */
4657 sys_minsane = (int)dvalue;
4660 case PROTO_ORPHAN: /* orphan stratum (orphan) */
4661 sys_orphan = (int)dvalue;
4664 case PROTO_ORPHWAIT: /* orphan wait (orphwait) */
4665 orphwait -= sys_orphwait;
4666 sys_orphwait = (int)dvalue;
4667 orphwait += sys_orphwait;
4671 * Miscellaneous commands
4673 case PROTO_MULTICAST_ADD: /* add group address */
4675 io_multicast_add(svalue);
4679 case PROTO_MULTICAST_DEL: /* delete group address */
4681 io_multicast_del(svalue);
4685 * Unpeer Early policy choices
4688 case PROTO_UECRYPTO: /* Crypto */
4689 unpeer_crypto_early = value;
4692 case PROTO_UECRYPTONAK: /* Crypto_NAK */
4693 unpeer_crypto_nak_early = value;
4696 case PROTO_UEDIGEST: /* Digest */
4697 unpeer_digest_early = value;
4702 "proto: unsupported option %d", item);
4708 * proto_clr_stats - clear protocol stat counters
4711 proto_clr_stats(void)
4713 sys_stattime = current_time;
4722 sys_limitrejected = 0;