2 * ntp_proto.c - NTP version 4 protocol machinery
4 * $FreeBSD: src/contrib/ntp/ntpd/ntp_proto.c,v 1.3.2.1 2001/12/21 17:39:13 roberto Exp $
5 * $DragonFly: src/contrib/ntp/ntpd/Attic/ntp_proto.c,v 1.2 2003/06/17 04:24:04 dillon Exp $
12 #include "ntp_stdlib.h"
13 #include "ntp_unixtime.h"
14 #include "ntp_control.h"
15 #include "ntp_string.h"
16 #include "ntp_crypto.h"
20 #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
21 #include "ntp_refclock.h"
24 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
25 #include <sys/sysctl.h>
29 * System variables are declared here. See Section 3.2 of the
32 u_char sys_leap; /* system leap indicator */
33 u_char sys_stratum; /* stratum of system */
34 s_char sys_precision; /* local clock precision */
35 double sys_rootdelay; /* roundtrip delay to primary source */
36 double sys_rootdispersion; /* dispersion to primary source */
37 u_int32 sys_refid; /* reference source for local clock */
38 static double sys_offset; /* current local clock offset */
39 l_fp sys_reftime; /* time we were last updated */
40 struct peer *sys_peer; /* our current peer */
41 struct peer *sys_prefer; /* our cherished peer */
43 u_long sys_automax; /* maximum session key lifetime */
47 * Nonspecified system state variables.
49 int sys_bclient; /* we set our time to broadcasts */
50 double sys_bdelay; /* broadcast client default delay */
51 int sys_authenticate; /* requre authentication for config */
52 l_fp sys_authdelay; /* authentication delay */
53 static u_long sys_authdly[2]; /* authentication delay shift reg */
54 static u_char leap_consensus; /* consensus of survivor leap bits */
55 static double sys_selerr; /* select error (squares) */
56 static double sys_syserr; /* system error (squares) */
57 keyid_t sys_private; /* private value for session seed */
58 int sys_manycastserver; /* respond to manycast client pkts */
59 u_int sys_survivors; /* truest of the truechimers */
60 int peer_ntpdate; /* active peers in ntpdate mode */
62 char *sys_hostname; /* gethostname() name */
68 u_long sys_stattime; /* time when we started recording */
69 u_long sys_badstratum; /* packets with invalid stratum */
70 u_long sys_oldversionpkt; /* old version packets received */
71 u_long sys_newversionpkt; /* new version packets received */
72 u_long sys_unknownversion; /* don't know version packets */
73 u_long sys_badlength; /* packets with bad length */
74 u_long sys_processed; /* packets processed */
75 u_long sys_badauth; /* packets dropped because of auth */
76 u_long sys_limitrejected; /* pkts rejected due to client count per net */
78 static double root_distance P((struct peer *));
79 static double clock_combine P((struct peer **, int));
80 static void peer_xmit P((struct peer *));
81 static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
82 static void clock_update P((void));
83 int default_get_precision P((void));
87 * transmit - Transmit Procedure. See Section 3.4.2 of the
92 struct peer *peer /* peer structure pointer */
98 if (peer->burst == 0) {
102 * The polling state machine. There are two kinds of
103 * machines, those that never expect a reply (broadcast
104 * and manycast server modes) and those that do (all
105 * other modes). The dance is intricate...
107 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
110 * In broadcast mode the poll interval is fixed
111 * at minpoll and the ttl at ttlmax.
113 hpoll = peer->minpoll;
114 peer->ttl = peer->ttlmax;
116 } else if (peer->cast_flags & MDF_ACAST) {
119 * In manycast mode we start with the minpoll
120 * interval and ttl. However, the actual poll
121 * interval is eight times the nominal poll
122 * interval shown here. If fewer than three
123 * servers are found, the ttl is increased by
124 * one and we try again. If this continues to
125 * the max ttl, the poll interval is bumped by
126 * one and we try again. If at least three
127 * servers are found, the poll interval
128 * increases with the system poll interval to
129 * the max and we continue indefinately.
130 * However, about once per day when the
131 * agreement parameters are refreshed, the
132 * manycast clients are reset and we start from
133 * the beginning. This is to catch and clamp the
134 * ttl to the lowest practical value and avoid
135 * knocking on spurious doors.
137 if (sys_survivors < NTP_MINCLOCK && peer->ttl <
145 * For associations expecting a reply, the
146 * watchdog counter is bumped by one if the peer
147 * has not been heard since the previous poll.
148 * If the counter reaches the max, the peer is
149 * demobilized if not configured and just
150 * cleared if it is, but in this case the poll
151 * interval is bumped by one.
153 if (peer->unreach < NTP_UNREACH) {
155 } else if (!(peer->flags & FLAG_CONFIG)) {
165 oreach = peer->reach;
167 if (peer->reach == 0) {
170 * If this association has become unreachable,
171 * clear it and raise a trap.
174 report_event(EVNT_UNREACH, peer);
175 peer->timereachable = current_time;
176 if (!(peer->flags & FLAG_CONFIG)) {
182 hpoll = peer->minpoll;
185 if (peer->flags & FLAG_IBURST)
186 peer->burst = NTP_SHIFT;
190 * Here the peer is reachable. If it has not
191 * been heard for three consecutive polls, stuff
192 * the clock filter. Next, determine the poll
193 * interval. If the peer is a synchronization
194 * candidate, use the system poll interval. If
195 * the peer is not sane, increase it by one. If
196 * the number of valid updates is not greater
197 * than half the register size, clamp it to the
198 * minimum. This is to quickly recover the time
199 * variables when a noisy peer shows life.
201 if (!(peer->reach & 0x07)) {
202 clock_filter(peer, 0., 0., MAXDISPERSE);
205 if ((peer->stratum > 1 && peer->refid ==
206 peer->dstadr->sin.sin_addr.s_addr) ||
207 peer->stratum >= STRATUM_UNSPEC)
211 if (peer->flags & FLAG_BURST)
212 peer->burst = NTP_SHIFT;
216 if (peer->burst == 0) {
219 * If a broadcast client at this point, the
220 * burst has concluded, so we switch to client
221 * mode and purge the keylist, since no further
222 * transmissions will be made.
224 if (peer->cast_flags & MDF_BCLNT) {
225 peer->hmode = MODE_BCLIENT;
230 poll_update(peer, hpoll);
234 * If ntpdate mode and the clock has not been
235 * set and all peers have completed the burst,
236 * we declare a successful failure.
240 if (peer_ntpdate > 0)
242 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
244 "no reply; clock not set");
246 "ntpd: no reply; clock not set\n");
253 peer->outdate = current_time;
254 poll_update(peer, hpoll);
257 * We need to be very careful about honking uncivilized time.
258 * Never transmit if in broadcast client mode or access denied.
259 * If in broadcast mode, transmit only if synchronized to a
262 if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
264 } else if (peer->hmode == MODE_BROADCAST) {
265 if (sys_peer == NULL)
272 * receive - Receive Procedure. See section 3.4.3 in the specification.
276 struct recvbuf *rbufp
279 register struct peer *peer;
280 register struct pkt *pkt;
284 int has_mac; /* length of MAC field */
285 int authlen; /* offset of MAC field */
286 int is_authentic; /* cryptosum ok */
287 keyid_t skeyid; /* cryptographic keys */
288 struct sockaddr_in *dstadr_sin; /* active runway */
290 keyid_t pkeyid, tkeyid; /* cryptographic keys */
293 int retcode = AM_NOMATCH;
296 * Monitor the packet and get restrictions. Note that the packet
297 * length for control and private mode packets must be checked
298 * by the service routines. Note that no statistics counters are
299 * recorded for restrict violations, since these counters are in
300 * the restriction routine. Note the careful distinctions here
301 * between a packet with a format error and a packet that is
302 * simply discarded without prejudice. Some restrictions have to
303 * be handled later in order to generate a kiss-of-death packet.
306 restrict_mask = restrictions(&rbufp->recv_srcadr);
309 printf("receive: at %ld %s<-%s restrict %02x\n",
310 current_time, ntoa(&rbufp->dstadr->sin),
311 ntoa(&rbufp->recv_srcadr), restrict_mask);
313 if (restrict_mask & RES_IGNORE)
314 return; /* no anything */
315 if (!(SRCPORT(&rbufp->recv_srcadr) == NTP_PORT ||
316 SRCPORT(&rbufp->recv_srcadr) >= IPPORT_RESERVED)) {
318 return; /* invalid port */
320 pkt = &rbufp->recv_pkt;
321 if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
322 sys_newversionpkt++; /* new version */
323 } else if (!(restrict_mask & RES_VERSION) &&
324 PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
325 sys_oldversionpkt++; /* old version */
327 sys_unknownversion++;
328 return; /* invalid version */
330 if (PKT_MODE(pkt->li_vn_mode) == MODE_PRIVATE) {
331 if (restrict_mask & RES_NOQUERY)
332 return; /* no query private */
333 process_private(rbufp, ((restrict_mask &
334 RES_NOMODIFY) == 0));
337 if (PKT_MODE(pkt->li_vn_mode) == MODE_CONTROL) {
338 if (restrict_mask & RES_NOQUERY)
339 return; /* no query control */
340 process_control(rbufp, restrict_mask);
343 if (rbufp->recv_length < LEN_PKT_NOMAC) {
345 return; /* runt packet */
349 * Validate mode. Note that NTPv1 is no longer supported.
351 hismode = (int)PKT_MODE(pkt->li_vn_mode);
352 if (hismode == MODE_UNSPEC) {
354 return; /* invalid mode */
358 * Discard broadcast packets received on the wildcard interface
359 * or if not enabled as broadcast client.
361 if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
362 (rbufp->dstadr == any_interface || !sys_bclient))
366 * Parse the extension field if present. We figure out whether
367 * an extension field is present by measuring the MAC size. If
368 * the number of words following the packet header is 0 or 1, no
369 * MAC is present and the packet is not authenticated. If 1, the
370 * packet is a reply to a previous request that failed to
371 * authenticate. If 3, the packet is authenticated with DES; if
372 * 5, the packet is authenticated with MD5. If greater than 5,
373 * an extension field is present. If 2 or 4, the packet is a
374 * runt and goes poof! with a brilliant flash.
380 authlen = LEN_PKT_NOMAC;
381 while ((has_mac = rbufp->recv_length - authlen) > 0) {
384 if (has_mac % 4 != 0 || has_mac < 0) {
388 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
390 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
393 } else if (has_mac > MAX_MAC_LEN) {
394 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
396 if (temp < 4 || temp % 4 != 0) {
408 * We have tossed out as many buggy packets as possible early in
409 * the game to reduce the exposure to a clogging attack. Now we
410 * have to burn some cycles to find the association and
411 * authenticate the packet if required. Note that we burn only
412 * MD5 or DES cycles, again to reduce exposure. There may be no
413 * matching association and that's okay.
415 * More on the autokey mambo. Normally the local interface is
416 * found when the association was mobilized with respect to a
417 * designated remote address. We assume packets arriving from
418 * the remote address arrive via this interface and the local
419 * address used to construct the autokey is the unicast address
420 * of the interface. However, if the sender is a broadcaster,
421 * the interface broadcast address is used instead.
422 * Notwithstanding this technobabble, if the sender is a
423 * multicaster, the broadcast address is null, so we use the
424 * unicast address anyway. Don't ask.
426 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
429 dstadr_sin = &rbufp->dstadr->sin;
433 printf("receive: at %ld %s<-%s mode %d code %d\n",
434 current_time, ntoa(&rbufp->dstadr->sin),
435 ntoa(&rbufp->recv_srcadr), hismode, retcode);
440 * For autokey modes, generate the session key
441 * and install in the key cache. Use the socket
442 * broadcast or unicast address as appropriate.
444 if (skeyid > NTP_MAXKEY) {
447 * More on the autokey dance (AKD). A cookie is
448 * constructed from public and private values.
449 * For broadcast packets, the cookie is public
450 * (zero). For packets that match no
451 * association, the cookie is hashed from the
452 * addresses and private value. For server
453 * packets, the cookie was previously obtained
454 * from the server. For symmetric modes, the
455 * cookie was previously constructed using an
456 * agreement protocol; however, should PKI be
457 * unavailable, we construct a fake agreement as
458 * the EXOR of the peer and host cookies.
460 * hismode ephemeral persistent
461 * =======================================
464 * client sys cookie 0%
465 * server 0% sys cookie
471 if (hismode == MODE_BROADCAST) {
474 * For broadcaster, use the interface
475 * broadcast address when available;
476 * otherwise, use the unicast address
477 * found when the association was
481 if (rbufp->dstadr->bcast.sin_addr.s_addr
484 &rbufp->dstadr->bcast;
485 } else if (peer == NULL) {
486 pkeyid = session_key(
487 &rbufp->recv_srcadr, dstadr_sin, 0,
490 pkeyid = peer->pcookie.key;
494 * The session key includes both the public
495 * values and cookie. In case of an extension
496 * field, the cookie used for authentication
497 * purposes is zero. Note the hash is saved for
498 * use later in the autokey mambo.
500 if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
501 session_key(&rbufp->recv_srcadr,
502 dstadr_sin, skeyid, 0, 2);
503 tkeyid = session_key(
504 &rbufp->recv_srcadr, dstadr_sin,
507 tkeyid = session_key(
508 &rbufp->recv_srcadr, dstadr_sin,
516 * Compute the cryptosum. Note a clogging attack may
517 * succeed in bloating the key cache. If an autokey,
518 * purge it immediately, since we won't be needing it
521 if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
527 if (skeyid > NTP_MAXKEY)
528 authtrust(skeyid, 0);
533 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
534 current_time, ntoa(dstadr_sin),
535 ntoa(&rbufp->recv_srcadr), hismode, retcode,
536 skeyid, authlen, has_mac,
542 * The association matching rules are implemented by a set of
543 * routines and a table in ntp_peer.c. A packet matching an
544 * association is processed by that association. If not and
545 * certain conditions prevail, then an ephemeral association is
546 * mobilized: a broadcast packet mobilizes a broadcast client
547 * aassociation; a server packet mobilizes a client association;
548 * a symmetric active packet mobilizes a symmetric passive
549 * association. And, the adventure continues...
555 * This is a client mode packet not matching a known
556 * association. If from a manycast client we run a few
557 * sanity checks before deciding to send a unicast
558 * server response. Otherwise, it must be a client
559 * request, so send a server response and go home.
561 if (sys_manycastserver && (rbufp->dstadr->flags &
565 * We are picky about responding to a
566 * manycaster. There is no reason to respond to
567 * a request if our time is worse than the
568 * manycaster. We certainly don't reply if not
569 * synchronized to proventic time.
571 if (sys_peer == NULL)
575 * We don't reply if the our stratum is greater
576 * than the manycaster.
578 if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
583 * Note that we don't require an authentication check
584 * here, since we can't set the system clock; but, we do
585 * set the key ID to zero to tell the caller about this.
588 fast_xmit(rbufp, MODE_SERVER, skeyid,
591 fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
597 * This is a server mode packet returned in response to
598 * a client mode packet sent to a multicast group
599 * address. The originate timestamp is a good nonce to
600 * reliably associate the reply with what was sent. If
601 * there is no match, that's curious and could be an
602 * intruder attempting to clog, so we just ignore it.
604 * First, make sure the packet is authentic. If so and
605 * the manycast association is found, we mobilize a
606 * client mode association, copy pertinent variables
607 * from the manycast to the client mode association and
608 * wind up the spring.
610 * There is an implosion hazard at the manycast client,
611 * since the manycast servers send the server packet
614 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
615 RES_NOPEER)) || (sys_authenticate &&
619 peer2 = findmanycastpeer(rbufp);
623 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
624 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
625 sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
626 (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
627 MDF_UCAST, 0, skeyid);
635 * This is the first packet received from a symmetric
636 * active peer. First, make sure the packet is
637 * authentic. If so, mobilize a symmetric passive
640 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
641 RES_NOPEER)) || (sys_authenticate &&
643 fast_xmit(rbufp, MODE_PASSIVE, 0,
647 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
648 MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
649 sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
650 FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
658 * This is the first packet received from a broadcast
659 * server. First, make sure the packet is authentic, not
660 * restricted and that we are a broadcast or multicast
661 * client. If so, mobilize a broadcast client
664 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
665 RES_NOPEER)) || (sys_authenticate &&
666 !is_authentic) || !sys_bclient)
669 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
670 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
671 sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
672 FLAG_IBURST | (sys_authenticate ?
673 FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
678 if (peer->flags & FLAG_SKEY)
679 crypto_recv(peer, rbufp);
688 * Happiness and nothing broke. Earn some revenue.
695 * Invalid mode combination. Leave the island
700 printf("receive: bad protocol %d\n", retcode);
706 * If the peer isn't configured, set his authenable and autokey
707 * status based on the packet. Once the status is set, it can't
708 * be unset. It seems like a silly idea to do this here, rather
709 * in the configuration routine, but in some goofy cases the
710 * first packet sent cannot be authenticated and we need a way
711 * for the dude to change his mind.
713 oflags = peer->flags;
714 peer->timereceived = current_time;
716 if (!(peer->flags & FLAG_CONFIG) && has_mac) {
717 peer->flags |= FLAG_AUTHENABLE;
719 if (skeyid > NTP_MAXKEY)
720 peer->flags |= FLAG_SKEY;
725 * A valid packet must be from an authentic and allowed source.
726 * All packets must pass the authentication allowed tests.
727 * Autokey authenticated packets must pass additional tests and
728 * public-key authenticated packets must have the credentials
729 * verified. If all tests are passed, the packet is forwarded
730 * for processing. If not, the packet is discarded and the
731 * association demobilized if appropriate.
735 peer->flags |= FLAG_AUTHENTIC;
737 peer->flags &= ~FLAG_AUTHENTIC;
739 if (peer->hmode == MODE_BROADCAST &&
740 (restrict_mask & RES_DONTTRUST)) /* test 4 */
741 peer->flash |= TEST4; /* access denied */
742 if (peer->flags & FLAG_AUTHENABLE) {
743 if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
744 peer->flash |= TEST5; /* auth failed */
745 else if (!(oflags & FLAG_AUTHENABLE))
746 report_event(EVNT_PEERAUTH, peer);
751 printf("receive: bad auth %03x\n", peer->flash);
758 * More autokey dance. The rules of the cha-cha are as follows:
760 * 1. If there is no key or the key is not auto, do nothing.
762 * 2. If an extension field contains a verified signature, it is
763 * self-authenticated and we sit the dance.
765 * 3. If this is a server reply, check only to see that the
766 * transmitted key ID matches the received key ID.
768 * 4. Check to see that one or more hashes of the current key ID
769 * matches the previous key ID or ultimate original key ID
770 * obtained from the broadcaster or symmetric peer. If no
771 * match, sit the dance and wait for timeout.
773 if (peer->flags & FLAG_SKEY) {
774 peer->flash |= TEST10;
775 crypto_recv(peer, rbufp);
776 poll_update(peer, peer->hpoll);
777 if (hismode == MODE_SERVER) {
778 if (skeyid == peer->keyid)
779 peer->flash &= ~TEST10;
780 } else if (!peer->flash & TEST10) {
781 peer->pkeyid = skeyid;
786 if (tkeyid == peer->pkeyid ||
787 tkeyid == peer->recauto.key) {
788 peer->flash &= ~TEST10;
789 peer->pkeyid = skeyid;
792 if (i > peer->recauto.seq)
794 tkeyid = session_key(
795 &rbufp->recv_srcadr, dstadr_sin,
802 * This is delicious. Ordinarily, we kick out all errors
803 * at this point; however, in symmetric mode and just
804 * warming up, an unsynchronized peer must inject the
805 * timestamps, even if it fails further up the road. So,
806 * let the dude by here, but only if the jerk is not yet
807 * reachable. After that, he's on his own.
809 if (!(peer->flags & FLAG_PROVEN))
810 peer->flash |= TEST11;
811 if (peer->flash && peer->reach) {
814 printf("packet: bad autokey %03x\n",
824 * We have survived the gaunt. Forward to the packet routine. If
825 * a symmetric passive association has been mobilized and the
826 * association doesn't deserve to live, it will die in the
827 * transmit routine if not reachable after timeout.
829 process_packet(peer, pkt, &rbufp->recv_time);
834 * process_packet - Packet Procedure, a la Section 3.4.4 of the
835 * specification. Or almost, at least. If we're in here we have a
836 * reasonable expectation that we will be having a long term
837 * relationship with this host.
841 register struct peer *peer,
842 register struct pkt *pkt,
847 double p_offset, p_del, p_disp;
849 l_fp p_rec, p_xmt, p_org, p_reftime;
851 int pmode, pleap, pstratum;
854 * Swap header fields and keep the books. The books amount to
855 * the receive timestamp and poll interval in the header. We
856 * need these even if there are other problems in order to crank
857 * up the state machine.
861 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
862 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
863 NTOHL_FP(&pkt->reftime, &p_reftime);
864 NTOHL_FP(&pkt->rec, &p_rec);
865 NTOHL_FP(&pkt->xmt, &p_xmt);
866 if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST)
867 NTOHL_FP(&pkt->org, &p_org);
872 * Test for old, duplicate or unsynch packets (tests 1-3).
874 peer->rec = *recv_ts;
875 pmode = PKT_MODE(pkt->li_vn_mode);
876 pleap = PKT_LEAP(pkt->li_vn_mode);
877 pstratum = PKT_TO_STRATUM(pkt->stratum);
878 if (L_ISHIS(&peer->org, &p_xmt)) /* count old packets */
880 if (L_ISEQU(&peer->org, &p_xmt)) /* 1 */
881 peer->flash |= TEST1; /* dupe */
882 if (pmode != MODE_BROADCAST) {
883 if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
884 peer->flash |= TEST2; /* bogus */
885 if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
886 peer->flash |= TEST3; /* unsynch */
888 if (L_ISZERO(&p_xmt)) /* 3 */
889 peer->flash |= TEST3; /* unsynch */
893 * If tests 1-3 fail, the packet is discarded leaving only the
894 * receive and origin timestamps and poll interval, which is
895 * enough to get the protocol started.
900 printf("packet: bad data %03x\n",
907 * A kiss-of-death (kod) packet is returned by a server in case
908 * the client is denied access. It consists of the client
909 * request packet with the leap bits indicating never
910 * synchronized, stratum zero and reference ID field the ASCII
911 * string "DENY". If the packet originate timestamp matches the
912 * association transmit timestamp the kod is legitimate. If the
913 * peer leap bits indicate never synchronized, this must be
914 * access deny and the association is disabled; otherwise this
915 * must be a limit reject. In either case a naughty message is
916 * forced to the system log.
918 if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
919 memcmp(&pkt->refid, "DENY", 4) == 0) {
920 if (peer->leap == LEAP_NOTINSYNC) {
921 peer->stratum = STRATUM_UNSPEC;
922 peer->flash |= TEST4;
923 memcpy(&peer->refid, &pkt->refid, 4);
924 msyslog(LOG_INFO, "access denied");
926 msyslog(LOG_INFO, "limit reject");
932 * Test for valid peer data (tests 6-8)
935 L_SUB(&ci, &p_reftime);
937 if (pleap == LEAP_NOTINSYNC || /* 6 */
938 pstratum >= STRATUM_UNSPEC || dtemp < 0)
939 peer->flash |= TEST6; /* bad synch */
940 if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
941 if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
942 peer->flash |= TEST7; /* bad stratum */
946 if (p_del < 0 || p_disp < 0 || p_del / /* 8 */
947 2 + p_disp >= MAXDISPERSE)
948 peer->flash |= TEST8; /* bad peer distance */
952 printf("packet: bad header %03x\n",
959 * The header is valid. Capture the remaining header values and
962 record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
963 &p_rec, &p_xmt, &peer->rec);
966 peer->stratum = pstratum;
967 peer->ppoll = pkt->ppoll;
968 peer->precision = pkt->precision;
969 peer->rootdelay = p_del;
970 peer->rootdispersion = p_disp;
971 peer->refid = pkt->refid;
972 peer->reftime = p_reftime;
973 if (!(peer->reach)) {
974 report_event(EVNT_REACH, peer);
975 peer->timereachable = current_time;
979 poll_update(peer, peer->hpoll);
982 * If running in a client/server association, calculate the
983 * clock offset c, roundtrip delay d and dispersion e. We use
984 * the equations (reordered from those in the spec). Note that,
985 * in a broadcast association, org has been set to the time of
986 * last reception. Note the computation of dispersion includes
987 * the system precision plus that due to the frequency error
988 * since the originate time.
990 * c = ((t2 - t3) + (t1 - t0)) / 2
991 * d = (t2 - t3) - (t1 - t0)
992 * e = (org - rec) (seconds only)
994 t10 = p_xmt; /* compute t1 - t0 */
995 L_SUB(&t10, &peer->rec);
996 t23 = p_rec; /* compute t2 - t3 */
999 p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
1002 * If running in a broadcast association, the clock offset is
1003 * (t1 - t0) corrected by the one-way delay, but we can't
1004 * measure that directly. Therefore, we start up in MODE_CLIENT
1005 * mode, set FLAG_MCAST and exchange eight messages to determine
1006 * the clock offset. When the last message is sent, we switch to
1007 * MODE_BCLIENT mode. The next broadcast message after that
1008 * computes the broadcast offset and clears FLAG_MCAST.
1010 if (pmode == MODE_BROADCAST) {
1011 if (peer->flags & FLAG_MCAST) {
1012 LFPTOD(&ci, p_offset);
1013 peer->estbdelay = peer->offset - p_offset;
1014 if (peer->hmode == MODE_CLIENT)
1017 peer->flags &= ~FLAG_MCAST;
1019 DTOLFP(peer->estbdelay, &t10);
1021 p_del = peer->delay;
1026 LFPTOD(&t23, p_del);
1028 p_del = max(p_del, LOGTOD(sys_precision));
1029 LFPTOD(&ci, p_offset);
1030 if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1031 p_disp >= MAXDISPERSE) /* 9 */
1032 peer->flash |= TEST9; /* bad peer distance */
1035 * If any flasher bits remain set at this point, abandon ship.
1036 * Otherwise, forward to the clock filter.
1041 printf("packet: bad packet data %03x\n",
1046 clock_filter(peer, p_offset, p_del, p_disp);
1048 record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1049 peer->offset, peer->delay, peer->disp,
1050 SQRT(peer->jitter));
1055 * clock_update - Called at system process update intervals.
1064 * Reset/adjust the system clock. Do this only if there is a
1065 * system peer and we haven't seen that peer lately. Watch for
1068 if (sys_peer == NULL)
1070 if (sys_peer->pollsw == FALSE || sys_peer->burst > 0)
1072 sys_peer->pollsw = FALSE;
1075 printf("clock_update: at %ld assoc %d \n", current_time,
1079 ostratum = sys_stratum;
1080 switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1083 * Clock is too screwed up. Just exit for now.
1086 report_event(EVNT_SYSFAULT, (struct peer *)0);
1091 * Clock was stepped. Flush all time values of all peers.
1096 sys_stratum = STRATUM_UNSPEC;
1097 sys_poll = NTP_MINPOLL;
1098 NLOG(NLOG_SYNCSTATUS)
1099 msyslog(LOG_INFO, "synchronisation lost");
1100 report_event(EVNT_CLOCKRESET, (struct peer *)0);
1104 * Update the system stratum, leap bits, root delay, root
1105 * dispersion, reference ID and reference time. We also update
1106 * select dispersion and max frequency error. If the leap
1107 * changes, we gotta reroll the keys.
1110 sys_stratum = sys_peer->stratum + 1;
1111 if (sys_stratum == 1)
1112 sys_refid = sys_peer->refid;
1114 sys_refid = sys_peer->srcadr.sin_addr.s_addr;
1115 sys_reftime = sys_peer->rec;
1116 sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1117 sys_leap = leap_consensus;
1119 if (oleap == LEAP_NOTINSYNC) {
1120 report_event(EVNT_SYNCCHG, (struct peer *)0);
1123 #endif /* AUTOKEY */
1125 if (ostratum != sys_stratum)
1126 report_event(EVNT_PEERSTCHG, (struct peer *)0);
1131 * poll_update - update peer poll interval
1141 #endif /* AUTOKEY */
1144 * A little foxtrot to determine what controls the poll
1145 * interval. If the peer is reachable, but the last four polls
1146 * have not been answered, use the minimum. If declared
1147 * truechimer, use the system poll interval. This allows each
1148 * association to ramp up the poll interval for useless sources
1149 * and to clamp it to the minimum when first starting up.
1152 oldpoll = peer->kpoll;
1153 #endif /* AUTOKEY */
1154 if (hpoll > peer->maxpoll)
1155 peer->hpoll = peer->maxpoll;
1156 else if (hpoll < peer->minpoll)
1157 peer->hpoll = peer->minpoll;
1159 peer->hpoll = hpoll;
1162 * Bit of adventure here. If during a burst and not timeout,
1163 * just slink away. If timeout, figure what the next timeout
1164 * should be. If IBURST or a reference clock, use one second. If
1165 * not and the dude was reachable during the previous poll
1166 * interval, randomize over 1-4 seconds; otherwise, randomize
1167 * over 15-18 seconds. This is to give time for a modem to
1168 * complete the call, for example. If not during a burst,
1169 * randomize over the poll interval -1 to +2 seconds.
1171 * In case of manycast server, make the poll interval, which is
1172 * axtually the manycast beacon interval, eight times the system
1173 * poll interval. Normally when the host poll interval settles
1174 * up to 17.1 s, the beacon interval settles up to 2.3 hours.
1176 if (peer->burst > 0) {
1177 if (peer->nextdate != current_time)
1180 else if (peer->flags & FLAG_REFCLOCK)
1183 else if (peer->reach & 0x1)
1184 peer->nextdate += RANDPOLL(BURST_INTERVAL2);
1186 peer->nextdate += RANDPOLL(BURST_INTERVAL1);
1187 } else if (peer->cast_flags & MDF_ACAST) {
1188 if (sys_survivors < NTP_MINCLOCK)
1189 peer->kpoll = peer->hpoll;
1191 peer->kpoll = peer->hpoll + 3;
1192 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1194 peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1196 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1198 if (peer->nextdate < current_time)
1199 peer->nextdate = current_time;
1202 * Bit of crass arrogance at this point. If the poll interval
1203 * has changed and we have a keylist, the lifetimes in the
1204 * keylist are probably bogus. In this case purge the keylist
1205 * and regenerate it later.
1207 if (peer->kpoll != oldpoll)
1209 #endif /* AUTOKEY */
1212 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1213 current_time, ntoa(&peer->srcadr), peer->flags,
1214 peer->kpoll, peer->burst, peer->outdate,
1221 * clear - clear peer filter registers. See Section 3.4.8 of the spec.
1225 register struct peer *peer
1232 * If cryptographic credentials have been acquired, toss them to
1233 * Valhalla. Note that autokeys are ephemeral, in that they are
1234 * tossed immediately upon use. Therefore, the keylist can be
1235 * purged anytime without needing to preserve random keys. Note
1236 * that, if the peer is purged, the cryptographic variables are
1237 * purged, too. This makes it much harder to sneak in some
1238 * unauthenticated data in the clock filter.
1242 printf("peer_clear: at %ld assoc ID %d\n", current_time,
1248 if (peer->keystr != NULL)
1250 if (peer->pubkey.ptr != NULL)
1251 free(peer->pubkey.ptr);
1252 if (peer->certif.ptr != NULL)
1253 free(peer->certif.ptr);
1255 #endif /* AUTOKEY */
1256 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1259 * If he dies as a broadcast client, he comes back to life as
1260 * a broadcast client in client mode in order to recover the
1261 * initial autokey values. Note that there is no need to call
1262 * clock_select(), since the perp has already been voted off
1263 * the island at this point.
1265 if (peer->cast_flags & MDF_BCLNT) {
1266 peer->flags |= FLAG_MCAST;
1267 peer->hmode = MODE_CLIENT;
1269 peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1270 peer->estbdelay = sys_bdelay;
1271 peer->hpoll = peer->kpoll = peer->minpoll;
1272 peer->ppoll = peer->maxpoll;
1273 peer->pollsw = FALSE;
1274 peer->jitter = MAXDISPERSE;
1275 peer->epoch = current_time;
1277 if (!(peer->flags & FLAG_REFCLOCK)) {
1278 peer->leap = LEAP_NOTINSYNC;
1279 peer->stratum = STRATUM_UNSPEC;
1282 for (i = 0; i < NTP_SHIFT; i++) {
1283 peer->filter_order[i] = i;
1284 peer->filter_disp[i] = MAXDISPERSE;
1285 peer->filter_epoch[i] = current_time;
1289 * Randomize the first poll over 1-16s to avoid bunching.
1291 peer->update = peer->outdate = current_time;
1293 peer->nextdate = current_time + (u_rand & ((1 <<
1294 BURST_INTERVAL1) - 1)) + 1;
1299 * clock_filter - add incoming clock sample to filter register and run
1300 * the filter procedure to find the best sample.
1304 register struct peer *peer, /* peer structure pointer */
1305 double sample_offset, /* clock offset */
1306 double sample_delay, /* roundtrip delay */
1307 double sample_disp /* dispersion */
1310 double dst[NTP_SHIFT]; /* distance vector */
1311 int ord[NTP_SHIFT]; /* index vector */
1312 register int i, j, k, m;
1313 double dsp, jit, dtemp, etemp;
1316 * Shift the new sample into the register and discard the oldest
1317 * one. The new offset and delay come directly from the
1318 * timestamp calculations. The dispersion grows from the last
1319 * outbound packet or reference clock update to the present time
1320 * and increased by the sum of the peer precision and the system
1321 * precision. The delay can sometimes swing negative due to
1322 * frequency skew, so it is clamped non-negative.
1324 dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1325 sample_disp, MAXDISPERSE);
1326 j = peer->filter_nextpt;
1327 peer->filter_offset[j] = sample_offset;
1328 peer->filter_delay[j] = max(0, sample_delay);
1329 peer->filter_disp[j] = dsp;
1330 peer->filter_epoch[j] = current_time;
1332 peer->filter_nextpt = j;
1335 * Update dispersions since the last update and at the same
1336 * time initialize the distance and index lists. The distance
1337 * list uses a compound metric. If the sample is valid and
1338 * younger than the minimum Allan intercept, use delay;
1339 * otherwise, use biased dispersion.
1341 dtemp = clock_phi * (current_time - peer->update);
1342 peer->update = current_time;
1343 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1345 peer->filter_disp[j] += dtemp;
1346 if (peer->filter_disp[j] > MAXDISPERSE)
1347 peer->filter_disp[j] = MAXDISPERSE;
1349 if (peer->filter_disp[j] >= MAXDISPERSE)
1350 dst[i] = MAXDISPERSE;
1351 else if (peer->update - peer->filter_epoch[j] >
1353 dst[i] = MAXDISTANCE + peer->filter_disp[j];
1355 dst[i] = peer->filter_delay[j];
1357 j++; j %= NTP_SHIFT;
1361 * Sort the samples in both lists by distance.
1363 for (i = 1; i < NTP_SHIFT; i++) {
1364 for (j = 0; j < i; j++) {
1365 if (dst[j] > dst[i]) {
1377 * Copy the index list to the association structure so ntpq
1378 * can see it later. Prune the distance list to samples less
1379 * than MAXDISTANCE, but keep at least two valid samples for
1380 * jitter calculation.
1383 for (i = 0; i < NTP_SHIFT; i++) {
1384 peer->filter_order[i] = ord[i];
1385 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1392 * Compute the dispersion and jitter squares. The dispersion
1393 * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1394 * normalized close to 1.0. The jitter is the mean of the square
1395 * differences relative to the lowest delay sample. If no
1396 * acceptable samples remain in the shift register, quietly
1397 * tiptoe home leaving only the
1403 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1406 peer->disp = NTP_FWEIGHT * (peer->disp +
1407 peer->filter_disp[j]);
1409 jit += DIFF(peer->filter_offset[j],
1410 peer->filter_offset[k]);
1414 * If no acceptable samples remain in the shift register,
1415 * quietly tiptoe home leaving only the dispersion. Otherwise,
1416 * save the offset, delay and jitter average. Note the jitter
1417 * must not be less than the system precision.
1421 etemp = peer->offset;
1422 peer->offset = peer->filter_offset[k];
1423 peer->delay = peer->filter_delay[k];
1426 peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1429 * A new sample is useful only if it is younger than the last
1432 if (peer->filter_epoch[k] <= peer->epoch) {
1435 printf("clock_filter: discard %lu\n",
1436 peer->epoch - peer->filter_epoch[k]);
1442 * If the difference between the last offset and the current one
1443 * exceeds the jitter by CLOCK_SGATE (4) and the interval since
1444 * the last update is less than twice the system poll interval,
1445 * consider the update a popcorn spike and ignore it.
1447 if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
1448 CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
1449 (1 << (sys_poll + 1))) {
1452 printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
1453 m, peer->offset, SQRT(peer->jitter));
1459 * The mitigated sample statistics are saved for later
1460 * processing, but can be processed only once.
1462 peer->epoch = peer->filter_epoch[k];
1463 peer->pollsw = TRUE;
1467 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1468 m, peer->offset, peer->delay, peer->disp,
1469 SQRT(peer->jitter), peer->update - peer->epoch);
1475 * clock_select - find the pick-of-the-litter clock
1480 register struct peer *peer;
1482 int nreach, nlist, nl3;
1484 int allow, found, sw;
1486 double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1487 struct peer *osys_peer;
1488 struct peer *typeacts = NULL;
1489 struct peer *typelocal = NULL;
1490 struct peer *typepps = NULL;
1491 struct peer *typesystem = NULL;
1493 static int list_alloc = 0;
1494 static struct endpoint *endpoint = NULL;
1495 static int *indx = NULL;
1496 static struct peer **peer_list = NULL;
1497 static u_int endpoint_size = 0;
1498 static u_int indx_size = 0;
1499 static u_int peer_list_size = 0;
1502 * Initialize and create endpoint, index and peer lists big
1503 * enough to handle all associations.
1505 osys_peer = sys_peer;
1511 for (n = 0; n < HASH_SIZE; n++)
1512 nlist += peer_hash_count[n];
1513 if (nlist > list_alloc) {
1514 if (list_alloc > 0) {
1519 while (list_alloc < nlist) {
1521 endpoint_size += 5 * 3 * sizeof(*endpoint);
1522 indx_size += 5 * 3 * sizeof(*indx);
1523 peer_list_size += 5 * sizeof(*peer_list);
1525 endpoint = (struct endpoint *)emalloc(endpoint_size);
1526 indx = (int *)emalloc(indx_size);
1527 peer_list = (struct peer **)emalloc(peer_list_size);
1531 * Initially, we populate the island with all the rifraff peers
1532 * that happen to be lying around. Those with seriously
1533 * defective clocks are immediately booted off the island. Then,
1534 * the falsetickers are culled and put to sea. The truechimers
1535 * remaining are subject to repeated rounds where the most
1536 * unpopular at each round is kicked off. When the population
1537 * has dwindled to NTP_MINCLOCK (3), the survivors split a
1538 * million bucks and collectively crank the chimes.
1540 nlist = nl3 = 0; /* none yet */
1541 for (n = 0; n < HASH_SIZE; n++) {
1542 for (peer = peer_hash[n]; peer != NULL; peer =
1544 peer->flags &= ~FLAG_SYSPEER;
1545 peer->status = CTL_PST_SEL_REJECT;
1548 * A peer leaves the island immediately if
1549 * unreachable, synchronized to us or suffers
1550 * excessive root distance. Careful with the
1551 * root distance, since the poll interval can
1552 * increase to a day and a half.
1554 if (!peer->reach || (peer->stratum > 1 &&
1556 peer->dstadr->sin.sin_addr.s_addr) ||
1557 peer->stratum >= STRATUM_UNSPEC ||
1558 (root_distance(peer) >= MAXDISTANCE + 2 *
1559 clock_phi * ULOGTOD(sys_poll)))
1563 * Don't allow the local clock or modem drivers
1564 * in the kitchen at this point, unless the
1565 * prefer peer. Do that later, but only if
1566 * nobody else is around. These guys are all
1567 * configured, so we never throw them away.
1569 if (peer->refclktype == REFCLK_LOCALCLOCK
1570 #if defined(VMS) && defined(VMS_LOCALUNIT)
1571 /* wjm: local unit VMS_LOCALUNIT taken seriously */
1572 && REFCLOCKUNIT(&peer->srcadr) != VMS_LOCALUNIT
1573 #endif /* VMS && VMS_LOCALUNIT */
1576 if (!(peer->flags & FLAG_PREFER))
1577 continue; /* no local clock */
1579 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1581 if (!(peer->flags & FLAG_PREFER))
1582 continue; /* no acts */
1586 * If we get this far, the peer can stay on the
1587 * island, but does not yet have the immunity
1591 peer->status = CTL_PST_SEL_SANE;
1592 peer_list[nlist++] = peer;
1595 * Insert each interval endpoint on the sorted
1598 e = peer->offset; /* Upper end */
1599 f = root_distance(peer);
1601 for (i = nl3 - 1; i >= 0; i--) {
1602 if (e >= endpoint[indx[i]].val)
1604 indx[i + 3] = indx[i];
1607 endpoint[nl3].type = 1;
1608 endpoint[nl3++].val = e;
1610 e = e - f; /* Center point */
1611 for ( ; i >= 0; i--) {
1612 if (e >= endpoint[indx[i]].val)
1614 indx[i + 2] = indx[i];
1617 endpoint[nl3].type = 0;
1618 endpoint[nl3++].val = e;
1620 e = e - f; /* Lower end */
1621 for ( ; i >= 0; i--) {
1622 if (e >= endpoint[indx[i]].val)
1624 indx[i + 1] = indx[i];
1627 endpoint[nl3].type = -1;
1628 endpoint[nl3++].val = e;
1633 for (i = 0; i < nl3; i++)
1634 printf("select: endpoint %2d %.6f\n",
1635 endpoint[indx[i]].type,
1636 endpoint[indx[i]].val);
1640 allow = nlist; /* falsetickers assumed */
1644 for (n = 0; i <= j; i++) {
1645 n += endpoint[indx[i]].type;
1648 if (endpoint[indx[i]].type == 0)
1651 for (n = 0; i <= j; j--) {
1652 n += endpoint[indx[j]].type;
1655 if (endpoint[indx[j]].type == 0)
1660 low = endpoint[indx[i++]].val;
1661 high = endpoint[indx[j--]].val;
1665 * If no survivors remain at this point, check if the local
1666 * clock or modem drivers have been found. If so, nominate one
1667 * of them as the only survivor. Otherwise, give up and declare
1668 * us unsynchronized.
1670 if ((allow << 1) >= nlist) {
1671 if (typeacts != 0) {
1672 typeacts->status = CTL_PST_SEL_SANE;
1673 peer_list[0] = typeacts;
1675 } else if (typelocal != 0) {
1676 typelocal->status = CTL_PST_SEL_SANE;
1677 peer_list[0] = typelocal;
1680 if (osys_peer != NULL) {
1681 sys_poll = NTP_MINPOLL;
1682 NLOG(NLOG_SYNCSTATUS)
1684 "synchronisation lost");
1685 report_event(EVNT_PEERSTCHG,
1691 #endif /* AUTOKEY */
1697 printf("select: low %.6f high %.6f\n", low, high);
1701 * Clustering algorithm. Construct candidate list in order first
1702 * by stratum then by root distance. If we have more than
1703 * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
1704 * list to find falsetickers, who leave the island immediately.
1705 * If a falseticker is not configured, his association raft is
1706 * drowned as well. We must leave at least one peer to collect
1707 * the million bucks.
1710 for (i = 0; i < nlist; i++) {
1711 peer = peer_list[i];
1712 if (nlist > 1 && (low >= peer->offset || peer->offset >=
1714 if (!(peer->flags & FLAG_CONFIG))
1718 peer->status = CTL_PST_SEL_DISTSYSPEER;
1719 d = root_distance(peer) + peer->stratum * MAXDISPERSE;
1720 if (j >= NTP_MAXCLOCK) {
1721 if (d >= synch[j - 1])
1726 for (k = j; k > 0; k--) {
1727 if (d >= synch[k - 1])
1729 peer_list[k] = peer_list[k - 1];
1730 error[k] = error[k - 1];
1731 synch[k] = synch[k - 1];
1733 peer_list[k] = peer;
1734 error[k] = peer->jitter;
1739 for (i = 0; i < nlist; i++) {
1740 peer_list[i]->status = CTL_PST_SEL_SELCAND;
1744 printf("select: %s distance %.6f\n",
1745 ntoa(&peer_list[i]->srcadr), synch[i]);
1750 * Now, vote outlyers off the island by select jitter weighted
1751 * by root dispersion. Continue voting as long as there are more
1752 * than NTP_MINCLOCK survivors and the minimum select jitter
1753 * squared is greater than the maximum peer jitter squared. Stop
1754 * if we are about to discard a prefer peer, who of course has
1755 * the immunity idol.
1761 for (i = 0; i < nlist; i++) {
1767 for (j = 0; j < nlist; j++)
1768 f += DIFF(peer_list[j]->offset,
1769 peer_list[i]->offset);
1772 f = max(f, SQUARE(LOGTOD(sys_precision)));
1773 if (f * synch[i] > e) {
1783 "select: survivors %d select %.6f peer %.6f\n",
1784 k, SQRT(sys_selerr), SQRT(d));
1786 if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
1787 peer_list[k]->flags & FLAG_PREFER)
1789 if (!(peer_list[k]->flags & FLAG_CONFIG))
1790 unpeer(peer_list[k]);
1791 for (j = k + 1; j < nlist; j++) {
1792 peer_list[j - 1] = peer_list[j];
1793 error[j - 1] = error[j];
1800 * In manycast client mode we may have spooked a sizeable number
1801 * of servers that we don't need. If there are at least
1802 * NTP_MINCLOCK of them, the manycast message will be turned
1803 * off. By the time we get here we nay be ready to prune some of
1804 * them back, but we want to make sure all the candicates have
1805 * had a chance. If they didn't pass the sanity and intersection
1806 * tests, they have already been voted off the island.
1808 if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
1810 #endif /* AUTOKEY */
1811 sys_survivors = nlist;
1815 for (i = 0; i < nlist; i++)
1817 "select: %s offset %.6f, distance %.6f poll %d\n",
1818 ntoa(&peer_list[i]->srcadr),
1819 peer_list[i]->offset, synch[i],
1820 peer_list[i]->pollsw);
1825 * What remains is a list of not greater than NTP_MINCLOCK
1826 * peers. We want only a peer at the lowest stratum to become
1827 * the system peer, although all survivors are eligible for the
1828 * combining algorithm. First record their order, diddle the
1829 * flags and clamp the poll intervals. Then, consider the peers
1830 * at the lowest stratum. Of these, OR the leap bits on the
1831 * assumption that, if some of them honk nonzero bits, they must
1832 * know what they are doing. Also, check for prefer and pps
1833 * peers. If a prefer peer is found within clock_max, update the
1834 * pps switch. Of the other peers not at the lowest stratum,
1835 * check if the system peer is among them and, if found, zap
1836 * him. We note that the head of the list is at the lowest
1837 * stratum and that unsynchronized peers cannot survive this
1840 * Note that we go no further, unless the number of survivors is
1841 * a majority of the suckers that have been found reachable and
1842 * no prior source is available. This avoids the transient when
1843 * one of a flock of sources is out to lunch and just happens
1844 * to be the first survivor.
1846 if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
1849 for (i = nlist - 1; i >= 0; i--) {
1850 peer = peer_list[i];
1851 peer->status = CTL_PST_SEL_SYNCCAND;
1852 peer->flags |= FLAG_SYSPEER;
1853 poll_update(peer, peer->hpoll);
1854 if (peer->stratum == peer_list[0]->stratum) {
1855 leap_consensus |= peer->leap;
1856 if (peer->refclktype == REFCLK_ATOM_PPS &&
1857 peer->stratum < STRATUM_UNSPEC)
1859 if (peer == osys_peer)
1861 if (peer->flags & FLAG_PREFER)
1867 * Mitigation rules of the game. There are several types of
1868 * peers that make a difference here: (1) prefer local peers
1869 * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
1870 * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
1871 * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
1872 * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
1873 * the head of the survivor list. Note that only one peer can be
1874 * declared prefer. The order of preference is in the order
1875 * stated. Note that all of these must be at the lowest stratum,
1876 * i.e., the stratum of the head of the survivor list.
1879 sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
1880 sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
1885 sys_peer = sys_prefer;
1886 sys_peer->status = CTL_PST_SEL_SYSPEER;
1887 sys_offset = sys_peer->offset;
1888 sys_syserr = sys_peer->jitter;
1891 printf("select: prefer offset %.6f\n",
1894 } else if (typepps) {
1896 sys_peer->status = CTL_PST_SEL_PPS;
1897 sys_offset = sys_peer->offset;
1898 sys_syserr = sys_peer->jitter;
1902 "pps sync enabled");
1903 pps_control = current_time;
1906 printf("select: pps offset %.6f\n",
1911 sys_peer = osys_peer;
1913 sys_peer = peer_list[0];
1914 sys_peer->status = CTL_PST_SEL_SYSPEER;
1915 sys_offset = clock_combine(peer_list, nlist);
1916 sys_syserr = sys_peer->jitter + sys_selerr;
1919 printf("select: combine offset %.6f\n",
1923 if (osys_peer != sys_peer)
1924 report_event(EVNT_PEERSTCHG, (struct peer *)0);
1929 * clock_combine - combine offsets from selected peers
1933 struct peer **peers,
1940 for (i = 0; i < npeers; i++) {
1941 x = root_distance(peers[i]);
1943 z += peers[i]->offset / x;
1949 * root_distance - compute synchronization distance from peer to root
1957 * Careful squeak here. The value returned must be greater than
1958 * zero blamed on the peer jitter, which must be at least the
1959 * square of sys_precision.
1961 return ((peer->rootdelay + peer->delay) / 2 +
1962 peer->rootdispersion + peer->disp + clock_phi *
1963 (current_time - peer->update) + SQRT(peer->jitter));
1967 * peer_xmit - send packet for persistent association.
1971 struct peer *peer /* peer structure pointer */
1974 struct pkt xpkt; /* transmit packet */
1975 int sendlen, authlen;
1976 keyid_t xkeyid; /* transmit key ID */
1980 * Initialize transmit packet header fields.
1982 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
1984 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
1985 xpkt.ppoll = peer->hpoll;
1986 xpkt.precision = sys_precision;
1987 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
1988 xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
1989 xpkt.refid = sys_refid;
1990 HTONL_FP(&sys_reftime, &xpkt.reftime);
1991 HTONL_FP(&peer->org, &xpkt.org);
1992 HTONL_FP(&peer->rec, &xpkt.rec);
1995 * If the received packet contains a MAC, the transmitted packet
1996 * is authenticated and contains a MAC. If not, the transmitted
1997 * packet is not authenticated.
1999 * In the current I/O semantics the default interface is set
2000 * until after receiving a packet and setting the right
2001 * interface. So, the first packet goes out unauthenticated.
2002 * That's why the really icky test next is here.
2004 sendlen = LEN_PKT_NOMAC;
2005 if (!(peer->flags & FLAG_AUTHENABLE)) {
2006 get_systime(&peer->xmt);
2007 HTONL_FP(&peer->xmt, &xpkt.xmt);
2008 sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
2013 printf("transmit: at %ld %s->%s mode %d\n",
2014 current_time, ntoa(&peer->dstadr->sin),
2015 ntoa(&peer->srcadr), peer->hmode);
2021 * The received packet contains a MAC, so the transmitted packet
2022 * must be authenticated. If autokey is enabled, fuss with the
2023 * various modes; otherwise, private key cryptography is used.
2026 if ((peer->flags & FLAG_SKEY)) {
2030 * The Public Key Dance (PKD): Cryptographic credentials
2031 * are contained in extension fields, each including a
2032 * 4-octet length/code word followed by a 4-octet
2033 * association ID and optional additional data. Optional
2034 * data includes a 4-octet data length field followed by
2035 * the data itself. Request messages are sent from a
2036 * configured association; response messages can be sent
2037 * from a configured association or can take the fast
2038 * path without ever matching an association. Response
2039 * messages have the same code as the request, but have
2040 * a response bit and possibly an error bit set. In this
2041 * implementation, a message may contain no more than
2042 * one command and no more than one response.
2044 * Cryptographic session keys include both a public and
2045 * a private componet. Request and response messages
2046 * using extension fields are always sent with the
2047 * private component set to zero. Packets without
2048 * extension fields indlude the private component when
2049 * the session key is generated.
2054 * Allocate and initialize a keylist if not
2055 * already done. Then, use the list in inverse
2056 * order, discarding keys once used. Keep the
2057 * latest key around until the next one, so
2058 * clients can use client/server packets to
2059 * compute propagation delay.
2061 * Note that once a key is used from the list,
2062 * it is retained in the key cache until the
2063 * next key is used. This is to allow a client
2064 * to retrieve the encrypted session key
2065 * identifier to verify authenticity.
2067 * If for some reason a key is no longer in the
2068 * key cache, a birthday has happened and the
2069 * pseudo-random sequence is probably broken. In
2070 * that case, purge the keylist and regenerate
2073 if (peer->keynumber == 0)
2074 make_keylist(peer, peer->dstadr);
2077 xkeyid = peer->keylist[peer->keynumber];
2078 if (authistrusted(xkeyid))
2083 peer->keyid = xkeyid;
2084 switch (peer->hmode) {
2087 * In broadcast mode the autokey values are required.
2088 * Send them when a new keylist is generated; otherwise,
2089 * send the association ID so the client can request
2090 * them at other times.
2092 case MODE_BROADCAST:
2093 if (peer->flags & FLAG_ASSOC)
2094 cmmd = CRYPTO_AUTO | CRYPTO_RESP;
2096 cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
2097 sendlen += crypto_xmit((u_int32 *)&xpkt,
2098 sendlen, cmmd, 0, peer->associd);
2102 * In symmetric modes the public key, leapsecond table,
2103 * agreement parameters and autokey values are required.
2105 * 1. If a response is pending, always send it first.
2107 * 2. Don't send anything except a public-key request
2108 * until the public key has been stored.
2110 * 3. Once the public key has been stored, don't send
2111 * anything except an agreement parameter request
2112 * until the agreement parameters have been stored.
2114 * 4. Once the argeement parameters have been stored,
2115 * don't send anything except a public value request
2116 * until the agreed key has been stored.
2118 * 5. When the agreed key has been stored and the key
2119 * list is regenerated, send the autokey values
2120 * gratis unless they have already been sent.
2125 if (peer->cmmd != 0)
2126 sendlen += crypto_xmit((u_int32 *)&xpkt,
2127 sendlen, (peer->cmmd >> 16) |
2128 CRYPTO_RESP, peer->hcookie,
2131 sendlen += crypto_xmit((u_int32 *)&xpkt,
2132 sendlen, CRYPTO_ASSOC,
2133 peer->hcookie, peer->assoc);
2134 else if (!crypto_flags &&
2135 peer->pcookie.tstamp == 0 && sys_leap !=
2137 sendlen += crypto_xmit((u_int32 *)&xpkt,
2138 sendlen, CRYPTO_PRIV, peer->hcookie,
2140 else if (crypto_flags && peer->pubkey.ptr ==
2142 sendlen += crypto_xmit((u_int32 *)&xpkt,
2143 sendlen, CRYPTO_NAME, peer->hcookie,
2145 else if (peer->crypto & CRYPTO_FLAG_CERT)
2146 sendlen += crypto_xmit((u_int32 *)&xpkt,
2147 sendlen, CRYPTO_CERT, peer->hcookie,
2149 else if (crypto_flags && peer->crypto &
2150 CRYPTO_FLAG_DH && sys_leap !=
2152 sendlen += crypto_xmit((u_int32 *)&xpkt,
2153 sendlen, CRYPTO_DHPAR,
2154 peer->hcookie, peer->assoc);
2155 else if (crypto_flags && peer->pcookie.tstamp ==
2156 0 && sys_leap != LEAP_NOTINSYNC)
2157 sendlen += crypto_xmit((u_int32 *)&xpkt,
2158 sendlen, CRYPTO_DH, peer->hcookie,
2161 if (peer->cmmd != 0)
2162 sendlen += crypto_xmit((u_int32 *)&xpkt,
2163 sendlen, (peer->cmmd >> 16) |
2164 CRYPTO_RESP, peer->hcookie,
2166 if (peer->pcookie.tstamp == 0 && sys_leap !=
2168 sendlen += crypto_xmit((u_int32 *)&xpkt,
2169 sendlen, CRYPTO_PRIV, peer->hcookie,
2172 else if (!(peer->flags & FLAG_AUTOKEY))
2173 sendlen += crypto_xmit((u_int32 *)&xpkt,
2174 sendlen, CRYPTO_AUTO, peer->hcookie,
2176 else if ((peer->flags & FLAG_ASSOC) &&
2177 (peer->cmmd >> 16) != CRYPTO_AUTO)
2178 sendlen += crypto_xmit((u_int32 *)&xpkt,
2179 sendlen, CRYPTO_AUTO | CRYPTO_RESP,
2180 peer->hcookie, peer->associd);
2182 else if (peer->crypto & CRYPTO_FLAG_TAI)
2183 sendlen += crypto_xmit((u_int32 *)&xpkt,
2184 sendlen, CRYPTO_TAI, peer->hcookie,
2191 * In client mode, the public key, host cookie and
2192 * autokey values are required. In broadcast client
2193 * mode, these values must be acquired during the
2194 * client/server exchange to avoid having to wait until
2195 * the next key list regeneration. Otherwise, the poor
2196 * dude may die a lingering death until becoming
2197 * unreachable and attempting rebirth. Note that we ask
2198 * for the cookie at each key list regeneration anyway.
2201 if (peer->cmmd != 0)
2202 sendlen += crypto_xmit((u_int32 *)&xpkt,
2203 sendlen, (peer->cmmd >> 16) |
2204 CRYPTO_RESP, peer->hcookie,
2207 sendlen += crypto_xmit((u_int32 *)&xpkt,
2208 sendlen, CRYPTO_ASSOC,
2209 peer->hcookie, peer->assoc);
2211 else if (crypto_flags && peer->pubkey.ptr ==
2213 sendlen += crypto_xmit((u_int32 *)&xpkt,
2214 sendlen, CRYPTO_NAME, peer->hcookie,
2216 else if (peer->crypto & CRYPTO_FLAG_CERT)
2217 sendlen += crypto_xmit((u_int32 *)&xpkt,
2218 sendlen, CRYPTO_CERT, peer->hcookie,
2221 else if (peer->pcookie.tstamp == 0)
2222 sendlen += crypto_xmit((u_int32 *)&xpkt,
2223 sendlen, CRYPTO_PRIV, peer->hcookie,
2225 else if (!(peer->flags & FLAG_AUTOKEY) &&
2226 (peer->cast_flags & MDF_BCLNT))
2227 sendlen += crypto_xmit((u_int32 *)&xpkt,
2228 sendlen, CRYPTO_AUTO, peer->hcookie,
2231 else if (peer->crypto & CRYPTO_FLAG_TAI)
2232 sendlen += crypto_xmit((u_int32 *)&xpkt,
2233 sendlen, CRYPTO_TAI, peer->hcookie,
2241 * If extension fields are present, we must use a
2242 * private value of zero and force min poll interval.
2245 if (sendlen > LEN_PKT_NOMAC)
2246 session_key(&peer->dstadr->sin, &peer->srcadr,
2249 #endif /* AUTOKEY */
2250 xkeyid = peer->keyid;
2251 get_systime(&peer->xmt);
2252 L_ADD(&peer->xmt, &sys_authdelay);
2253 HTONL_FP(&peer->xmt, &xpkt.xmt);
2254 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2257 "transmit: no encryption key found");
2258 peer->flash |= TEST4 | TEST5;
2263 if (xkeyid > NTP_MAXKEY)
2264 authtrust(xkeyid, 0);
2265 #endif /* AUTOKEY */
2266 get_systime(&xmt_tx);
2267 if (sendlen > sizeof(xpkt)) {
2268 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2271 sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
2274 * Calculate the encryption delay. Keep the minimum over
2275 * the latest two samples.
2277 L_SUB(&xmt_tx, &peer->xmt);
2278 L_ADD(&xmt_tx, &sys_authdelay);
2279 sys_authdly[1] = sys_authdly[0];
2280 sys_authdly[0] = xmt_tx.l_uf;
2281 if (sys_authdly[0] < sys_authdly[1])
2282 sys_authdelay.l_uf = sys_authdly[0];
2284 sys_authdelay.l_uf = sys_authdly[1];
2290 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2291 current_time, ntoa(&peer->dstadr->sin),
2292 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2293 authlen, peer->keynumber);
2299 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2300 current_time, ntoa(&peer->dstadr->sin),
2301 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2304 #endif /* AUTOKEY */
2309 * fast_xmit - Send packet for nonpersistent association. Note that
2310 * neither the source or destination can be a broadcast address.
2314 struct recvbuf *rbufp, /* receive packet pointer */
2315 int xmode, /* transmit mode */
2316 keyid_t xkeyid, /* transmit key ID */
2317 int mask /* restrict mask */
2320 struct pkt xpkt; /* transmit packet structure */
2321 struct pkt *rpkt; /* receive packet structure */
2322 l_fp xmt_ts; /* transmit timestamp */
2323 l_fp xmt_tx; /* transmit timestamp after authent */
2324 int sendlen, authlen;
2327 * Initialize transmit packet header fields from the receive
2328 * buffer provided. We leave some fields intact as received. If
2329 * the gazinta was from a multicast address, the gazouta must go
2332 rpkt = &rbufp->recv_pkt;
2333 if (rbufp->dstadr->flags & INT_MULTICAST)
2334 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2337 * If the caller is restricted, return a kiss-of-death packet;
2338 * otherwise, smooch politely.
2340 if (mask & (RES_DONTSERVE | RES_LIMITED)) {
2341 if (!(mask & RES_DEMOBILIZE)) {
2345 PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2346 PKT_VERSION(rpkt->li_vn_mode), xmode);
2347 xpkt.stratum = STRATUM_UNSPEC;
2348 memcpy(&xpkt.refid, "DENY", 4);
2351 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2352 PKT_VERSION(rpkt->li_vn_mode), xmode);
2353 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2354 xpkt.refid = sys_refid;
2356 xpkt.ppoll = rpkt->ppoll;
2357 xpkt.precision = sys_precision;
2358 xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2359 xpkt.rootdispersion =
2360 HTONS_FP(DTOUFP(sys_rootdispersion));
2361 HTONL_FP(&sys_reftime, &xpkt.reftime);
2362 xpkt.org = rpkt->xmt;
2363 HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2366 * If the received packet contains a MAC, the transmitted packet
2367 * is authenticated and contains a MAC. If not, the transmitted
2368 * packet is not authenticated.
2370 sendlen = LEN_PKT_NOMAC;
2371 if (rbufp->recv_length == sendlen) {
2372 get_systime(&xmt_ts);
2373 HTONL_FP(&xmt_ts, &xpkt.xmt);
2374 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2378 printf("transmit: at %ld %s->%s mode %d\n",
2379 current_time, ntoa(&rbufp->dstadr->sin),
2380 ntoa(&rbufp->recv_srcadr), xmode);
2386 * The received packet contains a MAC, so the transmitted packet
2387 * must be authenticated. For private-key cryptography, use the
2388 * predefined private keys to generate the cryptosum. For
2389 * autokey cryptography, use the server private value to
2390 * generate the cookie, which is unique for every source-
2391 * destination-key ID combination.
2394 if (xkeyid > NTP_MAXKEY) {
2396 u_int code, associd;
2399 * The only way to get here is a reply to a legitimate
2400 * client request message, so the mode must be
2401 * MODE_SERVER. If an extension field is present, there
2402 * can be only one and that must be a command. Do what
2403 * needs, but with private value of zero so the poor
2404 * jerk can decode it. If no extension field is present,
2405 * use the cookie to generate the session key.
2407 code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
2408 cookie = session_key(&rbufp->recv_srcadr,
2409 &rbufp->dstadr->sin, 0, sys_private, 0);
2410 associd = htonl(rpkt->exten[1]);
2411 if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
2413 session_key(&rbufp->dstadr->sin,
2414 &rbufp->recv_srcadr, xkeyid, 0, 2);
2415 sendlen += crypto_xmit((u_int32 *)&xpkt,
2416 sendlen, code, cookie, associd);
2418 session_key(&rbufp->dstadr->sin,
2419 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2422 #endif /* AUTOKEY */
2423 get_systime(&xmt_ts);
2424 L_ADD(&xmt_ts, &sys_authdelay);
2425 HTONL_FP(&xmt_ts, &xpkt.xmt);
2426 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2429 if (xkeyid > NTP_MAXKEY)
2430 authtrust(xkeyid, 0);
2431 #endif /* AUTOKEY */
2432 get_systime(&xmt_tx);
2433 if (sendlen > sizeof(xpkt)) {
2434 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2437 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2440 * Calculate the encryption delay. Keep the minimum over the
2441 * latest two samples.
2443 L_SUB(&xmt_tx, &xmt_ts);
2444 L_ADD(&xmt_tx, &sys_authdelay);
2445 sys_authdly[1] = sys_authdly[0];
2446 sys_authdly[0] = xmt_tx.l_uf;
2447 if (sys_authdly[0] < sys_authdly[1])
2448 sys_authdelay.l_uf = sys_authdly[0];
2450 sys_authdelay.l_uf = sys_authdly[1];
2454 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2455 current_time, ntoa(&rbufp->dstadr->sin),
2456 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
2464 * key_expire - purge the key list
2468 struct peer *peer /* peer structure pointer */
2473 if (peer->keylist != NULL) {
2474 for (i = 0; i <= peer->keynumber; i++)
2475 authtrust(peer->keylist[i], 0);
2476 free(peer->keylist);
2477 peer->keylist = NULL;
2479 peer->keynumber = peer->sndauto.seq = 0;
2482 printf("key_expire: at %lu\n", current_time);
2485 #endif /* AUTOKEY */
2488 * Find the precision of this particular machine
2490 #define DUSECS 1000000 /* us in a s */
2491 #define HUSECS (1 << 20) /* approx DUSECS for shifting etc */
2492 #define MINSTEP 5 /* minimum clock increment (us) */
2493 #define MAXSTEP 20000 /* maximum clock increment (us) */
2494 #define MINLOOPS 5 /* minimum number of step samples */
2497 * This routine calculates the differences between successive calls to
2498 * gettimeofday(). If a difference is less than zero, the us field
2499 * has rolled over to the next second, so we add a second in us. If
2500 * the difference is greater than zero and less than MINSTEP, the
2501 * clock has been advanced by a small amount to avoid standing still.
2502 * If the clock has advanced by a greater amount, then a timer interrupt
2503 * has occurred and this amount represents the precision of the clock.
2504 * In order to guard against spurious values, which could occur if we
2505 * happen to hit a fat interrupt, we do this for MINLOOPS times and
2506 * keep the minimum value obtained.
2509 default_get_precision(void)
2512 #if !defined(SYS_WINNT) && !defined(VMS) && !defined(_SEQUENT_)
2513 struct timezone tzp;
2514 #elif defined(VMS) || defined(_SEQUENT_)
2519 #endif /* defined(VMS) || defined(_SEQUENT_) */
2525 #ifdef HAVE_GETCLOCK
2528 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
2532 /* Try to see if we can find the frequency of of the counter
2533 * which drives our timekeeping
2536 i = sysctlbyname("kern.timecounter.frequency", &freq, &j , 0,
2539 i = sysctlbyname("machdep.tsc_freq", &freq, &j , 0, 0);
2541 i = sysctlbyname("machdep.i586_freq", &freq, &j , 0, 0);
2543 i = sysctlbyname("machdep.i8254_freq", &freq, &j , 0,
2546 for (i = 1; freq ; i--)
2553 #ifdef HAVE_GETCLOCK
2554 (void) getclock(TIMEOFDAY, &ts);
2555 tp.tv_sec = ts.tv_sec;
2556 tp.tv_usec = ts.tv_nsec / 1000;
2557 #else /* not HAVE_GETCLOCK */
2558 GETTIMEOFDAY(&tp, &tzp);
2559 #endif /* not HAVE_GETCLOCK */
2561 for (i = 0; i < MINLOOPS && usec < HUSECS;) {
2562 #ifdef HAVE_GETCLOCK
2563 (void) getclock(TIMEOFDAY, &ts);
2564 tp.tv_sec = ts.tv_sec;
2565 tp.tv_usec = ts.tv_nsec / 1000;
2566 #else /* not HAVE_GETCLOCK */
2567 GETTIMEOFDAY(&tp, &tzp);
2568 #endif /* not HAVE_GETCLOCK */
2569 diff = tp.tv_usec - last;
2574 if (diff > MINSTEP) {
2581 msyslog(LOG_INFO, "precision = %ld usec", val);
2583 val = MINSTEP; /* val <= MINSTEP; fast machine */
2585 for (i = 0; diff > val; i--)
2591 * init_proto - initialize the protocol module's data
2599 * Fill in the sys_* stuff. Default is don't listen to
2600 * broadcasting, authenticate.
2602 sys_leap = LEAP_NOTINSYNC;
2603 sys_stratum = STRATUM_UNSPEC;
2604 sys_precision = (s_char)default_get_precision();
2605 sys_jitter = LOGTOD(sys_precision);
2607 sys_rootdispersion = 0;
2609 L_CLR(&sys_reftime);
2612 get_systime(&dummy);
2614 sys_bdelay = DEFBROADDELAY;
2615 sys_authenticate = 1;
2616 L_CLR(&sys_authdelay);
2617 sys_authdly[0] = sys_authdly[1] = 0;
2620 sys_oldversionpkt = 0;
2621 sys_newversionpkt = 0;
2623 sys_unknownversion = 0;
2626 sys_manycastserver = 0;
2628 sys_automax = 1 << NTP_AUTOMAX;
2629 #endif /* AUTOKEY */
2632 * Default these to enable
2635 #ifndef KERNEL_FLL_BUG
2642 * Some system clocks should only be adjusted in 10ms
2645 #if defined RELIANTUNIX_CLOCK
2646 systime_10ms_ticks = 1; /* Reliant UNIX */
2647 #elif defined SCO5_CLOCK
2648 if (sys_precision >= (s_char)-10) /* pre-SCO OpenServer 5.0.6 */
2649 systime_10ms_ticks = 1;
2651 if (systime_10ms_ticks)
2652 msyslog(LOG_INFO, "using 10ms tick adjustments");
2657 * proto_config - configure the protocol module
2667 * Figure out what he wants to change, then do it
2673 * Turn on/off kernel discipline
2675 kern_enable = (int)value;
2681 * Turn on/off clock discipline
2683 ntp_enable = (int)value;
2689 * Turn on/off monitoring
2700 * Turn on/off statistics
2702 stats_control = (int)value;
2705 case PROTO_BROADCLIENT:
2708 * Turn on/off facility to listen to broadcasts
2710 sys_bclient = (int)value;
2717 case PROTO_MULTICAST_ADD:
2720 * Add muliticast group address
2722 io_multicast_add(value);
2725 case PROTO_MULTICAST_DEL:
2728 * Delete multicast group address
2730 io_multicast_del(value);
2733 case PROTO_BROADDELAY:
2736 * Set default broadcast delay
2738 sys_bdelay = dvalue;
2741 case PROTO_AUTHENTICATE:
2744 * Specify the use of authenticated data
2746 sys_authenticate = (int)value;
2752 * Turn on/off PPS discipline
2754 pps_enable = (int)value;
2761 * Turn on/off refclock calibrate
2763 cal_enable = (int)value;
2773 "proto_config: illegal item %d, value %ld",
2781 * proto_clr_stats - clear protocol stat counters
2784 proto_clr_stats(void)
2787 sys_oldversionpkt = 0;
2788 sys_newversionpkt = 0;
2789 sys_unknownversion = 0;
2793 sys_stattime = current_time;
2794 sys_limitrejected = 0;