4 * ntp_proto.c - NTP version 4 protocol machinery
6 * ATTENTION: Get approval from Dave Mills on all changes to this file!
14 #include "ntp_stdlib.h"
15 #include "ntp_unixtime.h"
16 #include "ntp_control.h"
17 #include "ntp_string.h"
23 #endif /* HAVE_LIBSCF_H */
26 #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
27 #include "ntp_refclock.h"
31 * This macro defines the authentication state. If x is 1 authentication
32 * is required; othewise it is optional.
34 #define AUTH(x, y) ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
37 #define AUTH_NONE 0 /* authentication not required */
38 #define AUTH_OK 1 /* authentication OK */
39 #define AUTH_ERROR 2 /* authentication error */
40 #define AUTH_CRYPTO 3 /* crypto_NAK */
43 * traffic shaping parameters
45 #define NTP_IBURST 6 /* packets in iburst */
46 #define RESP_DELAY 1 /* refclock burst delay (s) */
49 * System variables are declared here. Unless specified otherwise, all
50 * times are in seconds.
52 u_char sys_leap
; /* system leap indicator */
53 u_char sys_stratum
; /* system stratum */
54 s_char sys_precision
; /* local clock precision (log2 s) */
55 double sys_rootdelay
; /* roundtrip delay to primary source */
56 double sys_rootdisp
; /* dispersion to primary source */
57 u_int32 sys_refid
; /* reference id (network byte order) */
58 l_fp sys_reftime
; /* last update time */
59 struct peer
*sys_peer
; /* current peer */
62 * Rate controls. Leaky buckets are used to throttle the packet
63 * transmission rates in order to protect busy servers such as at NIST
64 * and USNO. There is a counter for each association and another for KoD
65 * packets. The association counter decrements each second, but not
66 * below zero. Each time a packet is sent the counter is incremented by
67 * a configurable value representing the average interval between
68 * packets. A packet is delayed as long as the counter is greater than
69 * zero. Note this does not affect the time value computations.
72 * Nonspecified system state variables
74 int sys_bclient
; /* broadcast client enable */
75 double sys_bdelay
; /* broadcast client default delay */
76 int sys_authenticate
; /* requre authentication for config */
77 l_fp sys_authdelay
; /* authentication delay */
78 double sys_offset
; /* current local clock offset */
79 double sys_mindisp
= MINDISPERSE
; /* minimum distance (s) */
80 double sys_maxdist
= MAXDISTANCE
; /* selection threshold */
81 double sys_jitter
; /* system jitter */
82 u_long sys_epoch
; /* last clock update time */
83 static double sys_clockhop
; /* clockhop threshold */
84 int leap_tai
; /* TAI at next next leap */
85 u_long leap_sec
; /* next scheduled leap from file */
86 u_long leap_peers
; /* next scheduled leap from peers */
87 u_long leap_expire
; /* leap information expiration */
88 static int leap_vote
; /* leap consensus */
89 keyid_t sys_private
; /* private value for session seed */
90 int sys_manycastserver
; /* respond to manycast client pkts */
91 int peer_ntpdate
; /* active peers in ntpdate mode */
92 int sys_survivors
; /* truest of the truechimers */
95 * TOS and multicast mapping stuff
97 int sys_floor
= 0; /* cluster stratum floor */
98 int sys_ceiling
= STRATUM_UNSPEC
; /* cluster stratum ceiling */
99 int sys_minsane
= 1; /* minimum candidates */
100 int sys_minclock
= NTP_MINCLOCK
; /* minimum candidates */
101 int sys_maxclock
= NTP_MAXCLOCK
; /* maximum candidates */
102 int sys_cohort
= 0; /* cohort switch */
103 int sys_orphan
= STRATUM_UNSPEC
+ 1; /* orphan stratum */
104 int sys_beacon
= BEACON
; /* manycast beacon interval */
105 int sys_ttlmax
; /* max ttl mapping vector index */
106 u_char sys_ttl
[MAX_TTL
]; /* ttl mapping vector */
109 * Statistics counters - first the good, then the bad
111 u_long sys_stattime
; /* elapsed time */
112 u_long sys_received
; /* packets received */
113 u_long sys_processed
; /* packets for this host */
114 u_long sys_newversion
; /* current version */
115 u_long sys_oldversion
; /* old version */
116 u_long sys_restricted
; /* access denied */
117 u_long sys_badlength
; /* bad length or format */
118 u_long sys_badauth
; /* bad authentication */
119 u_long sys_declined
; /* declined */
120 u_long sys_limitrejected
; /* rate exceeded */
121 u_long sys_kodsent
; /* KoD sent */
123 static double root_distance (struct peer
*);
124 static void clock_combine (struct peer
**, int);
125 static void peer_xmit (struct peer
*);
126 static void fast_xmit (struct recvbuf
*, int, keyid_t
,
128 static void clock_update (struct peer
*);
129 static int default_get_precision (void);
130 static int peer_unfit (struct peer
*);
134 * transmit - transmit procedure called by poll timeout
138 struct peer
*peer
/* peer structure pointer */
144 * The polling state machine. There are two kinds of machines,
145 * those that never expect a reply (broadcast and manycast
146 * server modes) and those that do (all other modes). The dance
152 * In broadcast mode the poll interval is never changed from
155 if (peer
->cast_flags
& (MDF_BCAST
| MDF_MCAST
)) {
156 peer
->outdate
= current_time
;
157 if (sys_leap
!= LEAP_NOTINSYNC
)
159 poll_update(peer
, hpoll
);
164 * In manycast mode we start with unity ttl. The ttl is
165 * increased by one for each poll until either sys_maxclock
166 * servers have been found or the maximum ttl is reached. When
167 * sys_maxclock servers are found we stop polling until one or
168 * more servers have timed out or until less than minpoll
169 * associations turn up. In this case additional better servers
170 * are dragged in and preempt the existing ones.
172 if (peer
->cast_flags
& MDF_ACAST
) {
173 peer
->outdate
= current_time
;
174 if (peer
->unreach
> sys_beacon
) {
178 } else if (sys_survivors
< sys_minclock
||
179 peer_associations
< sys_maxclock
) {
180 if (peer
->ttl
< sys_ttlmax
)
185 poll_update(peer
, hpoll
);
190 * In unicast modes the dance is much more intricate. It is
191 * desigmed to back off whenever possible to minimize network
194 if (peer
->burst
== 0) {
198 * Update the reachability status. If not heard for
199 * three consecutive polls, stuff infinity in the clock
202 oreach
= peer
->reach
;
203 peer
->outdate
= current_time
;
206 if (!(peer
->reach
& 0x0f))
207 clock_filter(peer
, 0., 0., MAXDISPERSE
);
211 * Here the peer is unreachable. If it was
212 * previously reachable raise a trap. Send a
216 report_event(PEVNT_UNREACH
, peer
, NULL
);
217 if ((peer
->flags
& FLAG_IBURST
) &&
219 peer
->retry
= NTP_RETRY
;
223 * Here the peer is reachable. Send a burst if
224 * enabled and the peer is fit.
227 if (!(peer
->flags
& FLAG_PREEMPT
&&
228 peer
->hmode
== MODE_CLIENT
))
230 if ((peer
->flags
& FLAG_BURST
) && peer
->retry
==
231 0 && !peer_unfit(peer
))
232 peer
->retry
= NTP_RETRY
;
236 * Watch for timeout. If preemptable, toss the rascal;
237 * otherwise, bump the poll interval. Note the
238 * poll_update() routine will clamp it to maxpoll.
240 if (peer
->unreach
>= NTP_UNREACH
) {
242 if (peer
->flags
& FLAG_PREEMPT
) {
243 report_event(PEVNT_RESTART
, peer
,
245 if (peer
->hmode
!= MODE_CLIENT
) {
246 peer_clear(peer
, "TIME");
250 if (peer_associations
> sys_maxclock
&&
252 peer_clear(peer
, "TIME");
260 if (peer
->burst
== 0) {
263 * If ntpdate mode and the clock has not been
264 * set and all peers have completed the burst,
265 * we declare a successful failure.
269 if (peer_ntpdate
== 0) {
271 "ntpd: no servers found");
273 "ntpd: no servers found\n");
283 * Do not transmit if in broadcast client mode.
285 if (peer
->hmode
!= MODE_BCLIENT
)
287 poll_update(peer
, hpoll
);
292 * receive - receive procedure called for each packet received
296 struct recvbuf
*rbufp
299 register struct peer
*peer
; /* peer structure pointer */
300 register struct pkt
*pkt
; /* receive packet pointer */
301 int hisversion
; /* packet version */
302 int hisleap
; /* packet leap indicator */
303 int hismode
; /* packet mode */
304 int hisstratum
; /* packet stratum */
305 int restrict_mask
; /* restrict bits */
306 int has_mac
; /* length of MAC field */
307 int authlen
; /* offset of MAC field */
308 int is_authentic
= 0; /* cryptosum ok */
309 int retcode
= AM_NOMATCH
; /* match code */
310 keyid_t skeyid
= 0; /* key IDs */
311 u_int32 opcode
= 0; /* extension field opcode */
312 sockaddr_u
*dstadr_sin
; /* active runway */
313 struct peer
*peer2
; /* aux peer structure pointer */
314 l_fp p_org
; /* origin timestamp */
315 l_fp p_rec
; /* receive timestamp */
316 l_fp p_xmt
; /* transmit timestamp */
318 struct autokey
*ap
; /* autokey structure pointer */
319 int rval
; /* cookie snatcher */
320 keyid_t pkeyid
= 0, tkeyid
= 0; /* key IDs */
322 #ifdef HAVE_NTP_SIGND
323 static unsigned char zero_key
[16];
324 #endif /* HAVE_NTP_SIGND */
327 * Monitor the packet and get restrictions. Note that the packet
328 * length for control and private mode packets must be checked
329 * by the service routines. Some restrictions have to be handled
330 * later in order to generate a kiss-o'-death packet.
333 * Bogus port check is before anything, since it probably
334 * reveals a clogging attack.
337 if (SRCPORT(&rbufp
->recv_srcadr
) < NTP_PORT
) {
339 return; /* bogus port */
341 restrict_mask
= restrictions(&rbufp
->recv_srcadr
);
344 printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
345 current_time
, stoa(&rbufp
->dstadr
->sin
),
346 stoa(&rbufp
->recv_srcadr
),
347 rbufp
->dstadr
->flags
, restrict_mask
);
349 pkt
= &rbufp
->recv_pkt
;
350 hisversion
= PKT_VERSION(pkt
->li_vn_mode
);
351 hisleap
= PKT_LEAP(pkt
->li_vn_mode
);
352 hismode
= (int)PKT_MODE(pkt
->li_vn_mode
);
353 hisstratum
= PKT_TO_STRATUM(pkt
->stratum
);
354 if (restrict_mask
& RES_IGNORE
) {
356 return; /* ignore everything */
358 if (hismode
== MODE_PRIVATE
) {
359 if (restrict_mask
& RES_NOQUERY
) {
361 return; /* no query private */
363 process_private(rbufp
, ((restrict_mask
&
364 RES_NOMODIFY
) == 0));
367 if (hismode
== MODE_CONTROL
) {
368 if (restrict_mask
& RES_NOQUERY
) {
370 return; /* no query control */
372 process_control(rbufp
, restrict_mask
);
375 if (restrict_mask
& RES_DONTSERVE
) {
377 return; /* no time serve */
381 * This is for testing. If restricted drop ten percent of
384 if (restrict_mask
& RES_TIMEOUT
) {
385 if ((double)ntp_random() / 0x7fffffff < .1) {
387 return; /* no flakeway */
392 * Version check must be after the query packets, since they
393 * intentionally use an early version.
395 if (hisversion
== NTP_VERSION
) {
396 sys_newversion
++; /* new version */
397 } else if (!(restrict_mask
& RES_VERSION
) && hisversion
>=
399 sys_oldversion
++; /* previous version */
402 return; /* old version */
406 * Figure out his mode and validate the packet. This has some
407 * legacy raunch that probably should be removed. In very early
408 * NTP versions mode 0 was equivalent to what later versions
409 * would interpret as client mode.
411 if (hismode
== MODE_UNSPEC
) {
412 if (hisversion
== NTP_OLDVERSION
) {
413 hismode
= MODE_CLIENT
;
416 return; /* invalid mode */
421 * Parse the extension field if present. We figure out whether
422 * an extension field is present by measuring the MAC size. If
423 * the number of words following the packet header is 0, no MAC
424 * is present and the packet is not authenticated. If 1, the
425 * packet is a crypto-NAK; if 3, the packet is authenticated
426 * with DES; if 5, the packet is authenticated with MD5; if 6,
427 * the packet is authenticated with SHA. If 2 or * 4, the packet
428 * is a runt and discarded forthwith. If greater than 6, an
429 * extension field is present, so we subtract the length of the
430 * field and go around again.
432 authlen
= LEN_PKT_NOMAC
;
433 has_mac
= rbufp
->recv_length
- authlen
;
434 while (has_mac
!= 0) {
437 if (has_mac
% 4 != 0 || has_mac
< MIN_MAC_LEN
) {
439 return; /* bad length */
441 if (has_mac
<= MAX_MAC_LEN
) {
442 skeyid
= ntohl(((u_int32
*)pkt
)[authlen
/ 4]);
446 opcode
= ntohl(((u_int32
*)pkt
)[authlen
/ 4]);
447 len
= opcode
& 0xffff;
448 if (len
% 4 != 0 || len
< 4 || len
+ authlen
>
449 rbufp
->recv_length
) {
451 return; /* bad length */
459 * If authentication required, a MAC must be present.
461 if (restrict_mask
& RES_DONTTRUST
&& has_mac
== 0) {
463 return; /* access denied */
467 * Update the MRU list and finger the cloggers. It can be a
468 * little expensive, so turn it off for production use.
470 restrict_mask
= ntp_monitor(rbufp
, restrict_mask
);
471 if (restrict_mask
& RES_LIMITED
) {
473 if (!(restrict_mask
& RES_KOD
) || hismode
==
475 return; /* rate exceeded */
477 if (hismode
== MODE_CLIENT
)
478 fast_xmit(rbufp
, MODE_SERVER
, skeyid
,
481 fast_xmit(rbufp
, MODE_ACTIVE
, skeyid
,
483 return; /* rate exceeded */
485 restrict_mask
&= ~RES_KOD
;
488 * We have tossed out as many buggy packets as possible early in
489 * the game to reduce the exposure to a clogging attack. now we
490 * have to burn some cycles to find the association and
491 * authenticate the packet if required. Note that we burn only
492 * MD5 cycles, again to reduce exposure. There may be no
493 * matching association and that's okay.
495 * More on the autokey mambo. Normally the local interface is
496 * found when the association was mobilized with respect to a
497 * designated remote address. We assume packets arriving from
498 * the remote address arrive via this interface and the local
499 * address used to construct the autokey is the unicast address
500 * of the interface. However, if the sender is a broadcaster,
501 * the interface broadcast address is used instead.
502 * Notwithstanding this technobabble, if the sender is a
503 * multicaster, the broadcast address is null, so we use the
504 * unicast address anyway. Don't ask.
506 peer
= findpeer(&rbufp
->recv_srcadr
, rbufp
->dstadr
, hismode
,
508 dstadr_sin
= &rbufp
->dstadr
->sin
;
509 NTOHL_FP(&pkt
->org
, &p_org
);
510 NTOHL_FP(&pkt
->rec
, &p_rec
);
511 NTOHL_FP(&pkt
->xmt
, &p_xmt
);
514 * Authentication is conditioned by three switches:
516 * NOPEER (RES_NOPEER) do not mobilize an association unless
518 * NOTRUST (RES_DONTTRUST) do not allow access unless
519 * authenticated (implies NOPEER)
520 * enable (sys_authenticate) master NOPEER switch, by default
523 * The NOPEER and NOTRUST can be specified on a per-client basis
524 * using the restrict command. The enable switch if on implies
525 * NOPEER for all clients. There are four outcomes:
527 * NONE The packet has no MAC.
528 * OK the packet has a MAC and authentication succeeds
529 * ERROR the packet has a MAC and authentication fails
530 * CRYPTO crypto-NAK. The MAC has four octets only.
532 * Note: The AUTH(x, y) macro is used to filter outcomes. If x
533 * is zero, acceptable outcomes of y are NONE and OK. If x is
534 * one, the only acceptable outcome of y is OK.
538 restrict_mask
&= ~RES_MSSNTP
;
539 is_authentic
= AUTH_NONE
; /* not required */
543 "receive: at %ld %s<-%s mode %d len %d\n",
544 current_time
, stoa(dstadr_sin
),
545 stoa(&rbufp
->recv_srcadr
), hismode
,
548 } else if (has_mac
== 4) {
549 restrict_mask
&= ~RES_MSSNTP
;
550 is_authentic
= AUTH_CRYPTO
; /* crypto-NAK */
554 "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
555 current_time
, stoa(dstadr_sin
),
556 stoa(&rbufp
->recv_srcadr
), hismode
, skeyid
,
557 authlen
+ has_mac
, is_authentic
);
560 #ifdef HAVE_NTP_SIGND
562 * If the signature is 20 bytes long, the last 16 of
563 * which are zero, then this is a Microsoft client
564 * wanting AD-style authentication of the server's
567 * This is described in Microsoft's WSPP docs, in MS-SNTP:
568 * http://msdn.microsoft.com/en-us/library/cc212930.aspx
570 } else if (has_mac
== MAX_MD5_LEN
&& (restrict_mask
& RES_MSSNTP
) &&
571 (retcode
== AM_FXMIT
|| retcode
== AM_NEWPASS
) &&
572 (memcmp(zero_key
, (char *)pkt
+ authlen
+ 4, MAX_MD5_LEN
- 4) ==
574 is_authentic
= AUTH_NONE
;
575 #endif /* HAVE_NTP_SIGND */
578 restrict_mask
&= ~RES_MSSNTP
;
581 * For autokey modes, generate the session key
582 * and install in the key cache. Use the socket
583 * broadcast or unicast address as appropriate.
585 if (crypto_flags
&& skeyid
> NTP_MAXKEY
) {
588 * More on the autokey dance (AKD). A cookie is
589 * constructed from public and private values.
590 * For broadcast packets, the cookie is public
591 * (zero). For packets that match no
592 * association, the cookie is hashed from the
593 * addresses and private value. For server
594 * packets, the cookie was previously obtained
595 * from the server. For symmetric modes, the
596 * cookie was previously constructed using an
597 * agreement protocol; however, should PKI be
598 * unavailable, we construct a fake agreement as
599 * the EXOR of the peer and host cookies.
601 * hismode ephemeral persistent
602 * =======================================
605 * client sys cookie 0%
606 * server 0% sys cookie
612 if (has_mac
< MAX_MD5_LEN
) {
616 if (hismode
== MODE_BROADCAST
) {
619 * For broadcaster, use the interface
620 * broadcast address when available;
621 * otherwise, use the unicast address
622 * found when the association was
623 * mobilized. However, if this is from
624 * the wildcard interface, game over.
626 if (crypto_flags
&& rbufp
->dstadr
==
629 return; /* no wildcard */
632 if (!SOCK_UNSPEC(&rbufp
->dstadr
->bcast
))
634 &rbufp
->dstadr
->bcast
;
635 } else if (peer
== NULL
) {
636 pkeyid
= session_key(
637 &rbufp
->recv_srcadr
, dstadr_sin
, 0,
640 pkeyid
= peer
->pcookie
;
644 * The session key includes both the public
645 * values and cookie. In case of an extension
646 * field, the cookie used for authentication
647 * purposes is zero. Note the hash is saved for
648 * use later in the autokey mambo.
650 if (authlen
> LEN_PKT_NOMAC
&& pkeyid
!= 0) {
651 session_key(&rbufp
->recv_srcadr
,
652 dstadr_sin
, skeyid
, 0, 2);
653 tkeyid
= session_key(
654 &rbufp
->recv_srcadr
, dstadr_sin
,
657 tkeyid
= session_key(
658 &rbufp
->recv_srcadr
, dstadr_sin
,
666 * Compute the cryptosum. Note a clogging attack may
667 * succeed in bloating the key cache. If an autokey,
668 * purge it immediately, since we won't be needing it
669 * again. If the packet is authentic, it can mobilize an
670 * association. Note that there is no key zero.
672 if (!authdecrypt(skeyid
, (u_int32
*)pkt
, authlen
,
674 is_authentic
= AUTH_ERROR
;
676 is_authentic
= AUTH_OK
;
678 if (crypto_flags
&& skeyid
> NTP_MAXKEY
)
679 authtrust(skeyid
, 0);
684 "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
685 current_time
, stoa(dstadr_sin
),
686 stoa(&rbufp
->recv_srcadr
), hismode
, skeyid
,
687 authlen
+ has_mac
, is_authentic
);
692 * The association matching rules are implemented by a set of
693 * routines and an association table. A packet matching an
694 * association is processed by the peer process for that
695 * association. If there are no errors, an ephemeral association
696 * is mobilized: a broadcast packet mobilizes a broadcast client
697 * aassociation; a manycast server packet mobilizes a manycast
698 * client association; a symmetric active packet mobilizes a
699 * symmetric passive association.
704 * This is a client mode packet not matching any association. If
705 * an ordinary client, simply toss a server mode packet back
706 * over the fence. If a manycast client, we have to work a
712 * If authentication OK, send a server reply; otherwise,
715 if (!(rbufp
->dstadr
->flags
& INT_MCASTOPEN
)) {
716 if (AUTH(restrict_mask
& RES_DONTTRUST
,
718 fast_xmit(rbufp
, MODE_SERVER
, skeyid
,
720 } else if (is_authentic
== AUTH_ERROR
) {
721 fast_xmit(rbufp
, MODE_SERVER
, 0,
731 * This must be manycast. Do not respond if not
732 * configured as a manycast server.
734 if (!sys_manycastserver
) {
736 return; /* not enabled */
740 * Do not respond if we are not synchronized or our
741 * stratum is greater than the manycaster or the
742 * manycaster has already synchronized to us.
744 if (sys_leap
== LEAP_NOTINSYNC
|| sys_stratum
>=
745 hisstratum
|| (!sys_cohort
&& sys_stratum
==
746 hisstratum
+ 1) || rbufp
->dstadr
->addr_refid
==
749 return; /* no help */
753 * Respond only if authentication succeeds. Don't do a
754 * crypto-NAK, as that would not be useful.
756 if (AUTH(restrict_mask
& RES_DONTTRUST
, is_authentic
))
757 fast_xmit(rbufp
, MODE_SERVER
, skeyid
,
762 * This is a server mode packet returned in response to a client
763 * mode packet sent to a multicast group address. The origin
764 * timestamp is a good nonce to reliably associate the reply
765 * with what was sent. If there is no match, that's curious and
766 * could be an intruder attempting to clog, so we just ignore
769 * If the packet is authentic and the manycast association is
770 * found, we mobilize a client association and copy pertinent
771 * variables from the manycast association to the new client
772 * association. If not, just ignore the packet.
774 * There is an implosion hazard at the manycast client, since
775 * the manycast servers send the server packet immediately. If
776 * the guy is already here, don't fire up a duplicate.
779 if (!AUTH(sys_authenticate
| (restrict_mask
&
780 (RES_NOPEER
| RES_DONTTRUST
)), is_authentic
)) {
782 return; /* access denied */
786 * Do not respond if unsynchronized or stratum is below
787 * the floor or at or above the ceiling.
789 if (hisleap
== LEAP_NOTINSYNC
|| hisstratum
<
790 sys_floor
|| hisstratum
>= sys_ceiling
) {
792 return; /* no help */
794 if ((peer2
= findmanycastpeer(rbufp
)) == NULL
) {
796 return; /* not enabled */
798 if ((peer
= newpeer(&rbufp
->recv_srcadr
, rbufp
->dstadr
,
799 MODE_CLIENT
, hisversion
, NTP_MINDPOLL
, NTP_MAXDPOLL
,
800 FLAG_PREEMPT
, MDF_UCAST
| MDF_ACLNT
, 0, skeyid
)) ==
803 return; /* ignore duplicate */
807 * We don't need these, but it warms the billboards.
809 if (peer2
->flags
& FLAG_IBURST
)
810 peer
->flags
|= FLAG_IBURST
;
811 peer
->minpoll
= peer2
->minpoll
;
812 peer
->maxpoll
= peer2
->maxpoll
;
816 * This is the first packet received from a broadcast server. If
817 * the packet is authentic and we are enabled as broadcast
818 * client, mobilize a broadcast client association. We don't
819 * kiss any frogs here.
822 if (sys_bclient
== 0) {
824 return; /* not enabled */
826 if (!AUTH(sys_authenticate
| (restrict_mask
&
827 (RES_NOPEER
| RES_DONTTRUST
)), is_authentic
)) {
829 return; /* access denied */
833 * Do not respond if unsynchronized or stratum is below
834 * the floor or at or above the ceiling.
836 if (hisleap
== LEAP_NOTINSYNC
|| hisstratum
<
837 sys_floor
|| hisstratum
>= sys_ceiling
) {
839 return; /* no help */
844 * Do not respond if Autokey and the opcode is not a
845 * CRYPTO_ASSOC response with associationn ID.
847 if (crypto_flags
&& skeyid
> NTP_MAXKEY
&& (opcode
&
848 0xffff0000) != (CRYPTO_ASSOC
| CRYPTO_RESP
)) {
850 return; /* protocol error */
855 * Determine whether to execute the initial volley.
857 if (sys_bdelay
!= 0) {
860 * If a two-way exchange is not possible,
861 * neither is Autokey.
863 if (crypto_flags
&& skeyid
> NTP_MAXKEY
) {
865 return; /* no autokey */
870 * Do not execute the volley. Start out in
871 * broadcast client mode.
873 if ((peer
= newpeer(&rbufp
->recv_srcadr
,
874 rbufp
->dstadr
, MODE_BCLIENT
, hisversion
,
875 pkt
->ppoll
, pkt
->ppoll
, 0, 0, 0,
878 return; /* ignore duplicate */
881 peer
->delay
= sys_bdelay
;
882 peer
->bias
= -sys_bdelay
/ 2.;
888 * Execute the initial volley in order to calibrate the
889 * propagation delay and run the Autokey protocol.
891 * Note that the minpoll is taken from the broadcast
892 * packet, normally 6 (64 s) and that the poll interval
893 * is fixed at this value.
895 if ((peer
= newpeer(&rbufp
->recv_srcadr
, rbufp
->dstadr
,
896 MODE_CLIENT
, hisversion
, pkt
->ppoll
, pkt
->ppoll
,
897 FLAG_IBURST
| FLAG_PREEMPT
, MDF_BCLNT
, 0,
900 return; /* ignore duplicate */
903 if (skeyid
> NTP_MAXKEY
)
904 crypto_recv(peer
, rbufp
);
910 * This is the first packet received from a symmetric active
911 * peer. If the packet is authentic and the first he sent,
912 * mobilize a passive association. If not, kiss the frog.
915 if (!AUTH(sys_authenticate
| (restrict_mask
&
916 (RES_NOPEER
| RES_DONTTRUST
)), is_authentic
)) {
919 * If authenticated but cannot mobilize an
920 * association, send a symmetric passive
921 * response without mobilizing an association.
922 * This is for drat broken Windows clients. See
923 * Microsoft KB 875424 for preferred workaround.
925 if (AUTH(restrict_mask
& RES_DONTTRUST
,
927 fast_xmit(rbufp
, MODE_PASSIVE
, skeyid
,
931 if (is_authentic
== AUTH_ERROR
) {
932 fast_xmit(rbufp
, MODE_ACTIVE
, 0,
939 * Do not respond if synchronized and stratum is either
940 * below the floor or at or above the ceiling. Note,
941 * this allows an unsynchronized peer to synchronize to
942 * us. It would be very strange if he did and then was
943 * nipped, but that could only happen if we were
944 * operating at the top end of the range.
946 if (hisleap
!= LEAP_NOTINSYNC
&& (hisstratum
<
947 sys_floor
|| hisstratum
>= sys_ceiling
)) {
949 return; /* no help */
953 * The message is correctly authenticated and
954 * allowed. Mobiliae a symmetric passive association.
956 if ((peer
= newpeer(&rbufp
->recv_srcadr
,
957 rbufp
->dstadr
, MODE_PASSIVE
, hisversion
, pkt
->ppoll
,
958 NTP_MAXDPOLL
, FLAG_PREEMPT
, MDF_UCAST
, 0,
961 return; /* ignore duplicate */
967 * Process regular packet. Nothing special.
973 * A passive packet matches a passive association. This is
974 * usually the result of reconfiguring a client on the fly. As
975 * this association might be legitamate and this packet an
976 * attempt to deny service, just ignore it.
983 * For everything else there is the bit bucket.
992 * If the association is configured for Autokey, the packet must
993 * have a public key ID; if not, the packet must have a
996 if (is_authentic
!= AUTH_CRYPTO
&& (((peer
->flags
&
997 FLAG_SKEY
) && skeyid
<= NTP_MAXKEY
) || (!(peer
->flags
&
998 FLAG_SKEY
) && skeyid
> NTP_MAXKEY
))) {
1002 #endif /* OPENSSL */
1004 peer
->flash
&= ~PKT_TEST_MASK
;
1005 if (peer
->flags
& FLAG_XBOGUS
) {
1006 peer
->flags
&= ~FLAG_XBOGUS
;
1007 peer
->flash
|= TEST3
;
1011 * Next comes a rigorous schedule of timestamp checking. If the
1012 * transmit timestamp is zero, the server has not initialized in
1013 * interleaved modes or is horribly broken.
1015 if (L_ISZERO(&p_xmt
)) {
1016 peer
->flash
|= TEST3
; /* unsynch */
1019 * If the transmit timestamp duplicates a previous one, the
1020 * packet is a replay. This prevents the bad guys from replaying
1021 * the most recent packet, authenticated or not.
1023 } else if (L_ISEQU(&peer
->xmt
, &p_xmt
)) {
1024 peer
->flash
|= TEST1
; /* duplicate */
1029 * If this is a broadcast mode packet, skip further checking. If
1030 * an intial volley, bail out now and let the client do its
1031 * stuff. If the origin timestamp is nonzero, this is an
1032 * interleaved broadcast. so restart the protocol.
1034 } else if (hismode
== MODE_BROADCAST
) {
1035 if (!L_ISZERO(&p_org
) && !(peer
->flags
& FLAG_XB
)) {
1036 peer
->flags
|= FLAG_XB
;
1038 peer
->borg
= rbufp
->recv_time
;
1039 report_event(PEVNT_XLEAVE
, peer
, NULL
);
1044 * Check for bogus packet in basic mode. If found, switch to
1045 * interleaved mode and resynchronize, but only after confirming
1046 * the packet is not bogus in symmetric interleaved mode.
1048 } else if (peer
->flip
== 0) {
1049 if (!L_ISEQU(&p_org
, &peer
->aorg
)) {
1051 peer
->flash
|= TEST2
; /* bogus */
1052 if (!L_ISZERO(&peer
->dst
) && L_ISEQU(&p_org
,
1055 report_event(PEVNT_XLEAVE
, peer
, NULL
);
1062 * Check for valid nonzero timestamp fields.
1064 } else if (L_ISZERO(&p_org
) || L_ISZERO(&p_rec
) ||
1065 L_ISZERO(&peer
->dst
)) {
1066 peer
->flash
|= TEST3
; /* unsynch */
1069 * Check for bogus packet in interleaved symmetric mode. This
1070 * can happen if a packet is lost, duplicat or crossed. If
1071 * found, flip and resynchronize.
1073 } else if (!L_ISZERO(&peer
->dst
) && !L_ISEQU(&p_org
,
1076 peer
->flags
|= FLAG_XBOGUS
;
1077 peer
->flash
|= TEST2
; /* bogus */
1081 * Update the state variables.
1083 if (peer
->flip
== 0) {
1084 if (hismode
!= MODE_BROADCAST
)
1086 peer
->dst
= rbufp
->recv_time
;
1091 * If this is a crypto_NAK, the server cannot authenticate a
1092 * client packet. The server might have just changed keys. Clear
1093 * the association and restart the protocol.
1095 if (is_authentic
== AUTH_CRYPTO
) {
1096 report_event(PEVNT_AUTH
, peer
, "crypto_NAK");
1097 peer
->flash
|= TEST5
; /* bad auth */
1099 if (peer
->flags
& FLAG_PREEMPT
) {
1105 peer_clear(peer
, "AUTH");
1106 #endif /* OPENSSL */
1110 * If the digest fails, the client cannot authenticate a server
1111 * reply to a client packet previously sent. The loopback check
1112 * is designed to avoid a bait-and-switch attack, which was
1113 * possible in past versions. If symmetric modes, return a
1114 * crypto-NAK. The peer should restart the protocol.
1116 } else if (!AUTH(has_mac
|| (restrict_mask
& RES_DONTTRUST
),
1118 report_event(PEVNT_AUTH
, peer
, "digest");
1119 peer
->flash
|= TEST5
; /* bad auth */
1121 if (hismode
== MODE_ACTIVE
|| hismode
== MODE_PASSIVE
)
1122 fast_xmit(rbufp
, MODE_ACTIVE
, 0, restrict_mask
);
1123 if (peer
->flags
& FLAG_PREEMPT
) {
1129 peer_clear(peer
, "AUTH");
1130 #endif /* OPENSSL */
1135 * Set the peer ppoll to the maximum of the packet ppoll and the
1136 * peer minpoll. If a kiss-o'-death, set the peer minpoll to
1137 * this maximumn and advance the headway to give the sender some
1138 * headroom. Very intricate.
1140 peer
->ppoll
= max(peer
->minpoll
, pkt
->ppoll
);
1141 if (hismode
== MODE_SERVER
&& hisleap
== LEAP_NOTINSYNC
&&
1142 hisstratum
== STRATUM_UNSPEC
&& memcmp(&pkt
->refid
,
1145 report_event(PEVNT_RATE
, peer
, NULL
);
1146 if (pkt
->ppoll
> peer
->minpoll
)
1147 peer
->minpoll
= peer
->ppoll
;
1148 peer
->burst
= peer
->retry
= 0;
1149 peer
->throttle
= (NTP_SHIFT
+ 1) * (1 << peer
->minpoll
);
1150 poll_update(peer
, pkt
->ppoll
);
1151 return; /* kiss-o'-death */
1155 * That was hard and I am sweaty, but the packet is squeaky
1156 * clean. Get on with real work.
1158 peer
->timereceived
= current_time
;
1159 if (is_authentic
== AUTH_OK
)
1160 peer
->flags
|= FLAG_AUTHENTIC
;
1162 peer
->flags
&= ~FLAG_AUTHENTIC
;
1166 * More autokey dance. The rules of the cha-cha are as follows:
1168 * 1. If there is no key or the key is not auto, do nothing.
1170 * 2. If this packet is in response to the one just previously
1171 * sent or from a broadcast server, do the extension fields.
1172 * Otherwise, assume bogosity and bail out.
1174 * 3. If an extension field contains a verified signature, it is
1175 * self-authenticated and we sit the dance.
1177 * 4. If this is a server reply, check only to see that the
1178 * transmitted key ID matches the received key ID.
1180 * 5. Check to see that one or more hashes of the current key ID
1181 * matches the previous key ID or ultimate original key ID
1182 * obtained from the broadcaster or symmetric peer. If no
1183 * match, sit the dance and call for new autokey values.
1185 * In case of crypto error, fire the orchestra, stop dancing and
1186 * restart the protocol.
1188 if (peer
->flags
& FLAG_SKEY
) {
1190 * Decrement remaining audokey hashes. This isn't
1191 * perfect if a packet is lost, but results in no harm.
1193 ap
= (struct autokey
*)peer
->recval
.ptr
;
1198 peer
->flash
|= TEST8
;
1199 rval
= crypto_recv(peer
, rbufp
);
1200 if (rval
== XEVNT_OK
) {
1203 if (rval
== XEVNT_ERR
) {
1204 report_event(PEVNT_RESTART
, peer
,
1206 peer_clear(peer
, "CRYP");
1207 peer
->flash
|= TEST9
; /* bad crypt */
1208 if (peer
->flags
& FLAG_PREEMPT
)
1215 * If server mode, verify the receive key ID matches
1216 * the transmit key ID.
1218 if (hismode
== MODE_SERVER
) {
1219 if (skeyid
== peer
->keyid
)
1220 peer
->flash
&= ~TEST8
;
1223 * If an extension field is present, verify only that it
1224 * has been correctly signed. We don't need a sequence
1225 * check here, but the sequence continues.
1227 } else if (!(peer
->flash
& TEST8
)) {
1228 peer
->pkeyid
= skeyid
;
1231 * Now the fun part. Here, skeyid is the current ID in
1232 * the packet, pkeyid is the ID in the last packet and
1233 * tkeyid is the hash of skeyid. If the autokey values
1234 * have not been received, this is an automatic error.
1235 * If so, check that the tkeyid matches pkeyid. If not,
1236 * hash tkeyid and try again. If the number of hashes
1237 * exceeds the number remaining in the sequence, declare
1238 * a successful failure and refresh the autokey values.
1240 } else if (ap
!= NULL
) {
1243 for (i
= 0; ; i
++) {
1244 if (tkeyid
== peer
->pkeyid
||
1245 tkeyid
== ap
->key
) {
1246 peer
->flash
&= ~TEST8
;
1247 peer
->pkeyid
= skeyid
;
1256 tkeyid
= session_key(
1257 &rbufp
->recv_srcadr
, dstadr_sin
,
1260 if (peer
->flash
& TEST8
)
1261 report_event(PEVNT_AUTH
, peer
, "keylist");
1263 if (!(peer
->crypto
& CRYPTO_FLAG_PROV
)) /* test 9 */
1264 peer
->flash
|= TEST8
; /* bad autokey */
1267 * The maximum lifetime of the protocol is about one
1268 * week before restarting the Autokey protocol to
1269 * refreshed certificates and leapseconds values.
1271 if (current_time
> peer
->refresh
) {
1272 report_event(PEVNT_RESTART
, peer
,
1274 peer_clear(peer
, "TIME");
1278 #endif /* OPENSSL */
1281 * The dance is complete and the flash bits have been lit. Toss
1282 * the packet over the fence for processing, which may light up
1285 process_packet(peer
, pkt
, rbufp
->recv_length
);
1288 * In interleaved mode update the state variables. Also adjust the
1289 * transmit phase to avoid crossover.
1291 if (peer
->flip
!= 0) {
1293 peer
->dst
= rbufp
->recv_time
;
1294 if (peer
->nextdate
- current_time
< (1 << min(peer
->ppoll
,
1304 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1305 * specification. Or almost, at least. If we're in here we have a
1306 * reasonable expectation that we will be having a long term
1307 * relationship with this host.
1311 register struct peer
*peer
,
1312 register struct pkt
*pkt
,
1317 double p_offset
, p_del
, p_disp
;
1318 l_fp p_rec
, p_xmt
, p_org
, p_reftime
, ci
;
1319 u_char pmode
, pleap
, pstratum
;
1320 char statstr
[NTP_MAXSTRLEN
];
1323 double etemp
, ftemp
, td
;
1328 p_del
= FPTOD(NTOHS_FP(pkt
->rootdelay
));
1330 p_disp
= FPTOD(NTOHS_FP(pkt
->rootdisp
));
1331 NTOHL_FP(&pkt
->reftime
, &p_reftime
);
1332 NTOHL_FP(&pkt
->org
, &p_org
);
1333 NTOHL_FP(&pkt
->rec
, &p_rec
);
1334 NTOHL_FP(&pkt
->xmt
, &p_xmt
);
1335 pmode
= PKT_MODE(pkt
->li_vn_mode
);
1336 pleap
= PKT_LEAP(pkt
->li_vn_mode
);
1337 pstratum
= PKT_TO_STRATUM(pkt
->stratum
);
1340 * Capture the header values in the client/peer association..
1342 record_raw_stats(&peer
->srcadr
, peer
->dstadr
?
1343 &peer
->dstadr
->sin
: NULL
, &p_org
, &p_rec
, &p_xmt
,
1346 peer
->stratum
= min(pstratum
, STRATUM_UNSPEC
);
1347 peer
->pmode
= pmode
;
1348 peer
->precision
= pkt
->precision
;
1349 peer
->rootdelay
= p_del
;
1350 peer
->rootdisp
= p_disp
;
1351 peer
->refid
= pkt
->refid
; /* network byte order */
1352 peer
->reftime
= p_reftime
;
1355 * First, if either burst mode is armed, enable the burst.
1356 * Compute the headway for the next packet and delay if
1357 * necessary to avoid exceeding the threshold.
1359 if (peer
->retry
> 0) {
1362 peer
->burst
= min(1 << (peer
->hpoll
-
1363 peer
->minpoll
), NTP_SHIFT
) - 1;
1365 peer
->burst
= NTP_IBURST
- 1;
1366 if (peer
->burst
> 0)
1367 peer
->nextdate
= current_time
;
1369 poll_update(peer
, peer
->hpoll
);
1372 * Verify the server is synchronized; that is, the leap bits,
1373 * stratum and root distance are valid.
1375 if (pleap
== LEAP_NOTINSYNC
|| /* test 6 */
1376 pstratum
< sys_floor
|| pstratum
>= sys_ceiling
)
1377 peer
->flash
|= TEST6
; /* bad synch or strat */
1378 if (p_del
/ 2 + p_disp
>= MAXDISPERSE
) /* test 7 */
1379 peer
->flash
|= TEST7
; /* bad header */
1382 * If any tests fail at this point, the packet is discarded.
1383 * Note that some flashers may have already been set in the
1384 * receive() routine.
1386 if (peer
->flash
& PKT_TEST_MASK
) {
1387 peer
->seldisptoolarge
++;
1390 printf("packet: flash header %04x\n",
1397 * If the peer was previously unreachable, raise a trap. In any
1398 * case, mark it reachable.
1401 report_event(PEVNT_REACH
, peer
, NULL
);
1402 peer
->timereachable
= current_time
;
1407 * For a client/server association, calculate the clock offset,
1408 * roundtrip delay and dispersion. The equations are reordered
1409 * from the spec for more efficient use of temporaries. For a
1410 * broadcast association, offset the last measurement by the
1411 * computed delay during the client/server volley. Note the
1412 * computation of dispersion includes the system precision plus
1413 * that due to the frequency error since the origin time.
1415 * It is very important to respect the hazards of overflow. The
1416 * only permitted operation on raw timestamps is subtraction,
1417 * where the result is a signed quantity spanning from 68 years
1418 * in the past to 68 years in the future. To avoid loss of
1419 * precision, these calculations are done using 64-bit integer
1420 * arithmetic. However, the offset and delay calculations are
1421 * sums and differences of these first-order differences, which
1422 * if done using 64-bit integer arithmetic, would be valid over
1423 * only half that span. Since the typical first-order
1424 * differences are usually very small, they are converted to 64-
1425 * bit doubles and all remaining calculations done in floating-
1426 * double arithmetic. This preserves the accuracy while
1427 * retaining the 68-year span.
1429 * There are three interleaving schemes, basic, interleaved
1430 * symmetric and interleaved broadcast. The timestamps are
1431 * idioscyncratically different. See the onwire briefing/white
1432 * paper at www.eecis.udel.edu/~mills for details.
1434 * Interleaved symmetric mode
1435 * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
1438 if (peer
->flip
!= 0) {
1439 ci
= p_xmt
; /* t3 - t4 */
1440 L_SUB(&ci
, &peer
->dst
);
1442 ci
= p_rec
; /* t2 - t1 */
1444 L_SUB(&ci
, &peer
->borg
);
1446 L_SUB(&ci
, &peer
->aorg
);
1449 p_offset
= (t21
+ t34
) / 2.;
1450 if (p_del
< 0 || p_del
> 1.) {
1451 sprintf(statstr
, "t21 %.6f t34 %.6f", t21
, t34
);
1452 report_event(PEVNT_XERR
, peer
, statstr
);
1459 } else if (peer
->pmode
== MODE_BROADCAST
) {
1462 * Interleaved broadcast mode. Use interleaved timestamps.
1463 * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
1465 if (peer
->flags
& FLAG_XB
) {
1466 ci
= p_org
; /* delay */
1467 L_SUB(&ci
, &peer
->aorg
);
1469 ci
= p_org
; /* t2 - t1 */
1470 L_SUB(&ci
, &peer
->borg
);
1473 peer
->borg
= peer
->dst
;
1474 if (t34
< 0 || t34
> 1.) {
1476 "offset %.6f delay %.6f", t21
, t34
);
1477 report_event(PEVNT_XERR
, peer
, statstr
);
1484 * Basic broadcast - use direct timestamps.
1485 * t3 = p_xmt, t4 = peer->dst
1488 ci
= p_xmt
; /* t3 - t4 */
1489 L_SUB(&ci
, &peer
->dst
);
1495 * When calibration is complete and the clock is
1496 * synchronized, the bias is calculated as the difference
1497 * between the unicast timestamp and the broadcast
1498 * timestamp. This works for both basic and interleaved
1501 if (peer
->cast_flags
& MDF_BCLNT
) {
1502 peer
->cast_flags
&= ~MDF_BCLNT
;
1503 peer
->delay
= (peer
->offset
- p_offset
) * 2;
1505 p_del
= peer
->delay
;
1506 p_offset
+= p_del
/ 2;
1510 * Basic mode, otherwise known as the old fashioned way.
1512 * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
1515 ci
= p_xmt
; /* t3 - t4 */
1516 L_SUB(&ci
, &peer
->dst
);
1518 ci
= p_rec
; /* t2 - t1 */
1521 p_del
= fabs(t21
- t34
);
1522 p_offset
= (t21
+ t34
) / 2.;
1524 p_offset
+= peer
->bias
;
1525 p_disp
= LOGTOD(sys_precision
) + LOGTOD(peer
->precision
) +
1530 * This code calculates the outbound and inbound data rates by
1531 * measuring the differences between timestamps at different
1532 * packet lengths. This is helpful in cases of large asymmetric
1533 * delays commonly experienced on deep space communication
1536 if (peer
->t21_last
> 0 && peer
->t34_bytes
> 0) {
1537 itemp
= peer
->t21_bytes
- peer
->t21_last
;
1539 etemp
= t21
- peer
->t21
;
1540 if (fabs(etemp
) > 1e-6) {
1541 ftemp
= itemp
/ etemp
;
1546 itemp
= len
- peer
->t34_bytes
;
1548 etemp
= -t34
- peer
->t34
;
1549 if (fabs(etemp
) > 1e-6) {
1550 ftemp
= itemp
/ etemp
;
1558 * The following section compensates for different data rates on
1559 * the outbound (d21) and inbound (t34) directions. To do this,
1560 * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
1561 * the roundtrip delay. Then it calculates the correction as a
1565 peer
->t21_last
= peer
->t21_bytes
;
1567 peer
->t34_bytes
= len
;
1570 printf("packet: t21 %.9lf %d t34 %.9lf %d\n", peer
->t21
,
1571 peer
->t21_bytes
, peer
->t34
, peer
->t34_bytes
);
1573 if (peer
->r21
> 0 && peer
->r34
> 0 && p_del
> 0) {
1574 if (peer
->pmode
!= MODE_BROADCAST
)
1575 td
= (peer
->r34
/ (peer
->r21
+ peer
->r34
) -
1581 * Unfortunately, in many cases the errors are
1582 * unacceptable, so for the present the rates are not
1583 * used. In future, we might find conditions where the
1584 * calculations are useful, so this should be considered
1585 * a work in progress.
1591 printf("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
1592 p_del
, peer
->r21
/ 1e3
, peer
->r34
/ 1e3
,
1599 * That was awesome. Now hand off to the clock filter.
1601 clock_filter(peer
, p_offset
, p_del
, p_disp
);
1604 * If we are in broadcast calibrate mode, return to broadcast
1605 * client mode when the client is fit and the autokey dance is
1608 if ((peer
->cast_flags
& MDF_BCLNT
) && !(peer_unfit(peer
) &
1611 if (peer
->flags
& FLAG_SKEY
) {
1612 if (!(~peer
->crypto
& CRYPTO_FLAG_ALL
))
1613 peer
->hmode
= MODE_BCLIENT
;
1615 peer
->hmode
= MODE_BCLIENT
;
1618 peer
->hmode
= MODE_BCLIENT
;
1619 #endif /* OPENSSL */
1625 * clock_update - Called at system process update intervals.
1629 struct peer
*peer
/* peer structure pointer */
1634 #ifdef HAVE_LIBSCF_H
1636 #endif /* HAVE_LIBSCF_H */
1639 * Update the system state variables. We do this very carefully,
1640 * as the poll interval might need to be clamped differently.
1643 sys_epoch
= peer
->epoch
;
1644 if (sys_poll
< peer
->minpoll
)
1645 sys_poll
= peer
->minpoll
;
1646 if (sys_poll
> peer
->maxpoll
)
1647 sys_poll
= peer
->maxpoll
;
1648 poll_update(peer
, sys_poll
);
1649 sys_stratum
= min(peer
->stratum
+ 1, STRATUM_UNSPEC
);
1650 if (peer
->stratum
== STRATUM_REFCLOCK
||
1651 peer
->stratum
== STRATUM_UNSPEC
)
1652 sys_refid
= peer
->refid
;
1654 sys_refid
= addr2refid(&peer
->srcadr
);
1655 dtemp
= sys_jitter
+ fabs(sys_offset
) + peer
->disp
+ clock_phi
*
1656 (current_time
- peer
->update
);
1657 sys_rootdisp
= dtemp
+ peer
->rootdisp
;
1658 sys_rootdelay
= peer
->delay
+ peer
->rootdelay
;
1659 sys_reftime
= peer
->dst
;
1664 "clock_update: at %lu sample %lu associd %d\n",
1665 current_time
, peer
->epoch
, peer
->associd
);
1669 * Comes now the moment of truth. Crank the clock discipline and
1670 * see what comes out.
1672 switch (local_clock(peer
, sys_offset
)) {
1675 * Clock exceeds panic threshold. Life as we know it ends.
1678 #ifdef HAVE_LIBSCF_H
1680 * For Solaris enter the maintenance mode.
1682 if ((fmri
= getenv("SMF_FMRI")) != NULL
) {
1683 if (smf_maintain_instance(fmri
, 0) < 0) {
1684 printf("smf_maintain_instance: %s\n",
1685 scf_strerror(scf_error()));
1689 * Sleep until SMF kills us.
1694 #endif /* HAVE_LIBSCF_H */
1699 * Clock was stepped. Flush all time values of all peers.
1703 sys_leap
= LEAP_NOTINSYNC
;
1704 sys_stratum
= STRATUM_UNSPEC
;
1705 memcpy(&sys_refid
, "STEP", 4);
1708 L_CLR(&sys_reftime
);
1709 sys_jitter
= LOGTOD(sys_precision
);
1714 * Clock was slewed. Handle the leapsecond stuff.
1719 * If this is the first time the clock is set, reset the
1720 * leap bits. If crypto, the timer will goose the setup
1723 if (sys_leap
== LEAP_NOTINSYNC
) {
1724 sys_leap
= LEAP_NOWARNING
;
1728 #endif /* OPENSSL */
1732 * If the leapseconds values are from file or network
1733 * and the leap is in the future, schedule a leap at the
1734 * given epoch. Otherwise, if the number of survivor
1735 * leap bits is greater than half the number of
1736 * survivors, schedule a leap for the end of the current
1741 if (leap_sec
> now
.l_ui
) {
1742 sys_tai
= leap_tai
- 1;
1744 report_event(EVNT_ARMED
, NULL
,
1746 leapsec
= leap_sec
- now
.l_ui
;
1752 } else if (leap_vote
> sys_survivors
/ 2) {
1753 leap_peers
= now
.l_ui
+ leap_month(now
.l_ui
);
1754 if (leap_peers
> now
.l_ui
) {
1756 report_event(PEVNT_ARMED
, peer
,
1758 leapsec
= leap_peers
- now
.l_ui
;
1760 } else if (leapsec
> 0) {
1761 report_event(EVNT_DISARMED
, NULL
, NULL
);
1767 * Popcorn spike or step threshold exceeded. Pretend it never
1777 * poll_update - update peer poll interval
1781 struct peer
*peer
, /* peer structure pointer */
1789 * This routine figures out when the next poll should be sent.
1790 * That turns out to be wickedly complicated. One problem is
1791 * that sometimes the time for the next poll is in the past when
1792 * the poll interval is reduced. We watch out for races here
1793 * between the receive process and the poll process.
1795 * First, bracket the poll interval according to the type of
1796 * association and options. If a fixed interval is configured,
1797 * use minpoll. This primarily is for reference clocks, but
1798 * works for any association. Otherwise, clamp the poll interval
1799 * between minpoll and maxpoll.
1801 if (peer
->cast_flags
& MDF_BCLNT
)
1802 hpoll
= peer
->minpoll
;
1804 hpoll
= max(min(peer
->maxpoll
, mpoll
), peer
->minpoll
);
1808 * If during the crypto protocol the poll interval has changed,
1809 * the lifetimes in the key list are probably bogus. Purge the
1810 * the key list and regenerate it later.
1812 if ((peer
->flags
& FLAG_SKEY
) && hpoll
!= peer
->hpoll
)
1814 #endif /* OPENSSL */
1815 peer
->hpoll
= hpoll
;
1818 * There are three variables important for poll scheduling, the
1819 * current time (current_time), next scheduled time (nextdate)
1820 * and the earliest time (utemp). The earliest time is 2 s
1821 * seconds, but could be more due to rate management. When
1822 * sending in a burst, use the earliest time. When not in a
1823 * burst but with a reply pending, send at the earliest time
1824 * unless the next scheduled time has not advanced. This can
1825 * only happen if multiple replies are peinding in the same
1826 * response interval. Otherwise, send at the later of the next
1827 * scheduled time and the earliest time.
1829 * Now we figure out if there is an override. If a burst is in
1830 * progress and we get called from the receive process, just
1831 * slink away. If called from the poll process, delay 1 s for a
1832 * reference clock, otherwise 2 s.
1834 minpkt
= 1 << ntp_minpkt
;
1835 utemp
= current_time
+ max(peer
->throttle
- (NTP_SHIFT
- 1) *
1836 (1 << peer
->minpoll
), minpkt
);
1837 if (peer
->burst
> 0) {
1838 if (peer
->nextdate
> current_time
)
1841 else if (peer
->flags
& FLAG_REFCLOCK
)
1842 peer
->nextdate
= current_time
+ RESP_DELAY
;
1843 #endif /* REFCLOCK */
1845 peer
->nextdate
= utemp
;
1849 * If a burst is not in progress and a crypto response message
1850 * is pending, delay 2 s, but only if this is a new interval.
1852 } else if (peer
->cmmd
!= NULL
) {
1853 if (peer
->nextdate
> current_time
) {
1854 if (peer
->nextdate
+ minpkt
!= utemp
)
1855 peer
->nextdate
= utemp
;
1857 peer
->nextdate
= utemp
;
1859 #endif /* OPENSSL */
1862 * The ordinary case. If a retry, use minpoll; if unreachable,
1863 * use host poll; otherwise, use the minimum of host and peer
1864 * polls; In other words, oversampling is okay but
1865 * understampling is evil. Use the maximum of this value and the
1866 * headway. If the average headway is greater than the headway
1867 * threshold, increase the headway by the minimum interval.
1870 if (peer
->retry
> 0)
1871 hpoll
= peer
->minpoll
;
1872 else if (!(peer
->reach
))
1873 hpoll
= peer
->hpoll
;
1875 hpoll
= min(peer
->ppoll
, peer
->hpoll
);
1877 if (peer
->flags
& FLAG_REFCLOCK
)
1880 next
= ((0x1000UL
| (ntp_random() & 0x0ff)) <<
1882 #else /* REFCLOCK */
1883 next
= ((0x1000UL
| (ntp_random() & 0x0ff)) << hpoll
) >>
1885 #endif /* REFCLOCK */
1886 next
+= peer
->outdate
;
1888 peer
->nextdate
= next
;
1890 peer
->nextdate
= utemp
;
1891 hpoll
= peer
->throttle
- (1 << peer
->minpoll
);
1893 peer
->nextdate
+= minpkt
;
1897 printf("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
1898 current_time
, ntoa(&peer
->srcadr
), peer
->hpoll
,
1899 peer
->burst
, peer
->retry
, peer
->throttle
,
1900 utemp
- current_time
, peer
->nextdate
-
1907 * peer_clear - clear peer filter registers. See Section 3.4.8 of the
1912 struct peer
*peer
, /* peer structure */
1913 char *ident
/* tally lights */
1920 * If cryptographic credentials have been acquired, toss them to
1921 * Valhalla. Note that autokeys are ephemeral, in that they are
1922 * tossed immediately upon use. Therefore, the keylist can be
1923 * purged anytime without needing to preserve random keys. Note
1924 * that, if the peer is purged, the cryptographic variables are
1925 * purged, too. This makes it much harder to sneak in some
1926 * unauthenticated data in the clock filter.
1929 if (peer
->iffval
!= NULL
)
1930 BN_free(peer
->iffval
);
1931 value_free(&peer
->cookval
);
1932 value_free(&peer
->recval
);
1933 value_free(&peer
->encrypt
);
1934 value_free(&peer
->sndval
);
1935 if (peer
->cmmd
!= NULL
)
1937 if (peer
->subject
!= NULL
)
1938 free(peer
->subject
);
1939 if (peer
->issuer
!= NULL
)
1941 #endif /* OPENSSL */
1944 * Clear all values, including the optional crypto values above.
1946 memset(CLEAR_TO_ZERO(peer
), 0, LEN_CLEAR_TO_ZERO
);
1947 peer
->ppoll
= peer
->maxpoll
;
1948 peer
->hpoll
= peer
->minpoll
;
1949 peer
->disp
= MAXDISPERSE
;
1950 peer
->flash
= peer_unfit(peer
);
1951 peer
->jitter
= LOGTOD(sys_precision
);
1954 * If interleave mode, initialize the alternate origin switch.
1956 if (peer
->flags
& FLAG_XLEAVE
)
1958 for (i
= 0; i
< NTP_SHIFT
; i
++) {
1959 peer
->filter_order
[i
] = i
;
1960 peer
->filter_disp
[i
] = MAXDISPERSE
;
1963 if (!(peer
->flags
& FLAG_REFCLOCK
)) {
1964 peer
->leap
= LEAP_NOTINSYNC
;
1965 peer
->stratum
= STRATUM_UNSPEC
;
1966 memcpy(&peer
->refid
, ident
, 4);
1969 peer
->leap
= LEAP_NOTINSYNC
;
1970 peer
->stratum
= STRATUM_UNSPEC
;
1971 memcpy(&peer
->refid
, ident
, 4);
1972 #endif /* REFCLOCK */
1975 * During initialization use the association count to spread out
1976 * the polls at one-second intervals. Otherwise, randomize over
1977 * the minimum poll interval in order to avoid broadcast
1980 peer
->nextdate
= peer
->update
= peer
->outdate
= current_time
;
1982 peer
->nextdate
+= peer_associations
;
1983 } else if (peer
->hmode
== MODE_PASSIVE
) {
1984 peer
->nextdate
+= 1 << ntp_minpkt
;
1986 peer
->nextdate
+= ntp_random() % peer_associations
;
1989 peer
->refresh
= current_time
+ (1 << NTP_REFRESH
);
1990 #endif /* OPENSSL */
1994 "peer_clear: at %ld next %ld associd %d refid %s\n",
1995 current_time
, peer
->nextdate
, peer
->associd
,
2002 * clock_filter - add incoming clock sample to filter register and run
2003 * the filter procedure to find the best sample.
2007 struct peer
*peer
, /* peer structure pointer */
2008 double sample_offset
, /* clock offset */
2009 double sample_delay
, /* roundtrip delay */
2010 double sample_disp
/* dispersion */
2013 double dst
[NTP_SHIFT
]; /* distance vector */
2014 int ord
[NTP_SHIFT
]; /* index vector */
2016 double dtemp
, etemp
;
2020 * A sample consists of the offset, delay, dispersion and epoch
2021 * of arrival. The offset and delay are determined by the on-
2022 * wire protcol. The dispersion grows from the last outbound
2023 * packet to the arrival of this one increased by the sum of the
2024 * peer precision and the system precision as required by the
2025 * error budget. First, shift the new arrival into the shift
2026 * register discarding the oldest one.
2028 j
= peer
->filter_nextpt
;
2029 peer
->filter_offset
[j
] = sample_offset
;
2030 peer
->filter_delay
[j
] = sample_delay
;
2031 peer
->filter_disp
[j
] = sample_disp
;
2032 peer
->filter_epoch
[j
] = current_time
;
2033 j
= (j
+ 1) % NTP_SHIFT
;
2034 peer
->filter_nextpt
= j
;
2037 * Update dispersions since the last update and at the same
2038 * time initialize the distance and index lists. Since samples
2039 * become increasingly uncorrelated beyond the Allan intercept,
2040 * only under exceptional cases will an older sample be used.
2041 * Therefore, the distance list uses a compound metric. If the
2042 * dispersion is greater than the maximum dispersion, clamp the
2043 * distance at that value. If the time since the last update is
2044 * less than the Allan intercept use the delay; otherwise, use
2045 * the sum of the delay and dispersion.
2047 dtemp
= clock_phi
* (current_time
- peer
->update
);
2048 peer
->update
= current_time
;
2049 for (i
= NTP_SHIFT
- 1; i
>= 0; i
--) {
2051 peer
->filter_disp
[j
] += dtemp
;
2052 if (peer
->filter_disp
[j
] >= MAXDISPERSE
) {
2053 peer
->filter_disp
[j
] = MAXDISPERSE
;
2054 dst
[i
] = MAXDISPERSE
;
2055 } else if (peer
->update
- peer
->filter_epoch
[j
] >
2056 ULOGTOD(allan_xpt
)) {
2057 dst
[i
] = peer
->filter_delay
[j
] +
2058 peer
->filter_disp
[j
];
2060 dst
[i
] = peer
->filter_delay
[j
];
2063 j
= (j
+ 1) % NTP_SHIFT
;
2067 * If the clock discipline has stabilized, sort the samples by
2070 if (sys_leap
!= LEAP_NOTINSYNC
) {
2071 for (i
= 1; i
< NTP_SHIFT
; i
++) {
2072 for (j
= 0; j
< i
; j
++) {
2073 if (dst
[j
] > dst
[i
]) {
2086 * Copy the index list to the association structure so ntpq
2087 * can see it later. Prune the distance list to leave only
2088 * samples less than the maximum dispersion, which disfavors
2089 * uncorrelated samples older than the Allan intercept. To
2090 * further improve the jitter estimate, of the remainder leave
2091 * only samples less than the maximum distance, but keep at
2092 * least two samples for jitter calculation.
2095 for (i
= 0; i
< NTP_SHIFT
; i
++) {
2096 peer
->filter_order
[i
] = (u_char
) ord
[i
];
2097 if (dst
[i
] >= MAXDISPERSE
|| (m
>= 2 && dst
[i
] >=
2104 * Compute the dispersion and jitter. The dispersion is weighted
2105 * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
2106 * to 1.0. The jitter is the RMS differences relative to the
2107 * lowest delay sample.
2109 peer
->disp
= peer
->jitter
= 0;
2111 for (i
= NTP_SHIFT
- 1; i
>= 0; i
--) {
2113 peer
->disp
= NTP_FWEIGHT
* (peer
->disp
+
2114 peer
->filter_disp
[j
]);
2116 peer
->jitter
+= DIFF(peer
->filter_offset
[j
],
2117 peer
->filter_offset
[k
]);
2121 * If no acceptable samples remain in the shift register,
2122 * quietly tiptoe home leaving only the dispersion. Otherwise,
2123 * save the offset, delay and jitter. Note the jitter must not
2124 * be less than the precision.
2129 etemp
= fabs(peer
->offset
- peer
->filter_offset
[k
]);
2130 peer
->offset
= peer
->filter_offset
[k
];
2131 peer
->delay
= peer
->filter_delay
[k
];
2133 peer
->jitter
/= m
- 1;
2134 peer
->jitter
= max(SQRT(peer
->jitter
), LOGTOD(sys_precision
));
2137 * If the the new sample and the current sample are both valid
2138 * and the difference between their offsets exceeds CLOCK_SGATE
2139 * (3) times the jitter and the interval between them is less
2140 * than twice the host poll interval, consider the new sample
2141 * a popcorn spike and ignore it.
2143 if (peer
->disp
< sys_maxdist
&& peer
->filter_disp
[k
] <
2144 sys_maxdist
&& etemp
> CLOCK_SGATE
* peer
->jitter
&&
2145 peer
->filter_epoch
[k
] - peer
->epoch
< 2. *
2146 ULOGTOD(peer
->hpoll
)) {
2147 snprintf(tbuf
, sizeof(tbuf
), "%.6f s", etemp
);
2148 report_event(PEVNT_POPCORN
, peer
, tbuf
);
2153 * A new minimum sample is useful only if it is later than the
2154 * last one used. In this design the maximum lifetime of any
2155 * sample is not greater than eight times the poll interval, so
2156 * the maximum interval between minimum samples is eight
2159 if (peer
->filter_epoch
[k
] <= peer
->epoch
) {
2162 printf("clock_filter: old sample %lu\n", current_time
-
2163 peer
->filter_epoch
[k
]);
2167 peer
->epoch
= peer
->filter_epoch
[k
];
2170 * The mitigated sample statistics are saved for later
2171 * processing. If not synchronized or not in a burst, tickle the
2172 * clock select algorithm.
2174 record_peer_stats(&peer
->srcadr
, ctlpeerstatus(peer
),
2175 peer
->offset
, peer
->delay
, peer
->disp
, peer
->jitter
);
2179 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
2180 m
, peer
->offset
, peer
->delay
, peer
->disp
,
2183 if (peer
->burst
== 0 || sys_leap
== LEAP_NOTINSYNC
)
2189 * clock_select - find the pick-of-the-litter clock
2191 * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
2192 * be enabled, even if declared falseticker, (2) only the prefer peer
2193 * caN Be selected as the system peer, (3) if the external source is
2194 * down, the system leap bits are set to 11 and the stratum set to
2207 double synch
[NTP_MAXASSOC
], error
[NTP_MAXASSOC
];
2208 double orphdist
= 1e10
;
2209 struct peer
*osys_peer
= NULL
;
2210 struct peer
*sys_prefer
= NULL
; /* prefer peer */
2211 struct peer
*typesystem
= NULL
;
2212 struct peer
*typeorphan
= NULL
;
2214 struct peer
*typeacts
= NULL
;
2215 struct peer
*typelocal
= NULL
;
2216 struct peer
*typepps
= NULL
;
2217 #endif /* REFCLOCK */
2219 static int list_alloc
= 0;
2220 static struct endpoint
*endpoint
= NULL
;
2221 static int *indx
= NULL
;
2222 static struct peer
**peer_list
= NULL
;
2223 static u_int endpoint_size
= 0;
2224 static u_int indx_size
= 0;
2225 static u_int peer_list_size
= 0;
2228 * Initialize and create endpoint, index and peer lists big
2229 * enough to handle all associations.
2231 osys_peer
= sys_peer
;
2232 osurv
= sys_survivors
;
2235 sys_leap
= LEAP_NOTINSYNC
;
2236 sys_stratum
= STRATUM_UNSPEC
;
2237 memcpy(&sys_refid
, "DOWN", 4);
2238 #endif /* LOCKCLOCK */
2240 for (n
= 0; n
< NTP_HASH_SIZE
; n
++)
2241 nlist
+= peer_hash_count
[n
];
2242 if (nlist
> list_alloc
) {
2243 if (list_alloc
> 0) {
2248 while (list_alloc
< nlist
) {
2250 endpoint_size
+= 5 * 3 * sizeof(*endpoint
);
2251 indx_size
+= 5 * 3 * sizeof(*indx
);
2252 peer_list_size
+= 5 * sizeof(*peer_list
);
2254 endpoint
= (struct endpoint
*)emalloc(endpoint_size
);
2255 indx
= (int *)emalloc(indx_size
);
2256 peer_list
= (struct peer
**)emalloc(peer_list_size
);
2260 * Initially, we populate the island with all the rifraff peers
2261 * that happen to be lying around. Those with seriously
2262 * defective clocks are immediately booted off the island. Then,
2263 * the falsetickers are culled and put to sea. The truechimers
2264 * remaining are subject to repeated rounds where the most
2265 * unpopular at each round is kicked off. When the population
2266 * has dwindled to sys_minclock, the survivors split a million
2267 * bucks and collectively crank the chimes.
2269 nlist
= nl3
= 0; /* none yet */
2270 for (n
= 0; n
< NTP_HASH_SIZE
; n
++) {
2271 for (peer
= peer_hash
[n
]; peer
!= NULL
; peer
=
2273 peer
->flags
&= ~FLAG_SYSPEER
;
2274 peer
->status
= CTL_PST_SEL_REJECT
;
2277 * Leave the island immediately if the peer is
2278 * unfit to synchronize.
2280 if (peer_unfit(peer
))
2284 * If this is an orphan, choose the one with
2285 * the lowest metric defined as the IPv4 address
2286 * or the first 64 bits of the hashed IPv6 address.
2288 if (peer
->stratum
== sys_orphan
) {
2291 ftemp
= addr2refid(&peer
->srcadr
);
2292 if (ftemp
< orphdist
) {
2300 * The following are special cases. We deal
2303 switch (peer
->refclktype
) {
2304 case REFCLK_LOCALCLOCK
:
2305 if (typelocal
== NULL
&&
2306 !(peer
->flags
& FLAG_PREFER
))
2311 if (typeacts
== NULL
&&
2312 !(peer
->flags
& FLAG_PREFER
))
2316 #endif /* REFCLOCK */
2319 * If we get this far, the peer can stay on the
2320 * island, but does not yet have the immunity
2323 peer
->status
= CTL_PST_SEL_SANE
;
2324 peer_list
[nlist
++] = peer
;
2327 * Insert each interval endpoint on the sorted
2330 e
= peer
->offset
; /* Upper end */
2331 f
= root_distance(peer
);
2333 for (i
= nl3
- 1; i
>= 0; i
--) {
2334 if (e
>= endpoint
[indx
[i
]].val
)
2337 indx
[i
+ 3] = indx
[i
];
2340 endpoint
[nl3
].type
= 1;
2341 endpoint
[nl3
++].val
= e
;
2343 e
= e
- f
; /* Center point */
2344 for (; i
>= 0; i
--) {
2345 if (e
>= endpoint
[indx
[i
]].val
)
2348 indx
[i
+ 2] = indx
[i
];
2351 endpoint
[nl3
].type
= 0;
2352 endpoint
[nl3
++].val
= e
;
2354 e
= e
- f
; /* Lower end */
2355 for (; i
>= 0; i
--) {
2356 if (e
>= endpoint
[indx
[i
]].val
)
2359 indx
[i
+ 1] = indx
[i
];
2362 endpoint
[nl3
].type
= -1;
2363 endpoint
[nl3
++].val
= e
;
2368 for (i
= 0; i
< nl3
; i
++)
2369 printf("select: endpoint %2d %.6f\n",
2370 endpoint
[indx
[i
]].type
,
2371 endpoint
[indx
[i
]].val
);
2374 * This is the actual algorithm that cleaves the truechimers
2375 * from the falsetickers. The original algorithm was described
2376 * in Keith Marzullo's dissertation, but has been modified for
2379 * Briefly put, we first assume there are no falsetickers, then
2380 * scan the candidate list first from the low end upwards and
2381 * then from the high end downwards. The scans stop when the
2382 * number of intersections equals the number of candidates less
2383 * the number of falsetickers. If this doesn't happen for a
2384 * given number of falsetickers, we bump the number of
2385 * falsetickers and try again. If the number of falsetickers
2386 * becomes equal to or greater than half the number of
2387 * candidates, the Albanians have won the Byzantine wars and
2388 * correct synchronization is not possible.
2390 * Here, nlist is the number of candidates and allow is the
2391 * number of falsetickers. Upon exit, the truechimers are the
2392 * susvivors with offsets not less than low and not greater than
2393 * high. There may be none of them.
2397 for (allow
= 0; 2 * allow
< nlist
; allow
++) {
2401 * Bound the interval (low, high) as the largest
2402 * interval containing points from presumed truechimers.
2406 for (i
= 0; i
< nl3
; i
++) {
2407 low
= endpoint
[indx
[i
]].val
;
2408 n
-= endpoint
[indx
[i
]].type
;
2409 if (n
>= nlist
- allow
)
2411 if (endpoint
[indx
[i
]].type
== 0)
2415 for (j
= nl3
- 1; j
>= 0; j
--) {
2416 high
= endpoint
[indx
[j
]].val
;
2417 n
+= endpoint
[indx
[j
]].type
;
2418 if (n
>= nlist
- allow
)
2420 if (endpoint
[indx
[j
]].type
== 0)
2425 * If the number of candidates found outside the
2426 * interval is greater than the number of falsetickers,
2427 * then at least one truechimer is outside the interval,
2428 * so go around again. This is what makes this algorithm
2429 * different than Marzullo's.
2435 * If an interval containing truechimers is found, stop.
2436 * If not, increase the number of falsetickers and go
2444 * Clustering algorithm. Construct candidate list in order first
2445 * by stratum then by root distance, but keep only the best
2446 * NTP_MAXASSOC of them. Scan the list to find falsetickers, who
2447 * leave the island immediately. The TRUE peer is always a
2448 * truechimer. We must leave at least one peer to collect the
2452 for (i
= 0; i
< nlist
; i
++) {
2453 peer
= peer_list
[i
];
2454 if (nlist
> 1 && (peer
->offset
<= low
|| peer
->offset
>=
2455 high
) && !(peer
->flags
& FLAG_TRUE
))
2460 * Elegible PPS peers must survive the intersection
2461 * algorithm. Use the first one found, but don't
2462 * include any of them in the cluster population.
2464 if (peer
->flags
& FLAG_PPS
) {
2465 if (typepps
== NULL
)
2469 #endif /* REFCLOCK */
2472 * The metric is the scaled root distance at the next
2473 * poll interval plus the peer stratum.
2475 d
= (root_distance(peer
) + clock_phi
* (peer
->nextdate
-
2476 current_time
)) / sys_maxdist
+ peer
->stratum
;
2477 if (j
>= NTP_MAXASSOC
) {
2478 if (d
>= synch
[j
- 1])
2483 for (k
= j
; k
> 0; k
--) {
2484 if (d
>= synch
[k
- 1])
2487 peer_list
[k
] = peer_list
[k
- 1];
2488 error
[k
] = error
[k
- 1];
2489 synch
[k
] = synch
[k
- 1];
2491 peer_list
[k
] = peer
;
2492 error
[k
] = peer
->jitter
;
2499 * If no survivors remain at this point, check if the modem
2500 * driver, local driver or orphan parent in that order. If so,
2501 * nominate the first one found as the only survivor.
2502 * Otherwise, give up and leave the island to the rats.
2508 if (typeacts
!= NULL
) {
2509 peer_list
[0] = typeacts
;
2511 } else if (typelocal
!= NULL
) {
2512 peer_list
[0] = typelocal
;
2515 #endif /* REFCLOCK */
2516 if (typeorphan
!= NULL
) {
2517 peer_list
[0] = typeorphan
;
2523 * Mark the candidates at this point as truechimers.
2525 for (i
= 0; i
< nlist
; i
++) {
2526 peer_list
[i
]->status
= CTL_PST_SEL_SELCAND
;
2529 printf("select: survivor %s %f\n",
2530 stoa(&peer_list
[i
]->srcadr
), synch
[i
]);
2535 * Now, vote outlyers off the island by select jitter weighted
2536 * by root distance. Continue voting as long as there are more
2537 * than sys_minclock survivors and the minimum select jitter is
2538 * greater than the maximum peer jitter. Stop if we are about to
2539 * discard a TRUE or PREFER peer, who of course has the
2548 for (i
= 0; i
< nlist
; i
++) {
2553 for (j
= 0; j
< nlist
; j
++)
2554 f
+= DIFF(peer_list
[j
]->offset
,
2555 peer_list
[i
]->offset
);
2556 f
= SQRT(f
/ (nlist
- 1));
2558 if (f
* synch
[i
] > e
) {
2564 f
= max(f
, LOGTOD(sys_precision
));
2565 if (nlist
<= sys_minsane
|| nlist
<= sys_minclock
) {
2568 } else if (f
<= d
|| peer_list
[k
]->flags
&
2569 (FLAG_TRUE
| FLAG_PREFER
)) {
2576 "select: drop %s seljit %.6f jit %.6f\n",
2577 ntoa(&peer_list
[k
]->srcadr
), g
, d
);
2579 if (nlist
> sys_maxclock
)
2580 peer_list
[k
]->status
= CTL_PST_SEL_EXCESS
;
2581 for (j
= k
+ 1; j
< nlist
; j
++) {
2582 peer_list
[j
- 1] = peer_list
[j
];
2583 synch
[j
- 1] = synch
[j
];
2584 error
[j
- 1] = error
[j
];
2590 * What remains is a list usually not greater than sys_minclock
2591 * peers. Note that the head of the list is the system peer at
2592 * the lowest stratum and that unsynchronized peers cannot
2595 * While at it, count the number of leap warning bits found.
2596 * This will be used later to vote the system leap warning bit.
2597 * If a leap warning bit is found on a reference clock, the vote
2601 for (i
= 0; i
< nlist
; i
++) {
2602 peer
= peer_list
[i
];
2604 peer
->status
= CTL_PST_SEL_SYNCCAND
;
2606 if (peer
->leap
== LEAP_ADDSECOND
) {
2607 if (peer
->flags
& FLAG_REFCLOCK
)
2612 if (peer
->flags
& FLAG_PREFER
)
2617 * Unless there are at least sys_misane survivors, leave the
2618 * building dark. Otherwise, do a clockhop dance. Ordinarily,
2619 * use the first survivor on the survivor list. However, if the
2620 * last selection is not first on the list, use it as long as
2621 * it doesn't get too old or too ugly.
2623 if (nlist
> 0 && nlist
>= sys_minsane
) {
2626 typesystem
= peer_list
[0];
2627 if (osys_peer
== NULL
|| osys_peer
== typesystem
) {
2629 } else if ((x
= fabs(typesystem
->offset
-
2630 osys_peer
->offset
)) < sys_mindisp
) {
2631 if (sys_clockhop
== 0)
2632 sys_clockhop
= sys_mindisp
;
2637 printf("select: clockhop %d %.6f %.6f\n",
2638 j
, x
, sys_clockhop
);
2640 if (fabs(x
) < sys_clockhop
)
2641 typesystem
= osys_peer
;
2650 * Mitigation rules of the game. We have the pick of the
2651 * litter in typesystem if any survivors are left. If
2652 * there is a prefer peer, use its offset and jitter.
2653 * Otherwise, use the combined offset and jitter of all kitters.
2655 if (typesystem
!= NULL
) {
2656 if (sys_prefer
== NULL
) {
2657 typesystem
->status
= CTL_PST_SEL_SYSPEER
;
2658 clock_combine(peer_list
, sys_survivors
);
2659 sys_jitter
= SQRT(SQUARE(typesystem
->jitter
) +
2660 SQUARE(sys_jitter
) + SQUARE(seljitter
));
2662 typesystem
= sys_prefer
;
2664 typesystem
->status
= CTL_PST_SEL_SYSPEER
;
2665 sys_offset
= typesystem
->offset
;
2666 sys_jitter
= typesystem
->jitter
;
2670 printf("select: combine offset %.9f jitter %.9f\n",
2671 sys_offset
, sys_jitter
);
2676 * If a PPS driver is lit and the combined offset is less than
2677 * 0.4 s, select the driver as the PPS peer and use its offset
2678 * and jitter. However, if this is the atom driver, use it only
2679 * if there is a prefer peer or there are no survivors and none
2682 if (typepps
!= NULL
&& fabs(sys_offset
< 0.4) &&
2683 (typepps
->refclktype
!= REFCLK_ATOM_PPS
||
2684 (typepps
->refclktype
== REFCLK_ATOM_PPS
&& (sys_prefer
!=
2685 NULL
|| (typesystem
== NULL
&& sys_minsane
== 0))))) {
2686 typesystem
= typepps
;
2688 typesystem
->status
= CTL_PST_SEL_PPS
;
2689 sys_offset
= typesystem
->offset
;
2690 sys_jitter
= typesystem
->jitter
;
2693 printf("select: pps offset %.9f jitter %.9f\n",
2694 sys_offset
, sys_jitter
);
2697 #endif /* REFCLOCK */
2700 * If there are no survivors at this point, there is no
2701 * system peer. If so and this is an old update, keep the
2702 * current statistics, but do not update the clock.
2704 if (typesystem
== NULL
) {
2705 if (osys_peer
!= NULL
)
2706 report_event(EVNT_NOPEER
, NULL
, NULL
);
2712 * Do not use old data, as this may mess up the clock discipline
2715 if (typesystem
->epoch
<= sys_epoch
)
2719 * We have found the alpha male. Wind the clock.
2721 if (osys_peer
!= typesystem
)
2722 report_event(PEVNT_NEWPEER
, typesystem
, NULL
);
2723 typesystem
->flags
|= FLAG_SYSPEER
;
2724 clock_update(typesystem
);
2729 * clock_combine - compute system offset and jitter from selected peers
2733 struct peer
**peers
, /* survivor list */
2734 int npeers
/* number of survivors */
2741 for (i
= 0; i
< npeers
; i
++) {
2742 x
= root_distance(peers
[i
]);
2744 z
+= peers
[i
]->offset
/ x
;
2745 w
+= SQUARE(peers
[i
]->offset
- peers
[0]->offset
) / x
;
2748 sys_jitter
= SQRT(w
/ y
);
2753 * root_distance - compute synchronization distance from peer to root
2757 struct peer
*peer
/* peer structure pointer */
2763 * Careful squeak here. The value returned must be greater than
2764 * the minimum root dispersion in order to avoid clockhop with
2765 * highly precise reference clocks. Note that the root distance
2766 * cannot exceed the sys_maxdist, as this is the cutoff by the
2767 * selection algorithm.
2769 dtemp
= (peer
->delay
+ peer
->rootdelay
) / 2 + peer
->disp
+
2770 peer
->rootdisp
+ clock_phi
* (current_time
- peer
->update
) +
2772 if (dtemp
< sys_mindisp
)
2773 dtemp
= sys_mindisp
;
2779 * peer_xmit - send packet for persistent association.
2783 struct peer
*peer
/* peer structure pointer */
2786 struct pkt xpkt
; /* transmit packet */
2787 int sendlen
, authlen
;
2788 keyid_t xkeyid
= 0; /* transmit key ID */
2789 l_fp xmt_tx
, xmt_ty
;
2791 if (!peer
->dstadr
) /* drop peers without interface */
2794 xpkt
.li_vn_mode
= PKT_LI_VN_MODE(sys_leap
, peer
->version
,
2796 xpkt
.stratum
= STRATUM_TO_PKT(sys_stratum
);
2797 xpkt
.ppoll
= peer
->hpoll
;
2798 xpkt
.precision
= sys_precision
;
2799 xpkt
.refid
= sys_refid
;
2800 xpkt
.rootdelay
= HTONS_FP(DTOFP(sys_rootdelay
));
2801 xpkt
.rootdisp
= HTONS_FP(DTOUFP(sys_rootdisp
));
2802 HTONL_FP(&sys_reftime
, &xpkt
.reftime
);
2803 HTONL_FP(&peer
->rec
, &xpkt
.org
);
2804 HTONL_FP(&peer
->dst
, &xpkt
.rec
);
2807 * If the received packet contains a MAC, the transmitted packet
2808 * is authenticated and contains a MAC. If not, the transmitted
2809 * packet is not authenticated.
2811 * It is most important when autokey is in use that the local
2812 * interface IP address be known before the first packet is
2813 * sent. Otherwise, it is not possible to compute a correct MAC
2814 * the recipient will accept. Thus, the I/O semantics have to do
2815 * a little more work. In particular, the wildcard interface
2816 * might not be usable.
2818 sendlen
= LEN_PKT_NOMAC
;
2820 if (!(peer
->flags
& FLAG_SKEY
) && peer
->keyid
== 0) {
2822 if (peer
->keyid
== 0) {
2823 #endif /* OPENSSL */
2826 * Transmit a-priori timestamps
2828 get_systime(&xmt_tx
);
2829 if (peer
->flip
== 0) { /* basic mode */
2830 peer
->aorg
= xmt_tx
;
2831 HTONL_FP(&xmt_tx
, &xpkt
.xmt
);
2832 } else { /* interleaved modes */
2833 if (peer
->hmode
== MODE_BROADCAST
) { /* bcst */
2834 HTONL_FP(&xmt_tx
, &xpkt
.xmt
);
2836 HTONL_FP(&peer
->borg
,
2839 HTONL_FP(&peer
->aorg
,
2841 } else { /* symmetric */
2843 HTONL_FP(&peer
->borg
,
2846 HTONL_FP(&peer
->aorg
,
2850 peer
->t21_bytes
= sendlen
;
2851 sendpkt(&peer
->srcadr
, peer
->dstadr
, sys_ttl
[peer
->ttl
],
2854 peer
->throttle
+= (1 << peer
->minpoll
) - 2;
2857 * Capture a-posteriori timestamps
2859 get_systime(&xmt_ty
);
2860 if (peer
->flip
!= 0) { /* interleaved modes */
2862 peer
->aorg
= xmt_ty
;
2864 peer
->borg
= xmt_ty
;
2865 peer
->flip
= -peer
->flip
;
2867 L_SUB(&xmt_ty
, &xmt_tx
);
2868 LFPTOD(&xmt_ty
, peer
->xleave
);
2871 printf("transmit: at %ld %s->%s mode %d len %d\n",
2872 current_time
, peer
->dstadr
?
2873 stoa(&peer
->dstadr
->sin
) : "-",
2874 stoa(&peer
->srcadr
), peer
->hmode
, sendlen
);
2880 * Authentication is enabled, so the transmitted packet must be
2881 * authenticated. If autokey is enabled, fuss with the various
2882 * modes; otherwise, symmetric key cryptography is used.
2885 if (peer
->flags
& FLAG_SKEY
) {
2886 struct exten
*exten
; /* extension field */
2889 * The Public Key Dance (PKD): Cryptographic credentials
2890 * are contained in extension fields, each including a
2891 * 4-octet length/code word followed by a 4-octet
2892 * association ID and optional additional data. Optional
2893 * data includes a 4-octet data length field followed by
2894 * the data itself. Request messages are sent from a
2895 * configured association; response messages can be sent
2896 * from a configured association or can take the fast
2897 * path without ever matching an association. Response
2898 * messages have the same code as the request, but have
2899 * a response bit and possibly an error bit set. In this
2900 * implementation, a message may contain no more than
2901 * one command and one or more responses.
2903 * Cryptographic session keys include both a public and
2904 * a private componet. Request and response messages
2905 * using extension fields are always sent with the
2906 * private component set to zero. Packets without
2907 * extension fields indlude the private component when
2908 * the session key is generated.
2913 * Allocate and initialize a keylist if not
2914 * already done. Then, use the list in inverse
2915 * order, discarding keys once used. Keep the
2916 * latest key around until the next one, so
2917 * clients can use client/server packets to
2918 * compute propagation delay.
2920 * Note that once a key is used from the list,
2921 * it is retained in the key cache until the
2922 * next key is used. This is to allow a client
2923 * to retrieve the encrypted session key
2924 * identifier to verify authenticity.
2926 * If for some reason a key is no longer in the
2927 * key cache, a birthday has happened or the key
2928 * has expired, so the pseudo-random sequence is
2929 * broken. In that case, purge the keylist and
2932 if (peer
->keynumber
== 0)
2933 make_keylist(peer
, peer
->dstadr
);
2936 xkeyid
= peer
->keylist
[peer
->keynumber
];
2937 if (authistrusted(xkeyid
))
2942 peer
->keyid
= xkeyid
;
2944 switch (peer
->hmode
) {
2947 * In broadcast server mode the autokey values are
2948 * required by the broadcast clients. Push them when a
2949 * new keylist is generated; otherwise, push the
2950 * association message so the client can request them at
2953 case MODE_BROADCAST
:
2954 if (peer
->flags
& FLAG_ASSOC
)
2955 exten
= crypto_args(peer
, CRYPTO_AUTO
|
2956 CRYPTO_RESP
, peer
->associd
, NULL
);
2958 exten
= crypto_args(peer
, CRYPTO_ASSOC
|
2959 CRYPTO_RESP
, peer
->associd
, NULL
);
2963 * In symmetric modes the parameter, certificate,
2964 * identity, cookie and autokey exchanges are
2965 * required. The leapsecond exchange is optional. But, a
2966 * peer will not believe the other peer until the other
2967 * peer has synchronized, so the certificate exchange
2968 * might loop until then. If a peer finds a broken
2969 * autokey sequence, it uses the autokey exchange to
2970 * retrieve the autokey values. In any case, if a new
2971 * keylist is generated, the autokey values are pushed.
2977 * Parameter, certificate and identity.
2980 exten
= crypto_args(peer
, CRYPTO_ASSOC
,
2981 peer
->associd
, sys_hostname
);
2982 else if (!(peer
->crypto
& CRYPTO_FLAG_CERT
))
2983 exten
= crypto_args(peer
, CRYPTO_CERT
,
2984 peer
->associd
, peer
->issuer
);
2985 else if (!(peer
->crypto
& CRYPTO_FLAG_VRFY
))
2986 exten
= crypto_args(peer
,
2987 crypto_ident(peer
), peer
->associd
,
2991 * Cookie and autokey. We request the cookie
2992 * only when the this peer and the other peer
2993 * are synchronized. But, this peer needs the
2994 * autokey values when the cookie is zero. Any
2995 * time we regenerate the key list, we offer the
2996 * autokey values without being asked. If for
2997 * some reason either peer finds a broken
2998 * autokey sequence, the autokey exchange is
2999 * used to retrieve the autokey values.
3001 else if (sys_leap
!= LEAP_NOTINSYNC
&&
3002 peer
->leap
!= LEAP_NOTINSYNC
&&
3003 !(peer
->crypto
& CRYPTO_FLAG_COOK
))
3004 exten
= crypto_args(peer
, CRYPTO_COOK
,
3005 peer
->associd
, NULL
);
3006 else if (!(peer
->crypto
& CRYPTO_FLAG_AUTO
))
3007 exten
= crypto_args(peer
, CRYPTO_AUTO
,
3008 peer
->associd
, NULL
);
3009 else if (peer
->flags
& FLAG_ASSOC
&&
3010 peer
->crypto
& CRYPTO_FLAG_SIGN
)
3011 exten
= crypto_args(peer
, CRYPTO_AUTO
|
3012 CRYPTO_RESP
, peer
->assoc
, NULL
);
3015 * Wait for clock sync, then sign the
3016 * certificate and retrieve the leapsecond
3019 else if (sys_leap
== LEAP_NOTINSYNC
)
3022 else if (!(peer
->crypto
& CRYPTO_FLAG_SIGN
))
3023 exten
= crypto_args(peer
, CRYPTO_SIGN
,
3024 peer
->associd
, sys_hostname
);
3025 else if (!(peer
->crypto
& CRYPTO_FLAG_LEAP
))
3026 exten
= crypto_args(peer
, CRYPTO_LEAP
,
3027 peer
->associd
, NULL
);
3031 * In client mode the parameter, certificate, identity,
3032 * cookie and sign exchanges are required. The
3033 * leapsecond exchange is optional. If broadcast client
3034 * mode the same exchanges are required, except that the
3035 * autokey exchange is substitutes for the cookie
3036 * exchange, since the cookie is always zero. If the
3037 * broadcast client finds a broken autokey sequence, it
3038 * uses the autokey exchange to retrieve the autokey
3044 * Parameter, certificate and identity.
3047 exten
= crypto_args(peer
, CRYPTO_ASSOC
,
3048 peer
->associd
, sys_hostname
);
3049 else if (!(peer
->crypto
& CRYPTO_FLAG_CERT
))
3050 exten
= crypto_args(peer
, CRYPTO_CERT
,
3051 peer
->associd
, peer
->issuer
);
3052 else if (!(peer
->crypto
& CRYPTO_FLAG_VRFY
))
3053 exten
= crypto_args(peer
,
3054 crypto_ident(peer
), peer
->associd
,
3058 * Cookie and autokey. These are requests, but
3059 * we use the peer association ID with autokey
3060 * rather than our own.
3062 else if (!(peer
->crypto
& CRYPTO_FLAG_COOK
))
3063 exten
= crypto_args(peer
, CRYPTO_COOK
,
3064 peer
->associd
, NULL
);
3065 else if (!(peer
->crypto
& CRYPTO_FLAG_AUTO
))
3066 exten
= crypto_args(peer
, CRYPTO_AUTO
,
3070 * Wait for clock sync, then sign the
3071 * certificate and retrieve the leapsecond
3074 else if (sys_leap
== LEAP_NOTINSYNC
)
3077 else if (!(peer
->crypto
& CRYPTO_FLAG_SIGN
))
3078 exten
= crypto_args(peer
, CRYPTO_SIGN
,
3079 peer
->associd
, sys_hostname
);
3080 else if (!(peer
->crypto
& CRYPTO_FLAG_LEAP
))
3081 exten
= crypto_args(peer
, CRYPTO_LEAP
,
3082 peer
->associd
, NULL
);
3087 * Add a queued extension field if present. This is
3088 * always a request message, so the reply ID is already
3089 * in the message. If an error occurs, the error bit is
3090 * lit in the response.
3092 if (peer
->cmmd
!= NULL
) {
3095 temp32
= CRYPTO_RESP
;
3096 peer
->cmmd
->opcode
|= htonl(temp32
);
3097 sendlen
+= crypto_xmit(peer
, &xpkt
, NULL
,
3098 sendlen
, peer
->cmmd
, 0);
3104 * Add an extension field created above. All but the
3105 * autokey response message are request messages.
3107 if (exten
!= NULL
) {
3108 if (exten
->opcode
!= 0)
3109 sendlen
+= crypto_xmit(peer
, &xpkt
,
3110 NULL
, sendlen
, exten
, 0);
3115 * Calculate the next session key. Since extension
3116 * fields are present, the cookie value is zero.
3118 if (sendlen
> LEN_PKT_NOMAC
) {
3119 session_key(&peer
->dstadr
->sin
, &peer
->srcadr
,
3123 #endif /* OPENSSL */
3126 * Transmit a-priori timestamps
3128 get_systime(&xmt_tx
);
3129 if (peer
->flip
== 0) { /* basic mode */
3130 peer
->aorg
= xmt_tx
;
3131 HTONL_FP(&xmt_tx
, &xpkt
.xmt
);
3132 } else { /* interleaved modes */
3133 if (peer
->hmode
== MODE_BROADCAST
) { /* bcst */
3134 HTONL_FP(&xmt_tx
, &xpkt
.xmt
);
3136 HTONL_FP(&peer
->borg
, &xpkt
.org
);
3138 HTONL_FP(&peer
->aorg
, &xpkt
.org
);
3139 } else { /* symmetric */
3141 HTONL_FP(&peer
->borg
, &xpkt
.xmt
);
3143 HTONL_FP(&peer
->aorg
, &xpkt
.xmt
);
3146 xkeyid
= peer
->keyid
;
3147 authlen
= authencrypt(xkeyid
, (u_int32
*)&xpkt
, sendlen
);
3149 report_event(PEVNT_AUTH
, peer
, "no key");
3150 peer
->flash
|= TEST5
; /* auth error */
3156 if (xkeyid
> NTP_MAXKEY
)
3157 authtrust(xkeyid
, 0);
3158 #endif /* OPENSSL */
3159 if (sendlen
> sizeof(xpkt
)) {
3160 msyslog(LOG_ERR
, "proto: buffer overflow %u", sendlen
);
3163 peer
->t21_bytes
= sendlen
;
3164 sendpkt(&peer
->srcadr
, peer
->dstadr
, sys_ttl
[peer
->ttl
], &xpkt
,
3167 peer
->throttle
+= (1 << peer
->minpoll
) - 2;
3170 * Capture a-posteriori timestamps
3172 get_systime(&xmt_ty
);
3173 if (peer
->flip
!= 0) { /* interleaved modes */
3175 peer
->aorg
= xmt_ty
;
3177 peer
->borg
= xmt_ty
;
3178 peer
->flip
= -peer
->flip
;
3180 L_SUB(&xmt_ty
, &xmt_tx
);
3181 LFPTOD(&xmt_ty
, peer
->xleave
);
3185 printf("transmit: at %ld %s->%s mode %d keyid %08x len %d index %d\n",
3186 current_time
, peer
->dstadr
?
3187 ntoa(&peer
->dstadr
->sin
) : "-",
3188 ntoa(&peer
->srcadr
), peer
->hmode
, xkeyid
, sendlen
,
3194 printf("transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3195 current_time
, peer
->dstadr
?
3196 ntoa(&peer
->dstadr
->sin
) : "-",
3197 ntoa(&peer
->srcadr
), peer
->hmode
, xkeyid
, sendlen
);
3199 #endif /* OPENSSL */
3204 * fast_xmit - Send packet for nonpersistent association. Note that
3205 * neither the source or destination can be a broadcast address.
3209 struct recvbuf
*rbufp
, /* receive packet pointer */
3210 int xmode
, /* receive mode */
3211 keyid_t xkeyid
, /* transmit key ID */
3212 int flags
/* restrict mask */
3215 struct pkt xpkt
; /* transmit packet structure */
3216 struct pkt
*rpkt
; /* receive packet structure */
3217 l_fp xmt_tx
, xmt_ty
;
3224 * Initialize transmit packet header fields from the receive
3225 * buffer provided. We leave the fields intact as received, but
3226 * set the peer poll at the maximum of the receive peer poll and
3227 * the system minimum poll (ntp_minpoll). This is for KoD rate
3228 * control and not strictly specification compliant, but doesn't
3231 * If the gazinta was from a multicast address, the gazoutta
3232 * must go out another way.
3234 rpkt
= &rbufp
->recv_pkt
;
3235 if (rbufp
->dstadr
->flags
& INT_MCASTOPEN
)
3236 rbufp
->dstadr
= findinterface(&rbufp
->recv_srcadr
);
3239 * If this is a kiss-o'-death (KoD) packet, show leap
3240 * unsynchronized, stratum zero, reference ID the four-character
3241 * kiss code and system root delay. Note we don't reveal the
3242 * local time, so these packets can't be used for
3245 if (flags
& RES_KOD
) {
3247 xpkt
.li_vn_mode
= PKT_LI_VN_MODE(LEAP_NOTINSYNC
,
3248 PKT_VERSION(rpkt
->li_vn_mode
), xmode
);
3249 xpkt
.stratum
= STRATUM_PKT_UNSPEC
;
3250 xpkt
.ppoll
= max(rpkt
->ppoll
, ntp_minpoll
);
3251 memcpy(&xpkt
.refid
, "RATE", 4);
3252 xpkt
.org
= rpkt
->xmt
;
3253 xpkt
.rec
= rpkt
->xmt
;
3254 xpkt
.xmt
= rpkt
->xmt
;
3257 * This is a normal packet. Use the system variables.
3260 xpkt
.li_vn_mode
= PKT_LI_VN_MODE(sys_leap
,
3261 PKT_VERSION(rpkt
->li_vn_mode
), xmode
);
3262 xpkt
.stratum
= STRATUM_TO_PKT(sys_stratum
);
3263 xpkt
.ppoll
= max(rpkt
->ppoll
, ntp_minpoll
);
3264 xpkt
.precision
= sys_precision
;
3265 xpkt
.refid
= sys_refid
;
3266 xpkt
.rootdelay
= HTONS_FP(DTOFP(sys_rootdelay
));
3267 xpkt
.rootdisp
= HTONS_FP(DTOUFP(sys_rootdisp
));
3268 HTONL_FP(&sys_reftime
, &xpkt
.reftime
);
3269 xpkt
.org
= rpkt
->xmt
;
3270 HTONL_FP(&rbufp
->recv_time
, &xpkt
.rec
);
3271 get_systime(&xmt_tx
);
3272 HTONL_FP(&xmt_tx
, &xpkt
.xmt
);
3275 #ifdef HAVE_NTP_SIGND
3276 if (flags
& RES_MSSNTP
) {
3277 send_via_ntp_signd(rbufp
, xmode
, xkeyid
, flags
, &xpkt
);
3280 #endif /* HAVE_NTP_SIGND */
3283 * If the received packet contains a MAC, the transmitted packet
3284 * is authenticated and contains a MAC. If not, the transmitted
3285 * packet is not authenticated.
3287 sendlen
= LEN_PKT_NOMAC
;
3288 if (rbufp
->recv_length
== sendlen
) {
3289 sendpkt(&rbufp
->recv_srcadr
, rbufp
->dstadr
, 0, &xpkt
,
3294 "transmit: at %ld %s->%s mode %d len %d\n",
3295 current_time
, stoa(&rbufp
->dstadr
->sin
),
3296 stoa(&rbufp
->recv_srcadr
), xmode
, sendlen
);
3302 * The received packet contains a MAC, so the transmitted packet
3303 * must be authenticated. For symmetric key cryptography, use
3304 * the predefined and trusted symmetric keys to generate the
3305 * cryptosum. For autokey cryptography, use the server private
3306 * value to generate the cookie, which is unique for every
3307 * source-destination-key ID combination.
3310 if (xkeyid
> NTP_MAXKEY
) {
3314 * The only way to get here is a reply to a legitimate
3315 * client request message, so the mode must be
3316 * MODE_SERVER. If an extension field is present, there
3317 * can be only one and that must be a command. Do what
3318 * needs, but with private value of zero so the poor
3319 * jerk can decode it. If no extension field is present,
3320 * use the cookie to generate the session key.
3322 cookie
= session_key(&rbufp
->recv_srcadr
,
3323 &rbufp
->dstadr
->sin
, 0, sys_private
, 0);
3324 if (rbufp
->recv_length
> sendlen
+ MAX_MAC_LEN
) {
3325 session_key(&rbufp
->dstadr
->sin
,
3326 &rbufp
->recv_srcadr
, xkeyid
, 0, 2);
3327 temp32
= CRYPTO_RESP
;
3328 rpkt
->exten
[0] |= htonl(temp32
);
3329 sendlen
+= crypto_xmit(NULL
, &xpkt
, rbufp
,
3330 sendlen
, (struct exten
*)rpkt
->exten
,
3333 session_key(&rbufp
->dstadr
->sin
,
3334 &rbufp
->recv_srcadr
, xkeyid
, cookie
, 2);
3337 #endif /* OPENSSL */
3338 get_systime(&xmt_tx
);
3339 sendlen
+= authencrypt(xkeyid
, (u_int32
*)&xpkt
, sendlen
);
3341 if (xkeyid
> NTP_MAXKEY
)
3342 authtrust(xkeyid
, 0);
3343 #endif /* OPENSSL */
3344 sendpkt(&rbufp
->recv_srcadr
, rbufp
->dstadr
, 0, &xpkt
, sendlen
);
3345 get_systime(&xmt_ty
);
3346 L_SUB(&xmt_ty
, &xmt_tx
);
3347 sys_authdelay
= xmt_ty
;
3351 "transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
3352 current_time
, ntoa(&rbufp
->dstadr
->sin
),
3353 ntoa(&rbufp
->recv_srcadr
), xmode
, xkeyid
, sendlen
);
3360 * key_expire - purge the key list
3364 struct peer
*peer
/* peer structure pointer */
3369 if (peer
->keylist
!= NULL
) {
3370 for (i
= 0; i
<= peer
->keynumber
; i
++)
3371 authtrust(peer
->keylist
[i
], 0);
3372 free(peer
->keylist
);
3373 peer
->keylist
= NULL
;
3375 value_free(&peer
->sndval
);
3376 peer
->keynumber
= 0;
3377 peer
->flags
&= ~FLAG_ASSOC
;
3380 printf("key_expire: at %lu associd %d\n", current_time
,
3384 #endif /* OPENSSL */
3388 * Determine if the peer is unfit for synchronization
3390 * A peer is unfit for synchronization if
3391 * > TEST10 bad leap or stratum below floor or at or above ceiling
3392 * > TEST11 root distance exceeded for remote peer
3393 * > TEST12 a direct or indirect synchronization loop would form
3394 * > TEST13 unreachable or noselect
3396 int /* FALSE if fit, TRUE if unfit */
3398 struct peer
*peer
/* peer structure pointer */
3404 * A stratum error occurs if (1) the server has never been
3405 * synchronized, (2) the server stratum is below the floor or
3406 * greater than or equal to the ceiling.
3408 if (peer
->leap
== LEAP_NOTINSYNC
|| peer
->stratum
< sys_floor
||
3409 peer
->stratum
>= sys_ceiling
)
3410 rval
|= TEST10
; /* bad synch or stratum */
3413 * A distance error for a remote peer occurs if the root
3414 * distance is greater than or equal to the distance threshold
3415 * plus the increment due to one host poll interval.
3417 if (!(peer
->flags
& FLAG_REFCLOCK
) && root_distance(peer
) >=
3418 sys_maxdist
+ clock_phi
* ULOGTOD(peer
->hpoll
))
3419 rval
|= TEST11
; /* distance exceeded */
3422 * A loop error occurs if the remote peer is synchronized to the
3423 * local peer or if the remote peer is synchronized to the same
3424 * server as the local peer but only if the remote peer is
3425 * neither a reference clock nor an orphan.
3427 if (peer
->stratum
> 1 && peer
->refid
!= htonl(LOOPBACKADR
) &&
3428 (peer
->refid
== (peer
->dstadr
? peer
->dstadr
->addr_refid
:
3429 0) || peer
->refid
== sys_refid
))
3430 rval
|= TEST12
; /* synchronization loop */
3433 * An unreachable error occurs if the server is unreachable or
3434 * the noselect bit is set.
3436 if (!peer
->reach
|| (peer
->flags
& FLAG_NOSELECT
))
3437 rval
|= TEST13
; /* unreachable */
3439 peer
->flash
&= ~PEER_TEST_MASK
;
3440 peer
->flash
|= rval
;
3446 * Find the precision of this particular machine
3448 #define MINSTEP 100e-9 /* minimum clock increment (s) */
3449 #define MAXSTEP 20e-3 /* maximum clock increment (s) */
3450 #define MINLOOPS 5 /* minimum number of step samples */
3453 * This routine measures the system precision defined as the minimum of
3454 * a sequence of differences between successive readings of the system
3455 * clock. However, if a difference is less than MINSTEP, the clock has
3456 * been read more than once during a clock tick and the difference is
3457 * ignored. We set MINSTEP greater than zero in case something happens
3458 * like a cache miss.
3461 default_get_precision(void)
3463 l_fp val
; /* current seconds fraction */
3464 l_fp last
; /* last seconds fraction */
3465 l_fp diff
; /* difference */
3466 double tick
; /* computed tick value */
3467 double dtemp
; /* scratch */
3468 int i
; /* log2 precision */
3471 * Loop to find precision value in seconds.
3479 L_SUB(&diff
, &last
);
3481 LFPTOD(&diff
, dtemp
);
3482 if (dtemp
< MINSTEP
)
3487 if (++i
>= MINLOOPS
)
3493 * Find the nearest power of two.
3495 msyslog(LOG_NOTICE
, "proto: precision = %.3f usec", tick
* 1e6
);
3496 for (i
= 0; tick
<= 1; i
++)
3498 if (tick
- 1 > 1 - tick
/ 2)
3505 * init_proto - initialize the protocol module's data
3514 * Fill in the sys_* stuff. Default is don't listen to
3515 * broadcasting, require authentication.
3517 sys_leap
= LEAP_NOTINSYNC
;
3518 sys_stratum
= STRATUM_UNSPEC
;
3519 memcpy(&sys_refid
, "INIT", 4);
3523 L_CLR(&sys_reftime
);
3525 sys_precision
= (s_char
)default_get_precision();
3526 get_systime(&dummy
);
3528 sys_manycastserver
= 0;
3531 sys_authenticate
= 1;
3532 sys_stattime
= current_time
;
3534 for (i
= 0; i
< MAX_TTL
; i
++) {
3535 sys_ttl
[i
] = (u_char
)((i
* 256) / MAX_TTL
);
3544 * proto_config - configure the protocol module
3555 * Figure out what he wants to change, then do it
3557 DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
3558 item
, value
, dvalue
));
3563 * enable and disable commands - arguments are Boolean.
3565 case PROTO_AUTHENTICATE
: /* authentication (auth) */
3566 sys_authenticate
= value
;
3569 case PROTO_BROADCLIENT
: /* broadcast client (bclient) */
3570 sys_bclient
= (int)value
;
3571 if (sys_bclient
== 0)
3578 case PROTO_CAL
: /* refclock calibrate (calibrate) */
3581 #endif /* REFCLOCK */
3583 case PROTO_KERNEL
: /* kernel discipline (kernel) */
3584 kern_enable
= value
;
3587 case PROTO_MONITOR
: /* monitoring (monitor) */
3594 case PROTO_NTP
: /* NTP discipline (ntp) */
3598 case PROTO_PPS
: /* PPS discipline (pps) */
3602 case PROTO_FILEGEN
: /* statistics (stats) */
3603 stats_control
= value
;
3607 * tos command - arguments are double, sometimes cast to int
3609 case PROTO_BEACON
: /* manycast beacon (beacon) */
3610 sys_beacon
= (int)dvalue
;
3613 case PROTO_BROADDELAY
: /* default broadcast delay (bdelay) */
3614 sys_bdelay
= dvalue
;
3617 case PROTO_CEILING
: /* stratum ceiling (ceiling) */
3618 sys_ceiling
= (int)dvalue
;
3621 case PROTO_COHORT
: /* cohort switch (cohort) */
3622 sys_cohort
= (int)dvalue
;
3625 case PROTO_FLOOR
: /* stratum floor (floor) */
3626 sys_floor
= (int)dvalue
;
3629 case PROTO_MAXCLOCK
: /* maximum candidates (maxclock) */
3630 sys_maxclock
= (int)dvalue
;
3633 case PROTO_MAXDIST
: /* select threshold (maxdist) */
3634 sys_maxdist
= dvalue
;
3637 case PROTO_CALLDELAY
: /* modem call delay (mdelay) */
3638 break; /* NOT USED */
3640 case PROTO_MINCLOCK
: /* minimum candidates (minclock) */
3641 sys_minclock
= (int)dvalue
;
3644 case PROTO_MINDISP
: /* minimum distance (mindist) */
3645 sys_mindisp
= dvalue
;
3648 case PROTO_MINSANE
: /* minimum survivors (minsane) */
3649 sys_minsane
= (int)dvalue
;
3652 case PROTO_ORPHAN
: /* orphan stratum (orphan) */
3653 sys_orphan
= (int)dvalue
;
3656 case PROTO_ADJ
: /* tick increment (tick) */
3661 * Miscellaneous commands
3663 case PROTO_MULTICAST_ADD
: /* add group address */
3665 io_multicast_add(svalue
);
3669 case PROTO_MULTICAST_DEL
: /* delete group address */
3671 io_multicast_del(svalue
);
3676 "proto: unsupported option %d", item
);
3682 * proto_clr_stats - clear protocol stat counters
3685 proto_clr_stats(void)
3687 sys_stattime
= current_time
;
3696 sys_limitrejected
= 0;