4c4
< * $FreeBSD: head/contrib/ntp/ntpd/ntp_proto.c 56749 2000-01-28 15:02:35Z roberto $
---
> * $FreeBSD: head/contrib/ntp/ntpd/ntp_proto.c 82505 2001-08-29 15:15:59Z roberto $
10,13d9
< #include <stdio.h>
< #include <sys/types.h>
< #include <sys/time.h>
<
18a15
> #include "ntp_crypto.h"
19a17,18
> #include <stdio.h>
>
29c28
< * System variables are declared here. See Section 3.2 of the
---
> * System variables are declared here. See Section 3.2 of the
35,36c34,35
< double sys_rootdelay; /* distance to current sync source */
< double sys_rootdispersion; /* dispersion of system clock */
---
> double sys_rootdelay; /* roundtrip delay to primary source */
> double sys_rootdispersion; /* dispersion to primary source */
40a40,41
> struct peer *sys_prefer; /* our cherished peer */
> #ifdef AUTOKEY
41a43
> #endif /* AUTOKEY */
52,55c54,62
< static double sys_maxd; /* select error (squares) */
< static double sys_epsil; /* system error (squares) */
< u_long sys_private; /* private value for session seed */
< int sys_manycastserver; /* 1 => respond to manycast client pkts */
---
> static double sys_selerr; /* select error (squares) */
> static double sys_syserr; /* system error (squares) */
> keyid_t sys_private; /* private value for session seed */
> int sys_manycastserver; /* respond to manycast client pkts */
> u_int sys_survivors; /* truest of the truechimers */
> int peer_ntpdate; /* active peers in ntpdate mode */
> #ifdef AUTOKEY
> char *sys_hostname; /* gethostname() name */
> #endif /* AUTOKEY */
73c80
< static void fast_xmit P((struct recvbuf *, int, u_long));
---
> static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
76,78d82
< #ifdef MD5
< static void make_keylist P((struct peer *));
< #endif /* MD5 */
79a84
>
96,99c101,104
< * Determine reachability and diddle things if we
< * haven't heard from the host for a while. If the peer
< * is not configured and not likely to stay around,
< * we exhaust it.
---
> * The polling state machine. There are two kinds of
> * machines, those that never expect a reply (broadcast
> * and manycast server modes) and those that do (all
> * other modes). The dance is intricate...
100a106,163
> if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
>
> /*
> * In broadcast mode the poll interval is fixed
> * at minpoll and the ttl at ttlmax.
> */
> hpoll = peer->minpoll;
> peer->ttl = peer->ttlmax;
> #ifdef AUTOKEY
> } else if (peer->cast_flags & MDF_ACAST) {
>
> /*
> * In manycast mode we start with the minpoll
> * interval and ttl. However, the actual poll
> * interval is eight times the nominal poll
> * interval shown here. If fewer than three
> * servers are found, the ttl is increased by
> * one and we try again. If this continues to
> * the max ttl, the poll interval is bumped by
> * one and we try again. If at least three
> * servers are found, the poll interval
> * increases with the system poll interval to
> * the max and we continue indefinately.
> * However, about once per day when the
> * agreement parameters are refreshed, the
> * manycast clients are reset and we start from
> * the beginning. This is to catch and clamp the
> * ttl to the lowest practical value and avoid
> * knocking on spurious doors.
> */
> if (sys_survivors < NTP_MINCLOCK && peer->ttl <
> peer->ttlmax)
> peer->ttl++;
> hpoll = sys_poll;
> #endif /* AUTOKEY */
> } else {
>
> /*
> * For associations expecting a reply, the
> * watchdog counter is bumped by one if the peer
> * has not been heard since the previous poll.
> * If the counter reaches the max, the peer is
> * demobilized if not configured and just
> * cleared if it is, but in this case the poll
> * interval is bumped by one.
> */
> if (peer->unreach < NTP_UNREACH) {
> peer->unreach++;
> } else if (!(peer->flags & FLAG_CONFIG)) {
> unpeer(peer);
> clock_select();
> return;
>
> } else {
> peer_clear(peer);
> hpoll++;
> }
> }
102,109d164
< if (oreach & 0x01)
< peer->valid++;
< if (oreach & 0x80)
< peer->valid--;
< if (!(peer->flags & FLAG_CONFIG) && peer->valid >
< NTP_SHIFT / 2 && (peer->reach & 0x80) &&
< peer->status < CTL_PST_SEL_SYNCCAND)
< peer->reach = 0;
114,115c169,170
< * If this is an uncofigured association and
< * has become unreachable, demobilize it.
---
> * If this association has become unreachable,
> * clear it and raise a trap.
120d174
< peer_clear(peer);
122a177
> clock_select();
123a179,181
> } else {
> peer_clear(peer);
> hpoll = peer->minpoll;
126,146c184,185
<
< /*
< * We would like to respond quickly when the
< * peer comes back to life. If the probes since
< * becoming unreachable are less than
< * NTP_UNREACH, clamp the poll interval to the
< * minimum. In order to minimize the network
< * traffic, the interval gradually ramps up the
< * the maximum after that.
< */
< peer->ppoll = peer->maxpoll;
< if (peer->unreach < NTP_UNREACH) {
< if (peer->hmode == MODE_CLIENT)
< peer->unreach++;
< hpoll = peer->minpoll;
< } else {
< hpoll++;
< }
< if (peer->flags & FLAG_BURST)
< peer->burst = 2;
<
---
> if (peer->flags & FLAG_IBURST)
> peer->burst = NTP_SHIFT;
150,156c189,198
< * Here the peer is reachable. If there is no
< * system peer or if the stratum of the system
< * peer is greater than this peer, clamp the
< * poll interval to the minimum. If less than
< * two samples are in the reachability register,
< * reduce the interval; if more than six samples
< * are in the register, increase the interval.
---
> * Here the peer is reachable. If it has not
> * been heard for three consecutive polls, stuff
> * the clock filter. Next, determine the poll
> * interval. If the peer is a synchronization
> * candidate, use the system poll interval. If
> * the peer is not sane, increase it by one. If
> * the number of valid updates is not greater
> * than half the register size, clamp it to the
> * minimum. This is to quickly recover the time
> * variables when a noisy peer shows life.
158,163c200
< peer->unreach = 0;
< if (sys_peer == 0)
< hpoll = peer->minpoll;
< else if (sys_peer->stratum > peer->stratum)
< hpoll = peer->minpoll;
< if ((peer->reach & 0x03) == 0) {
---
> if (!(peer->reach & 0x07)) {
167,169c204,206
< if (peer->valid <= 2)
< hpoll--;
< else if (peer->valid >= NTP_SHIFT - 2)
---
> if ((peer->stratum > 1 && peer->refid ==
> peer->dstadr->sin.sin_addr.s_addr) ||
> peer->stratum >= STRATUM_UNSPEC)
170a208,209
> else
> hpoll = sys_poll;
177,178c216,223
< if (peer->flags & FLAG_MCAST2) {
< peer->flags &= ~FLAG_BURST;
---
>
> /*
> * If a broadcast client at this point, the
> * burst has concluded, so we switch to client
> * mode and purge the keylist, since no further
> * transmissions will be made.
> */
> if (peer->cast_flags & MDF_BCLNT) {
179a225,227
> #ifdef AUTOKEY
> key_expire(peer);
> #endif /* AUTOKEY */
181d228
< clock_select();
182a230,247
> clock_select();
>
> /*
> * If ntpdate mode and the clock has not been
> * set and all peers have completed the burst,
> * we declare a successful failure.
> */
> if (mode_ntpdate) {
> peer_ntpdate--;
> if (peer_ntpdate > 0)
> return;
> NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
> msyslog(LOG_NOTICE,
> "no reply; clock not set");
> printf(
> "ntpd: no reply; clock not set\n");
> exit(0);
> }
183a249
>
185a252,253
> peer->outdate = current_time;
> poll_update(peer, hpoll);
188,194c256,259
< * We need to be very careful about honking uncivilized time. If
< * not operating in broadcast mode, honk in all except broadcast
< * client mode. If operating in broadcast mode and synchronized
< * to a real source, honk except when the peer is the local-
< * clock driver and the prefer flag is not set. In other words,
< * in broadcast mode we never honk unless known to be
< * synchronized to real time.
---
> * We need to be very careful about honking uncivilized time.
> * Never transmit if in broadcast client mode or access denied.
> * If in broadcast mode, transmit only if synchronized to a
> * valid source.
196,202c261,265
< if (peer->hmode != MODE_BROADCAST) {
< if (peer->hmode != MODE_BCLIENT)
< peer_xmit(peer);
< } else if (sys_peer != 0 && sys_leap != LEAP_NOTINSYNC) {
< if (!(sys_peer->refclktype == REFCLK_LOCALCLOCK &&
< !(sys_peer->flags & FLAG_PREFER)))
< peer_xmit(peer);
---
> if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
> return;
> } else if (peer->hmode == MODE_BROADCAST) {
> if (sys_peer == NULL)
> return;
204,205c267
< peer->outdate = current_time;
< poll_update(peer, hpoll);
---
> peer_xmit(peer);
221,222c283,284
< int has_mac; /* has MAC field */
< int authlen; /* length of MAC field */
---
> int has_mac; /* length of MAC field */
> int authlen; /* offset of MAC field */
224,227c286,290
< int is_mystic; /* session key exists */
< int is_error; /* parse error */
< /* u_long pkeyid; */
< u_long skeyid, tkeyid;
---
> keyid_t skeyid; /* cryptographic keys */
> struct sockaddr_in *dstadr_sin; /* active runway */
> #ifdef AUTOKEY
> keyid_t pkeyid, tkeyid; /* cryptographic keys */
> #endif /* AUTOKEY */
232c295,302
< * Monitor the packet and get restrictions
---
> * Monitor the packet and get restrictions. Note that the packet
> * length for control and private mode packets must be checked
> * by the service routines. Note that no statistics counters are
> * recorded for restrict violations, since these counters are in
> * the restriction routine. Note the careful distinctions here
> * between a packet with a format error and a packet that is
> * simply discarded without prejudice. Some restrictions have to
> * be handled later in order to generate a kiss-of-death packet.
237,238c307,309
< if (debug > 1)
< printf("receive: from %s restrict %02x\n",
---
> if (debug > 2)
> printf("receive: at %ld %s<-%s restrict %02x\n",
> current_time, ntoa(&rbufp->dstadr->sin),
242,246c313,318
< return;
<
< /*
< * Discard packets with invalid version number.
< */
---
> return; /* no anything */
> if (!(SRCPORT(&rbufp->recv_srcadr) == NTP_PORT ||
> SRCPORT(&rbufp->recv_srcadr) >= IPPORT_RESERVED)) {
> sys_badlength++;
> return; /* invalid port */
> }
248,252c320,325
< if (PKT_VERSION(pkt->li_vn_mode) >= NTP_VERSION)
< sys_newversionpkt++;
< else if (PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION)
< sys_oldversionpkt++;
< else {
---
> if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
> sys_newversionpkt++; /* new version */
> } else if (!(restrict_mask & RES_VERSION) &&
> PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
> sys_oldversionpkt++; /* old version */
> } else {
254c327
< return;
---
> return; /* invalid version */
256,261d328
<
< /*
< * Restrict control/private mode packets. Note that packet
< * length has to be checked in the control/private mode protocol
< * module.
< */
264c331
< return;
---
> return; /* no query private */
271c338
< return;
---
> return; /* no query control */
274a342,345
> if (rbufp->recv_length < LEN_PKT_NOMAC) {
> sys_badlength++;
> return; /* runt packet */
> }
277c348
< * Restrict revenue packets.
---
> * Validate mode. Note that NTPv1 is no longer supported.
279,280c350,354
< if (restrict_mask & RES_DONTSERVE)
< return;
---
> hismode = (int)PKT_MODE(pkt->li_vn_mode);
> if (hismode == MODE_UNSPEC) {
> sys_badlength++;
> return; /* invalid mode */
> }
282,291d355
< /*
< * See if we only accept limited number of clients from the net
< * this guy is from. Note: the flag is determined dynamically
< * within restrictions()
< */
< if (restrict_mask & RES_LIMITED) {
< sys_limitrejected++;
< return;
< }
<
293c357,358
< * If we are not a broadcast client, ignore broadcast packets.
---
> * Discard broadcast packets received on the wildcard interface
> * or if not enabled as broadcast client.
295,296c360,361
< if ((PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
< !sys_bclient))
---
> if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
> (rbufp->dstadr == any_interface || !sys_bclient))
300,306c365,373
< * This is really awful ugly. We figure out whether an extension
< * field is present and then measure the MAC size. If the number
< * of words following the packet header is less than or equal to
< * 5, no extension field is present and these words constitute
< * the MAC. If the number of words is greater than 5, an
< * extension field is present and the first word contains the
< * length of the extension field and the MAC follows that.
---
> * Parse the extension field if present. We figure out whether
> * an extension field is present by measuring the MAC size. If
> * the number of words following the packet header is 0 or 1, no
> * MAC is present and the packet is not authenticated. If 1, the
> * packet is a reply to a previous request that failed to
> * authenticate. If 3, the packet is authenticated with DES; if
> * 5, the packet is authenticated with MD5. If greater than 5,
> * an extension field is present. If 2 or 4, the packet is a
> * runt and goes poof! with a brilliant flash.
308,310c375,378
< has_mac = 0;
< /* pkeyid = 0; */
< skeyid = tkeyid = 0;
---
> skeyid = 0;
> #ifdef AUTOKEY
> pkeyid = tkeyid = 0;
> #endif /* AUTOKEY */
312,318c380,383
< has_mac = rbufp->recv_length - authlen;
< if (has_mac <= 5 * sizeof(u_int32)) {
< skeyid = (u_long)ntohl(pkt->keyid1) & 0xffffffff;
< } else {
< authlen += (u_long)ntohl(pkt->keyid1) & 0xffffffff;
< has_mac = rbufp->recv_length - authlen;
< if (authlen <= 0) {
---
> while ((has_mac = rbufp->recv_length - authlen) > 0) {
> int temp;
>
> if (has_mac % 4 != 0 || has_mac < 0) {
321a387,390
> if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
> MAX_MAC_LEN) {
> skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
> break;
323,349c392,401
< /*
< * Note that keyid3 is actually the key ident of the
< * MAC itself.
< */
< /* pkeyid = (u_long)ntohl(pkt->keyid2) & 0xffffffff; */
< skeyid = tkeyid = (u_long)ntohl(pkt->keyid3) &
< 0xffffffff;
< }
<
< /*
< * Figure out his mode and validate it.
< */
< hismode = (int)PKT_MODE(pkt->li_vn_mode);
< if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION && hismode ==
< 0) {
< /*
< * Easy. If it is from the NTP port it is
< * a sym act, else client.
< */
< if (SRCPORT(&rbufp->recv_srcadr) == NTP_PORT)
< hismode = MODE_ACTIVE;
< else
< hismode = MODE_CLIENT;
< } else {
< if (hismode != MODE_ACTIVE && hismode != MODE_PASSIVE &&
< hismode != MODE_SERVER && hismode != MODE_CLIENT &&
< hismode != MODE_BROADCAST)
---
> } else if (has_mac > MAX_MAC_LEN) {
> temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
> 0xffff;
> if (temp < 4 || temp % 4 != 0) {
> sys_badlength++;
> return;
> }
> authlen += temp;
> } else {
> sys_badlength++;
350a403
> }
354,355c407,423
< * If he included a mac field, decrypt it to see if it is
< * authentic.
---
> * We have tossed out as many buggy packets as possible early in
> * the game to reduce the exposure to a clogging attack. Now we
> * have to burn some cycles to find the association and
> * authenticate the packet if required. Note that we burn only
> * MD5 or DES cycles, again to reduce exposure. There may be no
> * matching association and that's okay.
> *
> * More on the autokey mambo. Normally the local interface is
> * found when the association was mobilized with respect to a
> * designated remote address. We assume packets arriving from
> * the remote address arrive via this interface and the local
> * address used to construct the autokey is the unicast address
> * of the interface. However, if the sender is a broadcaster,
> * the interface broadcast address is used instead.
> * Notwithstanding this technobabble, if the sender is a
> * multicaster, the broadcast address is null, so we use the
> * unicast address anyway. Don't ask.
357c425,428
< is_authentic = is_mystic = 0;
---
> peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
> hismode, &retcode);
> is_authentic = 0;
> dstadr_sin = &rbufp->dstadr->sin;
361,363c432,434
< printf("receive: at %ld from %s mode %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< hismode);
---
> printf("receive: at %ld %s<-%s mode %d code %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), hismode, retcode);
366,369c437,444
< is_mystic = authistrusted(skeyid);
< #ifdef MD5
< if (skeyid > NTP_MAXKEY && !is_mystic) {
<
---
> #ifdef AUTOKEY
> /*
> * For autokey modes, generate the session key
> * and install in the key cache. Use the socket
> * broadcast or unicast address as appropriate.
> */
> if (skeyid > NTP_MAXKEY) {
>
371,377c446,468
< * For multicast mode, generate the session key
< * and install in the key cache. For client
< * mode, generate the session key for the
< * unicast address. For server mode, the session
< * key should already be in the key cache, since
< * it was generated when the last request was
< * sent.
---
> * More on the autokey dance (AKD). A cookie is
> * constructed from public and private values.
> * For broadcast packets, the cookie is public
> * (zero). For packets that match no
> * association, the cookie is hashed from the
> * addresses and private value. For server
> * packets, the cookie was previously obtained
> * from the server. For symmetric modes, the
> * cookie was previously constructed using an
> * agreement protocol; however, should PKI be
> * unavailable, we construct a fake agreement as
> * the EXOR of the peer and host cookies.
> *
> * hismode ephemeral persistent
> * =======================================
> * active 0 cookie#
> * passive 0% cookie#
> * client sys cookie 0%
> * server 0% sys cookie
> * broadcast 0 0
> *
> * # if unsync, 0
> * % can't happen
379a471,501
>
> /*
> * For broadcaster, use the interface
> * broadcast address when available;
> * otherwise, use the unicast address
> * found when the association was
> * mobilized.
> */
> pkeyid = 0;
> if (rbufp->dstadr->bcast.sin_addr.s_addr
> != 0)
> dstadr_sin =
> &rbufp->dstadr->bcast;
> } else if (peer == NULL) {
> pkeyid = session_key(
> &rbufp->recv_srcadr, dstadr_sin, 0,
> sys_private, 0);
> } else {
> pkeyid = peer->pcookie.key;
> }
>
> /*
> * The session key includes both the public
> * values and cookie. In case of an extension
> * field, the cookie used for authentication
> * purposes is zero. Note the hash is saved for
> * use later in the autokey mambo.
> */
> if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
> session_key(&rbufp->recv_srcadr,
> dstadr_sin, skeyid, 0, 2);
381,384c503,505
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->bcast.sin_addr.s_addr),
< skeyid, (u_long)(4 * (1 << pkt->ppoll)));
< } else if (hismode != MODE_SERVER) {
---
> &rbufp->recv_srcadr, dstadr_sin,
> skeyid, pkeyid, 0);
> } else {
386,388c507,508
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->sin.sin_addr.s_addr),
< skeyid, (u_long)(4 * (1 << pkt->ppoll)));
---
> &rbufp->recv_srcadr, dstadr_sin,
> skeyid, pkeyid, 2);
392c512
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
396c516,518
< * succceed in bloating the key cache.
---
> * succeed in bloating the key cache. If an autokey,
> * purge it immediately, since we won't be needing it
> * again.
402a525,528
> #ifdef AUTOKEY
> if (skeyid > NTP_MAXKEY)
> authtrust(skeyid, 0);
> #endif /* AUTOKEY */
406,408c532,536
< "receive: at %ld %s mode %d keyid %08lx mac %d auth %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< hismode, skeyid, has_mac, is_authentic);
---
> "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
> current_time, ntoa(dstadr_sin),
> ntoa(&rbufp->recv_srcadr), hismode, retcode,
> skeyid, authlen, has_mac,
> is_authentic);
413,414c541,548
< * Find the peer. This will return a null if this guy isn't in
< * the database.
---
> * The association matching rules are implemented by a set of
> * routines and a table in ntp_peer.c. A packet matching an
> * association is processed by that association. If not and
> * certain conditions prevail, then an ephemeral association is
> * mobilized: a broadcast packet mobilizes a broadcast client
> * aassociation; a server packet mobilizes a client association;
> * a symmetric active packet mobilizes a symmetric passive
> * association. And, the adventure continues...
416,428d549
< peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
< hismode, &retcode);
< /*
< * The new association matching rules are driven by a table
< * specified in ntp.h. We have replaced the *default* behaviour
< * of replying to bogus packets in server mode in this version.
< * A packet must now match an association in order to be
< * processed. In the event that no association exists, then an
< * association is mobilized if need be. Two different
< * associations can be mobilized a) passive associations b)
< * client associations due to broadcasts or manycasts.
< */
< is_error = 0;
433,439c554,558
< * If the client is configured purely as a broadcast
< * client and not as an manycast server, it has no
< * business being a server. Simply go home. Otherwise,
< * send a MODE_SERVER response and go home. Note that we
< * don't do a authentication check here, since we can't
< * set the system clock; but, we do set the key ID to
< * zero to tell the caller about this.
---
> * This is a client mode packet not matching a known
> * association. If from a manycast client we run a few
> * sanity checks before deciding to send a unicast
> * server response. Otherwise, it must be a client
> * request, so send a server response and go home.
441,445c560,578
< if (!sys_bclient || sys_manycastserver) {
< if (is_authentic)
< fast_xmit(rbufp, MODE_SERVER, skeyid);
< else
< fast_xmit(rbufp, MODE_SERVER, 0);
---
> if (sys_manycastserver && (rbufp->dstadr->flags &
> INT_MULTICAST)) {
>
> /*
> * We are picky about responding to a
> * manycaster. There is no reason to respond to
> * a request if our time is worse than the
> * manycaster. We certainly don't reply if not
> * synchronized to proventic time.
> */
> if (sys_peer == NULL)
> return;
>
> /*
> * We don't reply if the our stratum is greater
> * than the manycaster.
> */
> if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
> return;
449,450c582,584
< * We can't get here if an association is mobilized, so
< * just toss the key, if appropriate.
---
> * Note that we don't require an authentication check
> * here, since we can't set the system clock; but, we do
> * set the key ID to zero to tell the caller about this.
452,454c586,591
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< return;
---
> if (is_authentic)
> fast_xmit(rbufp, MODE_SERVER, skeyid,
> restrict_mask);
> else
> fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
> return;
459,465c596,611
< * This could be in response to a multicast packet sent
< * by the "manycast" mode association. Find peer based
< * on the originate timestamp in the packet. Note that
< * we don't mobilize a new association, unless the
< * packet is properly authenticated. The response must
< * be properly authenticated and it's darn funny of the
< * manycaster isn't around now.
---
> * This is a server mode packet returned in response to
> * a client mode packet sent to a multicast group
> * address. The originate timestamp is a good nonce to
> * reliably associate the reply with what was sent. If
> * there is no match, that's curious and could be an
> * intruder attempting to clog, so we just ignore it.
> *
> * First, make sure the packet is authentic. If so and
> * the manycast association is found, we mobilize a
> * client mode association, copy pertinent variables
> * from the manycast to the client mode association and
> * wind up the spring.
> *
> * There is an implosion hazard at the manycast client,
> * since the manycast servers send the server packet
> * immediately.
467,475c613,616
< if ((sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
< }
< peer2 = (struct peer *)findmanycastpeer(&pkt->org);
< if (peer2 == 0) {
< is_error = 1;
< break;
< }
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic))
> return;
477,482c618,621
< /*
< * Create a new association and copy the peer variables
< * to it. If something goes wrong, carefully pry the new
< * association away and return its marbles to the candy
< * store.
< */
---
> peer2 = findmanycastpeer(rbufp);
> if (peer2 == 0)
> return;
>
485,490c624,628
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
< if (peer == 0) {
< is_error = 1;
< break;
< }
< peer_config_manycast(peer2, peer);
---
> sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
> (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
> MDF_UCAST, 0, skeyid);
> if (peer == NULL)
> return;
493,501d630
< case AM_ERR:
<
< /*
< * Something bad happened. Dirty floor will be mopped by
< * the code at the end of this adventure.
< */
< is_error = 1;
< break;
<
505,507c634,637
< * Okay, we're going to keep him around. Allocate him
< * some memory. But, don't do that unless the packet is
< * properly authenticated.
---
> * This is the first packet received from a symmetric
> * active peer. First, make sure the packet is
> * authentic. If so, mobilize a symmetric passive
> * association.
509,511c639,644
< if ((sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic)) {
> fast_xmit(rbufp, MODE_PASSIVE, 0,
> restrict_mask);
> return;
515c648,651
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
---
> sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
> FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
> if (peer == NULL)
> return;
521,522c657,661
< * Broadcast client being set up now. Do this only if
< * the packet is properly authenticated.
---
> * This is the first packet received from a broadcast
> * server. First, make sure the packet is authentic, not
> * restricted and that we are a broadcast or multicast
> * client. If so, mobilize a broadcast client
> * association.
524,528c663,667
< if ((restrict_mask & RES_NOPEER) || !sys_bclient ||
< (sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
< }
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic) || !sys_bclient)
> return;
>
530,536c669,681
< MODE_MCLIENT, PKT_VERSION(pkt->li_vn_mode),
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
< if (peer == 0)
< break;
< peer->flags |= FLAG_MCAST1 | FLAG_MCAST2 | FLAG_BURST;
< peer->hmode = MODE_CLIENT;
< break;
---
> MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
> sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
> FLAG_IBURST | (sys_authenticate ?
> FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
> #ifdef AUTOKEY
> #ifdef PUBKEY
> if (peer == NULL)
> return;
> if (peer->flags & FLAG_SKEY)
> crypto_recv(peer, rbufp);
> #endif /* PUBKEY */
> #endif /* AUTOKEY */
> return;
542c687
< * It seems like it is okay to process the packet now
---
> * Happiness and nothing broke. Earn some revenue.
549c694,695
< * shouldn't be getting here, but simply return anyway!
---
> * Invalid mode combination. Leave the island
> * immediately.
551,566d696
< is_error = 1;
< }
< if (is_error) {
<
< /*
< * Error stub. If we get here, something broke. We
< * scuttle the autokey if necessary and sink the ship.
< * This can occur only upon mobilization, so we can
< * throw the structure away without fear of breaking
< * anything.
< */
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< if (peer != 0)
< if (!(peer->flags & FLAG_CONFIG))
< unpeer(peer);
569,570c699
< printf("match error code %d assoc %d\n",
< retcode, peer_associations);
---
> printf("receive: bad protocol %d\n", retcode);
576,577c705,710
< * If the peer isn't configured, set his keyid and authenable
< * status based on the packet.
---
> * If the peer isn't configured, set his authenable and autokey
> * status based on the packet. Once the status is set, it can't
> * be unset. It seems like a silly idea to do this here, rather
> * in the configuration routine, but in some goofy cases the
> * first packet sent cannot be authenticated and we need a way
> * for the dude to change his mind.
580a714
> peer->received++;
583,588c717,720
< if (skeyid > NTP_MAXKEY) {
< if (peer->flags & FLAG_MCAST2)
< peer->keyid = skeyid;
< else
< peer->flags |= FLAG_SKEY;
< }
---
> #ifdef AUTOKEY
> if (skeyid > NTP_MAXKEY)
> peer->flags |= FLAG_SKEY;
> #endif /* AUTOKEY */
592,595c724,730
< * Determine if this guy is basically trustable. If not, flush
< * the bugger. If this is the first packet that is
< * authenticated, flush the clock filter. This is to foil
< * clogging attacks that might starve the poor dear.
---
> * A valid packet must be from an authentic and allowed source.
> * All packets must pass the authentication allowed tests.
> * Autokey authenticated packets must pass additional tests and
> * public-key authenticated packets must have the credentials
> * verified. If all tests are passed, the packet is forwarded
> * for processing. If not, the packet is discarded and the
> * association demobilized if appropriate.
598c733
< if (is_authentic)
---
> if (is_authentic) {
600c735
< else
---
> } else {
602,604c737,740
< if (peer->hmode == MODE_BROADCAST && (restrict_mask &
< RES_DONTTRUST))
< peer->flash |= TEST10; /* access denied */
---
> }
> if (peer->hmode == MODE_BROADCAST &&
> (restrict_mask & RES_DONTTRUST)) /* test 4 */
> peer->flash |= TEST4; /* access denied */
606c742
< if (!(peer->flags & FLAG_AUTHENTIC))
---
> if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
608,611c744
< else if (skeyid == 0)
< peer->flash |= TEST9; /* peer not auth */
< else if (!(oflags & FLAG_AUTHENABLE)) {
< peer_clear(peer);
---
> else if (!(oflags & FLAG_AUTHENABLE))
613d745
< }
615,626c747
< if ((peer->flash & ~(u_int)TEST9) != 0) {
<
< /*
< * The packet is bogus, so we throw it away before
< * becoming a denial-of-service hazard. We don't throw
< * the current association away if it is configured or
< * if it has prior reachable friends.
< */
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< if (!(peer->flags & FLAG_CONFIG) && peer->reach == 0)
< unpeer(peer);
---
> if (peer->flash) {
629,631c750
< printf(
< "invalid packet 0x%02x code %d assoc %d\n",
< peer->flash, retcode, peer_associations);
---
> printf("receive: bad auth %03x\n", peer->flash);
636c755
< #ifdef MD5
---
> #ifdef AUTOKEY
638,640c757,770
< * The autokey dance. The cha-cha requires that the hash of the
< * current session key matches the previous key identifier.
< * Heaps of trouble if the steps falter.
---
> * More autokey dance. The rules of the cha-cha are as follows:
> *
> * 1. If there is no key or the key is not auto, do nothing.
> *
> * 2. If an extension field contains a verified signature, it is
> * self-authenticated and we sit the dance.
> *
> * 3. If this is a server reply, check only to see that the
> * transmitted key ID matches the received key ID.
> *
> * 4. Check to see that one or more hashes of the current key ID
> * matches the previous key ID or ultimate original key ID
> * obtained from the broadcaster or symmetric peer. If no
> * match, sit the dance and wait for timeout.
642,649c772,775
< if (skeyid > NTP_MAXKEY) {
< int i;
<
< /*
< * In the case of a new autokey, verify the hash matches
< * one of the previous four hashes. If not, raise the
< * authentication flasher and hope the next one works.
< */
---
> if (peer->flags & FLAG_SKEY) {
> peer->flash |= TEST10;
> crypto_recv(peer, rbufp);
> poll_update(peer, peer->hpoll);
651,661c777,780
< peer->pkeyid = peer->keyid;
< } else if (peer->flags & FLAG_MCAST2) {
< if (peer->pkeyid > NTP_MAXKEY)
< authtrust(peer->pkeyid, 0);
< for (i = 0; i < 4 && tkeyid != peer->pkeyid;
< i++) {
< tkeyid = session_key(
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->bcast.sin_addr.s_addr),
< tkeyid, 0);
< }
---
> if (skeyid == peer->keyid)
> peer->flash &= ~TEST10;
> } else if (!peer->flash & TEST10) {
> peer->pkeyid = skeyid;
663,666c782,792
< if (peer->pkeyid > NTP_MAXKEY)
< authtrust(peer->pkeyid, 0);
< for (i = 0; i < 4 && tkeyid != peer->pkeyid;
< i++) {
---
> int i;
>
> for (i = 0; ; i++) {
> if (tkeyid == peer->pkeyid ||
> tkeyid == peer->recauto.key) {
> peer->flash &= ~TEST10;
> peer->pkeyid = skeyid;
> break;
> }
> if (i > peer->recauto.seq)
> break;
668,670c794,795
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->sin.sin_addr.s_addr),
< tkeyid, 0);
---
> &rbufp->recv_srcadr, dstadr_sin,
> tkeyid, pkeyid, 0);
673,675c798,814
< #ifdef XXX /* temp until certificate code is mplemented */
< if (tkeyid != peer->pkeyid)
< peer->flash |= TEST9; /* peer not authentic */
---
> #ifdef PUBKEY
>
> /*
> * This is delicious. Ordinarily, we kick out all errors
> * at this point; however, in symmetric mode and just
> * warming up, an unsynchronized peer must inject the
> * timestamps, even if it fails further up the road. So,
> * let the dude by here, but only if the jerk is not yet
> * reachable. After that, he's on his own.
> */
> if (!(peer->flags & FLAG_PROVEN))
> peer->flash |= TEST11;
> if (peer->flash && peer->reach) {
> #ifdef DEBUG
> if (debug)
> printf("packet: bad autokey %03x\n",
> peer->flash);
677c816,818
< peer->pkeyid = skeyid;
---
> return;
> }
> #endif /* PUBKEY */
679c820
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
682,685c823,826
< * Gawdz, it's come to this. Process the dang packet. If
< * something breaks and the association doesn't deserve to live,
< * toss it. Be careful in active mode and return a packet
< * anyway.
---
> * We have survived the gaunt. Forward to the packet routine. If
> * a symmetric passive association has been mobilized and the
> * association doesn't deserve to live, it will die in the
> * transmit routine if not reachable after timeout.
687,696c828
< process_packet(peer, pkt, &(rbufp->recv_time));
< if (!(peer->flags & FLAG_CONFIG) && peer->reach == 0) {
< if (peer->hmode == MODE_PASSIVE) {
< if (is_authentic)
< fast_xmit(rbufp, MODE_PASSIVE, skeyid);
< else
< fast_xmit(rbufp, MODE_PASSIVE, 0);
< }
< unpeer(peer);
< }
---
> process_packet(peer, pkt, &rbufp->recv_time);
706c838
< int
---
> void
718c850
< int pmode;
---
> int pmode, pleap, pstratum;
721c853,856
< * Swap header fields and keep the books.
---
> * Swap header fields and keep the books. The books amount to
> * the receive timestamp and poll interval in the header. We
> * need these even if there are other problems in order to crank
> * up the state machine.
734,736d868
< peer->rec = *recv_ts;
< peer->ppoll = pkt->ppoll;
< pmode = PKT_MODE(pkt->li_vn_mode);
739c871
< * Test for old or duplicate packets (tests 1 through 3).
---
> * Test for old, duplicate or unsynch packets (tests 1-3).
740a873,876
> peer->rec = *recv_ts;
> pmode = PKT_MODE(pkt->li_vn_mode);
> pleap = PKT_LEAP(pkt->li_vn_mode);
> pstratum = PKT_TO_STRATUM(pkt->stratum);
743,754c879,885
< if (L_ISEQU(&peer->org, &p_xmt)) /* test 1 */
< peer->flash |= TEST1; /* duplicate packet */
< if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST) {
< if (!L_ISEQU(&peer->xmt, &p_org)) { /* test 2 */
< peer->bogusorg++;
< peer->flash |= TEST2; /* bogus packet */
< }
< if (L_ISZERO(&p_rec) || L_ISZERO(&p_org))
< peer->flash |= TEST3; /* unsynchronized */
< } else {
< if (L_ISZERO(&p_org))
< peer->flash |= TEST3; /* unsynchronized */
---
> if (L_ISEQU(&peer->org, &p_xmt)) /* 1 */
> peer->flash |= TEST1; /* dupe */
> if (pmode != MODE_BROADCAST) {
> if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
> peer->flash |= TEST2; /* bogus */
> if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
> peer->flash |= TEST3; /* unsynch */
755a887,888
> if (L_ISZERO(&p_xmt)) /* 3 */
> peer->flash |= TEST3; /* unsynch */
759c892,894
< * Test for valid header (tests 5 through 10)
---
> * If tests 1-3 fail, the packet is discarded leaving only the
> * receive and origin timestamps and poll interval, which is
> * enough to get the protocol started.
760a896,932
> if (peer->flash) {
> #ifdef DEBUG
> if (debug)
> printf("packet: bad data %03x\n",
> peer->flash);
> #endif
> return;
> }
>
> /*
> * A kiss-of-death (kod) packet is returned by a server in case
> * the client is denied access. It consists of the client
> * request packet with the leap bits indicating never
> * synchronized, stratum zero and reference ID field the ASCII
> * string "DENY". If the packet originate timestamp matches the
> * association transmit timestamp the kod is legitimate. If the
> * peer leap bits indicate never synchronized, this must be
> * access deny and the association is disabled; otherwise this
> * must be a limit reject. In either case a naughty message is
> * forced to the system log.
> */
> if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
> memcmp(&pkt->refid, "DENY", 4) == 0) {
> if (peer->leap == LEAP_NOTINSYNC) {
> peer->stratum = STRATUM_UNSPEC;
> peer->flash |= TEST4;
> memcpy(&peer->refid, &pkt->refid, 4);
> msyslog(LOG_INFO, "access denied");
> } else {
> msyslog(LOG_INFO, "limit reject");
> }
> return;
> }
>
> /*
> * Test for valid peer data (tests 6-8)
> */
764,770c936,941
< if (PKT_LEAP(pkt->li_vn_mode) == LEAP_NOTINSYNC || /* test 6 */
< PKT_TO_STRATUM(pkt->stratum) >= NTP_MAXSTRATUM ||
< dtemp < 0)
< peer->flash |= TEST6; /* peer clock unsynchronized */
< if (!(peer->flags & FLAG_CONFIG) && sys_peer != 0) { /* test 7 */
< if (PKT_TO_STRATUM(pkt->stratum) > sys_stratum) {
< peer->flash |= TEST7; /* peer stratum too high */
---
> if (pleap == LEAP_NOTINSYNC || /* 6 */
> pstratum >= STRATUM_UNSPEC || dtemp < 0)
> peer->flash |= TEST6; /* bad synch */
> if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
> if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
> peer->flash |= TEST7; /* bad stratum */
774,783c945,948
< if (fabs(p_del) >= MAXDISPERSE /* test 8 */
< || p_disp >= MAXDISPERSE)
< peer->flash |= TEST8; /* delay/dispersion too high */
<
< /*
< * If the packet header is invalid (tests 5 through 10), exit.
< * XXX we let TEST9 sneak by until the certificate code is
< * implemented, but only to mobilize the association.
< */
< if (peer->flash & (TEST5 | TEST6 | TEST7 | TEST8 | TEST10)) {
---
> if (p_del < 0 || p_disp < 0 || p_del / /* 8 */
> 2 + p_disp >= MAXDISPERSE)
> peer->flash |= TEST8; /* bad peer distance */
> if (peer->flash) {
786,788c951,952
< printf(
< "invalid packet header 0x%02x mode %d\n",
< peer->flash, pmode);
---
> printf("packet: bad header %03x\n",
> peer->flash);
790c954
< return (0);
---
> return;
794c958,959
< * Valid header; update our state.
---
> * The header is valid. Capture the remaining header values and
> * mark as reachable.
796,801c961,966
< record_raw_stats(&peer->srcadr, &peer->dstadr->sin,
< &p_org, &p_rec, &p_xmt, &peer->rec);
<
< peer->leap = PKT_LEAP(pkt->li_vn_mode);
< peer->pmode = pmode; /* unspec */
< peer->stratum = PKT_TO_STRATUM(pkt->stratum);
---
> record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
> &p_rec, &p_xmt, &peer->rec);
> peer->leap = pleap;
> peer->pmode = pmode;
> peer->stratum = pstratum;
> peer->ppoll = pkt->ppoll;
807c972
< if (peer->reach == 0) {
---
> if (!(peer->reach)) {
811a977
> peer->unreach = 0;
832c998
< p_disp = CLOCK_PHI * (peer->rec.l_ui - p_org.l_ui);
---
> p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
837,850c1003,1007
< * measure that directly; therefore, we start up in
< * client/server mode, calculate the clock offset, using the
< * engineered refinement algorithms, while also receiving
< * broadcasts. When a broadcast is received in client/server
< * mode, we calculate a correction factor to use after switching
< * back to broadcast mode. We know NTP_SKEWFACTOR == 16, which
< * accounts for the simplified ei calculation.
< *
< * If FLAG_MCAST2 is set, we are a broadcast/multicast client.
< * If FLAG_MCAST1 is set, we haven't calculated the propagation
< * delay. If hmode is MODE_CLIENT, we haven't set the local
< * clock in client/server mode. Initially, we come up
< * MODE_CLIENT. When the clock is first updated and FLAG_MCAST2
< * is set, we switch from MODE_CLIENT to MODE_BCLIENT.
---
> * measure that directly. Therefore, we start up in MODE_CLIENT
> * mode, set FLAG_MCAST and exchange eight messages to determine
> * the clock offset. When the last message is sent, we switch to
> * MODE_BCLIENT mode. The next broadcast message after that
> * computes the broadcast offset and clears FLAG_MCAST.
853,855c1010
< if (peer->flags & FLAG_MCAST1) {
< if (peer->hmode == MODE_BCLIENT)
< peer->flags &= ~FLAG_MCAST1;
---
> if (peer->flags & FLAG_MCAST) {
858c1013,1014
< return (1);
---
> if (peer->hmode == MODE_CLIENT)
> return;
859a1016
> peer->flags &= ~FLAG_MCAST;
869a1027
> p_del = max(p_del, LOGTOD(sys_precision));
871,872c1029,1031
< if (fabs(p_del) >= MAXDISPERSE || p_disp >= MAXDISPERSE) /* test 4 */
< peer->flash |= TEST4; /* delay/dispersion too big */
---
> if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
> p_disp >= MAXDISPERSE) /* 9 */
> peer->flash |= TEST9; /* bad peer distance */
875c1034,1035
< * If the packet data are invalid (tests 1 through 4), exit.
---
> * If any flasher bits remain set at this point, abandon ship.
> * Otherwise, forward to the clock filter.
880,881c1040,1041
< printf("invalid packet data 0x%02x mode %d\n",
< peer->flash, pmode);
---
> printf("packet: bad packet data %03x\n",
> peer->flash);
883c1043
< return(1);
---
> return;
885,890c1045
<
<
< /*
< * This one is valid. Mark it so, give it to clock_filter().
< */
< clock_filter(peer, p_offset, p_del, fabs(p_disp));
---
> clock_filter(peer, p_offset, p_del, p_disp);
894,895c1049
< SQRT(peer->variance));
< return(1);
---
> SQRT(peer->jitter));
907,908d1060
< int i;
< struct peer *peer;
915c1067
< if (sys_peer == 0)
---
> if (sys_peer == NULL)
927c1079
< switch (local_clock(sys_peer, sys_offset, sys_epsil)) {
---
> switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
929,932c1081,1084
< case -1:
< /*
< * Clock is too screwed up. Just exit for now.
< */
---
> /*
> * Clock is too screwed up. Just exit for now.
> */
> case -1:
937,949c1089,1094
< case 1:
< /*
< * Clock was stepped. Clear filter registers
< * of all peers.
< */
< for (i = 0; i < HASH_SIZE; i++) {
< for (peer = peer_hash[i]; peer != 0;
< peer =peer->next)
< peer_clear(peer);
< }
< NLOG(NLOG_SYNCSTATUS)
< msyslog(LOG_INFO, "synchronisation lost");
< sys_peer = 0;
---
> /*
> * Clock was stepped. Flush all time values of all peers.
> */
> case 1:
> clear_all();
> sys_peer = NULL;
950a1096,1098
> sys_poll = NTP_MINPOLL;
> NLOG(NLOG_SYNCSTATUS)
> msyslog(LOG_INFO, "synchronisation lost");
954,960c1102,1108
< default:
< /*
< * Update the system stratum, leap bits, root delay,
< * root dispersion, reference ID and reference time. We
< * also update select dispersion and max frequency
< * error.
< */
---
> /*
> * Update the system stratum, leap bits, root delay, root
> * dispersion, reference ID and reference time. We also update
> * select dispersion and max frequency error. If the leap
> * changes, we gotta reroll the keys.
> */
> default:
967,968c1115
< sys_rootdelay = sys_peer->rootdelay +
< fabs(sys_peer->delay);
---
> sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
971c1118
< if (oleap != sys_leap)
---
> if (oleap == LEAP_NOTINSYNC) {
972a1120,1123
> #ifdef AUTOKEY
> expire_all();
> #endif /* AUTOKEY */
> }
979,980c1130
< * poll_update - update peer poll interval. See Section 3.4.9 of the
< * spec.
---
> * poll_update - update peer poll interval
988c1138,1140
< long update;
---
> #ifdef AUTOKEY
> int oldpoll;
> #endif /* AUTOKEY */
991,995c1143,1148
< * The wiggle-the-poll-interval dance. Broadcasters dance only
< * the minpoll beat. Reference clock partners sit this one out.
< * Dancers surviving the clustering algorithm beat to the system
< * clock. Broadcast clients are usually lead by their broadcast
< * partner, but faster in the initial mating dance.
---
> * A little foxtrot to determine what controls the poll
> * interval. If the peer is reachable, but the last four polls
> * have not been answered, use the minimum. If declared
> * truechimer, use the system poll interval. This allows each
> * association to ramp up the poll interval for useless sources
> * and to clamp it to the minimum when first starting up.
997c1150,1155
< if (peer->hmode == MODE_BROADCAST) {
---
> #ifdef AUTOKEY
> oldpoll = peer->kpoll;
> #endif /* AUTOKEY */
> if (hpoll > peer->maxpoll)
> peer->hpoll = peer->maxpoll;
> else if (hpoll < peer->minpoll)
999,1008c1157,1174
< } else if (peer->flags & FLAG_SYSPEER) {
< peer->hpoll = sys_poll;
< } else {
< if (hpoll > peer->maxpoll)
< peer->hpoll = peer->maxpoll;
< else if (hpoll < peer->minpoll)
< peer->hpoll = peer->minpoll;
< else
< peer->hpoll = hpoll;
< }
---
> else
> peer->hpoll = hpoll;
>
> /*
> * Bit of adventure here. If during a burst and not timeout,
> * just slink away. If timeout, figure what the next timeout
> * should be. If IBURST or a reference clock, use one second. If
> * not and the dude was reachable during the previous poll
> * interval, randomize over 1-4 seconds; otherwise, randomize
> * over 15-18 seconds. This is to give time for a modem to
> * complete the call, for example. If not during a burst,
> * randomize over the poll interval -1 to +2 seconds.
> *
> * In case of manycast server, make the poll interval, which is
> * axtually the manycast beacon interval, eight times the system
> * poll interval. Normally when the host poll interval settles
> * up to 17.1 s, the beacon interval settles up to 2.3 hours.
> */
1012c1178,1179
< if (peer->flags & FLAG_REFCLOCK)
---
> #ifdef REFCLOCK
> else if (peer->flags & FLAG_REFCLOCK)
1013a1181
> #endif
1017a1186,1191
> } else if (peer->cast_flags & MDF_ACAST) {
> if (sys_survivors < NTP_MINCLOCK)
> peer->kpoll = peer->hpoll;
> else
> peer->kpoll = peer->hpoll + 3;
> peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1019c1193
< update = max(min(peer->ppoll, peer->hpoll),
---
> peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1021c1195
< peer->nextdate = peer->outdate + RANDPOLL(update);
---
> peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1022a1197,1208
> if (peer->nextdate < current_time)
> peer->nextdate = current_time;
> #ifdef AUTOKEY
> /*
> * Bit of crass arrogance at this point. If the poll interval
> * has changed and we have a keylist, the lifetimes in the
> * keylist are probably bogus. In this case purge the keylist
> * and regenerate it later.
> */
> if (peer->kpoll != oldpoll)
> key_expire(peer);
> #endif /* AUTOKEY */
1025,1027c1211,1214
< printf("poll_update: at %lu %s poll %d burst %d last %lu next %lu\n",
< current_time, ntoa(&peer->srcadr), hpoll,
< peer->burst, peer->outdate, peer->nextdate);
---
> printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
> current_time, ntoa(&peer->srcadr), peer->flags,
> peer->kpoll, peer->burst, peer->outdate,
> peer->nextdate);
1040a1228
> u_long u_rand;
1041a1230,1254
> /*
> * If cryptographic credentials have been acquired, toss them to
> * Valhalla. Note that autokeys are ephemeral, in that they are
> * tossed immediately upon use. Therefore, the keylist can be
> * purged anytime without needing to preserve random keys. Note
> * that, if the peer is purged, the cryptographic variables are
> * purged, too. This makes it much harder to sneak in some
> * unauthenticated data in the clock filter.
> */
> #ifdef DEBUG
> if (debug)
> printf("peer_clear: at %ld assoc ID %d\n", current_time,
> peer->associd);
> #endif
> #ifdef AUTOKEY
> key_expire(peer);
> #ifdef PUBKEY
> if (peer->keystr != NULL)
> free(peer->keystr);
> if (peer->pubkey.ptr != NULL)
> free(peer->pubkey.ptr);
> if (peer->certif.ptr != NULL)
> free(peer->certif.ptr);
> #endif /* PUBKEY */
> #endif /* AUTOKEY */
1042a1256,1268
>
> /*
> * If he dies as a broadcast client, he comes back to life as
> * a broadcast client in client mode in order to recover the
> * initial autokey values. Note that there is no need to call
> * clock_select(), since the perp has already been voted off
> * the island at this point.
> */
> if (peer->cast_flags & MDF_BCLNT) {
> peer->flags |= FLAG_MCAST;
> peer->hmode = MODE_CLIENT;
> }
> peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1044c1270,1271
< peer->hpoll = peer->minpoll;
---
> peer->hpoll = peer->kpoll = peer->minpoll;
> peer->ppoll = peer->maxpoll;
1046c1273
< peer->variance = MAXDISPERSE;
---
> peer->jitter = MAXDISPERSE;
1047a1275,1280
> #ifdef REFCLOCK
> if (!(peer->flags & FLAG_REFCLOCK)) {
> peer->leap = LEAP_NOTINSYNC;
> peer->stratum = STRATUM_UNSPEC;
> }
> #endif
1053d1285
< poll_update(peer, peer->minpoll);
1056,1059c1288
< * Since we have a chance to correct possible funniness in
< * our selection of interfaces on a multihomed host, do so
< * by setting us to no particular interface.
< * WARNING: do so only in non-broadcast mode!
---
> * Randomize the first poll over 1-16s to avoid bunching.
1061,1062c1290,1293
< if (peer->hmode != MODE_BROADCAST)
< peer->dstadr = any_interface;
---
> peer->update = peer->outdate = current_time;
> u_rand = RANDOM;
> peer->nextdate = current_time + (u_rand & ((1 <<
> BURST_INTERVAL1) - 1)) + 1;
1072,1075c1303,1306
< register struct peer *peer,
< double sample_offset,
< double sample_delay,
< double sample_disp
---
> register struct peer *peer, /* peer structure pointer */
> double sample_offset, /* clock offset */
> double sample_delay, /* roundtrip delay */
> double sample_disp /* dispersion */
1078,1081c1309,1312
< register int i, j, k, n = 0;
< register u_char *ord;
< double distance[NTP_SHIFT];
< double x, y, z, off;
---
> double dst[NTP_SHIFT]; /* distance vector */
> int ord[NTP_SHIFT]; /* index vector */
> register int i, j, k, m;
> double dsp, jit, dtemp, etemp;
1084,1085c1315,1321
< * Update error bounds and calculate distances. Also initialize
< * sort index vector.
---
> * Shift the new sample into the register and discard the oldest
> * one. The new offset and delay come directly from the
> * timestamp calculations. The dispersion grows from the last
> * outbound packet or reference clock update to the present time
> * and increased by the sum of the peer precision and the system
> * precision. The delay can sometimes swing negative due to
> * frequency skew, so it is clamped non-negative.
1087,1089c1323,1324
< x = CLOCK_PHI * (current_time - peer->update);
< peer->update = current_time;
< ord = peer->filter_order;
---
> dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
> sample_disp, MAXDISPERSE);
1091,1100c1326,1331
< for (i = 0; i < NTP_SHIFT; i++) {
< peer->filter_disp[j] += x;
< if (peer->filter_disp[j] > MAXDISPERSE)
< peer->filter_disp[j] = MAXDISPERSE;
< distance[i] = fabs(peer->filter_delay[j]) / 2 +
< peer->filter_disp[j];
< ord[i] = j;
< if (--j < 0)
< j += NTP_SHIFT;
< }
---
> peer->filter_offset[j] = sample_offset;
> peer->filter_delay[j] = max(0, sample_delay);
> peer->filter_disp[j] = dsp;
> peer->filter_epoch[j] = current_time;
> j++; j %=NTP_SHIFT;
> peer->filter_nextpt = j;
1103c1334,1338
< * Insert the new sample at the beginning of the register.
---
> * Update dispersions since the last update and at the same
> * time initialize the distance and index lists. The distance
> * list uses a compound metric. If the sample is valid and
> * younger than the minimum Allan intercept, use delay;
> * otherwise, use biased dispersion.
1105,1114c1340,1357
< peer->filter_offset[peer->filter_nextpt] = sample_offset;
< peer->filter_delay[peer->filter_nextpt] = sample_delay;
< x = LOGTOD(peer->precision) + LOGTOD(sys_precision) +
< sample_disp;
< peer->filter_disp[peer->filter_nextpt] = min(x, MAXDISPERSE);
< peer->filter_epoch[peer->filter_nextpt] = current_time;
< distance[0] = min(x + fabs(sample_delay) / 2, MAXDISTANCE);
< peer->filter_nextpt++;
< if (peer->filter_nextpt >= NTP_SHIFT)
< peer->filter_nextpt = 0;
---
> dtemp = clock_phi * (current_time - peer->update);
> peer->update = current_time;
> for (i = NTP_SHIFT - 1; i >= 0; i--) {
> if (i != 0) {
> peer->filter_disp[j] += dtemp;
> if (peer->filter_disp[j] > MAXDISPERSE)
> peer->filter_disp[j] = MAXDISPERSE;
> }
> if (peer->filter_disp[j] >= MAXDISPERSE)
> dst[i] = MAXDISPERSE;
> else if (peer->update - peer->filter_epoch[j] >
> allan_xpt)
> dst[i] = MAXDISTANCE + peer->filter_disp[j];
> else
> dst[i] = peer->filter_delay[j];
> ord[i] = j;
> j++; j %= NTP_SHIFT;
> }
1116,1119c1359,1360
< /*
< * Sort the samples in the register by distance. The winning
< * sample will be in ord[0]. Sort the samples only if they
< * are younger than the Allen intercept.
---
> /*
> * Sort the samples in both lists by distance.
1121,1126c1362,1364
< y = min(allan_xpt, NTP_SHIFT * ULOGTOD(sys_poll));
< for (n = 0; n < NTP_SHIFT && current_time -
< peer->filter_epoch[ord[n]] <= y; n++) {
< for (j = 0; j < n; j++) {
< if (distance[j] > distance[n]) {
< x = distance[j];
---
> for (i = 1; i < NTP_SHIFT; i++) {
> for (j = 0; j < i; j++) {
> if (dst[j] > dst[i]) {
1128,1131c1366,1370
< distance[j] = distance[n];
< ord[j] = ord[n];
< distance[n] = x;
< ord[n] = k;
---
> ord[j] = ord[i];
> ord[i] = k;
> etemp = dst[j];
> dst[j] = dst[i];
> dst[i] = etemp;
1134c1373,1388
< }
---
> }
>
> /*
> * Copy the index list to the association structure so ntpq
> * can see it later. Prune the distance list to samples less
> * than MAXDISTANCE, but keep at least two valid samples for
> * jitter calculation.
> */
> m = 0;
> for (i = 0; i < NTP_SHIFT; i++) {
> peer->filter_order[i] = ord[i];
> if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
> MAXDISTANCE))
> continue;
> m++;
> }
1137c1391,1397
< * Compute the error bound and standard error.
---
> * Compute the dispersion and jitter squares. The dispersion
> * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
> * normalized close to 1.0. The jitter is the mean of the square
> * differences relative to the lowest delay sample. If no
> * acceptable samples remain in the shift register, quietly
> * tiptoe home leaving only the
> * dispersion.
1139c1399,1401
< x = y = z = off = 0.;
---
> jit = 0;
> peer->disp = 0;
> k = ord[0];
1141,1148c1403,1409
< x = NTP_FWEIGHT * (x + peer->filter_disp[ord[i]]);
< if (i < n) {
< z += 1. / distance[i];
< off += peer->filter_offset[ord[i]] /
< distance[i];
< y += DIFF(peer->filter_offset[ord[i]],
< peer->filter_offset[ord[0]]);
< }
---
>
> j = ord[i];
> peer->disp = NTP_FWEIGHT * (peer->disp +
> peer->filter_disp[j]);
> if (i < m)
> jit += DIFF(peer->filter_offset[j],
> peer->filter_offset[k]);
1150,1158d1410
< peer->delay = peer->filter_delay[ord[0]];
< peer->variance = min(y / n, MAXDISPERSE);
< peer->disp = min(x, MAXDISPERSE);
< peer->epoch = current_time;
< x = peer->offset;
< if (peer->flags & FLAG_BURST)
< peer->offset = off / z;
< else
< peer->offset = peer->filter_offset[ord[0]];
1160a1413,1427
> * If no acceptable samples remain in the shift register,
> * quietly tiptoe home leaving only the dispersion. Otherwise,
> * save the offset, delay and jitter average. Note the jitter
> * must not be less than the system precision.
> */
> if (m == 0)
> return;
> etemp = peer->offset;
> peer->offset = peer->filter_offset[k];
> peer->delay = peer->filter_delay[k];
> if (m > 1)
> jit /= m - 1;
> peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
>
> /*
1164c1431
< if (peer->filter_epoch[ord[0]] > peer->epoch) {
---
> if (peer->filter_epoch[k] <= peer->epoch) {
1168c1435
< peer->filter_epoch[ord[0]] - peer->epoch);
---
> peer->epoch - peer->filter_epoch[k]);
1174,1177c1441,1444
< * If the offset exceeds the dispersion by CLOCK_SGATE and the
< * interval since the last update is less than twice the system
< * poll interval, consider the update a popcorn spike and ignore
< * it.
---
> * If the difference between the last offset and the current one
> * exceeds the jitter by CLOCK_SGATE (4) and the interval since
> * the last update is less than twice the system poll interval,
> * consider the update a popcorn spike and ignore it.
1179,1181c1446,1448
< if (fabs(x - peer->offset) > CLOCK_SGATE &&
< peer->filter_epoch[ord[0]] - peer->epoch < (1 <<
< (sys_poll + 1))) {
---
> if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
> CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
> (1 << (sys_poll + 1))) {
1184c1451,1452
< printf("clock_filter: popcorn spike %.6f\n", x);
---
> printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
> m, peer->offset, SQRT(peer->jitter));
1188c1456,1461
< peer->epoch = peer->filter_epoch[ord[0]];
---
>
> /*
> * The mitigated sample statistics are saved for later
> * processing, but can be processed only once.
> */
> peer->epoch = peer->filter_epoch[k];
1193,1195c1466,1468
< "clock_filter: offset %.6f delay %.6f disp %.6f std %.6f, age %lu\n",
< peer->offset, peer->delay, peer->disp,
< SQRT(peer->variance), current_time - peer->epoch);
---
> "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
> m, peer->offset, peer->delay, peer->disp,
> SQRT(peer->jitter), peer->update - peer->epoch);
1207,1208c1480,1481
< int i;
< int nlist, nl3;
---
> int i, j, k, n;
> int nreach, nlist, nl3;
1210,1212c1483
< int j;
< int n;
< int allow, found, k;
---
> int allow, found, sw;
1216,1220c1487,1490
< struct peer *typeacts = 0;
< struct peer *typelocal = 0;
< struct peer *typepps = 0;
< struct peer *typeprefer = 0;
< struct peer *typesystem = 0;
---
> struct peer *typeacts = NULL;
> struct peer *typelocal = NULL;
> struct peer *typepps = NULL;
> struct peer *typesystem = NULL;
1224c1494
< static int *index = NULL;
---
> static int *indx = NULL;
1227c1497
< static u_int index_size = 0;
---
> static u_int indx_size = 0;
1231,1232c1501,1502
< * Initialize. If a prefer peer does not survive this thing,
< * the pps_update switch will remain zero.
---
> * Initialize and create endpoint, index and peer lists big
> * enough to handle all associations.
1234,1235c1504,1507
< pps_update = 0;
< nlist = 0;
---
> osys_peer = sys_peer;
> sys_peer = NULL;
> sys_prefer = NULL;
> nreach = nlist = 0;
1243c1515
< free(index);
---
> free(indx);
1248,1250c1520,1522
< endpoint_size += 5 * 3 * sizeof *endpoint;
< index_size += 5 * 3 * sizeof *index;
< peer_list_size += 5 * sizeof *peer_list;
---
> endpoint_size += 5 * 3 * sizeof(*endpoint);
> indx_size += 5 * 3 * sizeof(*indx);
> peer_list_size += 5 * sizeof(*peer_list);
1253c1525
< index = (int *)emalloc(index_size);
---
> indx = (int *)emalloc(indx_size);
1258,1261c1530,1537
< * This first chunk of code is supposed to go through all
< * peers we know about to find the peers which are most likely
< * to succeed. We run through the list doing the sanity checks
< * and trying to insert anyone who looks okay.
---
> * Initially, we populate the island with all the rifraff peers
> * that happen to be lying around. Those with seriously
> * defective clocks are immediately booted off the island. Then,
> * the falsetickers are culled and put to sea. The truechimers
> * remaining are subject to repeated rounds where the most
> * unpopular at each round is kicked off. When the population
> * has dwindled to NTP_MINCLOCK (3), the survivors split a
> * million bucks and collectively crank the chimes.
1265c1541,1542
< for (peer = peer_hash[n]; peer != 0; peer = peer->next) {
---
> for (peer = peer_hash[n]; peer != NULL; peer =
> peer->next) {
1268,1279d1544
< if (peer->flags & FLAG_NOSELECT)
< continue; /* noselect (survey) */
< if (peer->reach == 0)
< continue; /* unreachable */
< if (peer->stratum > 1 && peer->refid ==
< peer->dstadr->sin.sin_addr.s_addr)
< continue; /* sync loop */
< if (root_distance(peer) >= MAXDISTANCE + 2 *
< CLOCK_PHI * ULOGTOD(sys_poll)) {
< peer->seldisptoolarge++;
< continue; /* noisy or broken */
< }
1282c1547,1562
< * Don't allow the local-clock or acts drivers
---
> * A peer leaves the island immediately if
> * unreachable, synchronized to us or suffers
> * excessive root distance. Careful with the
> * root distance, since the poll interval can
> * increase to a day and a half.
> */
> if (!peer->reach || (peer->stratum > 1 &&
> peer->refid ==
> peer->dstadr->sin.sin_addr.s_addr) ||
> peer->stratum >= STRATUM_UNSPEC ||
> (root_distance(peer) >= MAXDISTANCE + 2 *
> clock_phi * ULOGTOD(sys_poll)))
> continue;
>
> /*
> * Don't allow the local clock or modem drivers
1285c1565,1566
< * nobody else is around.
---
> * nobody else is around. These guys are all
> * configured, so we never throw them away.
1304,1305c1585,1587
< * If we get this far, we assume the peer is
< * acceptable.
---
> * If we get this far, the peer can stay on the
> * island, but does not yet have the immunity
> * idol.
1306a1589
> nreach++;
1318c1601
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1320c1603
< index[i + 3] = index[i];
---
> indx[i + 3] = indx[i];
1322c1605
< index[i + 3] = nl3;
---
> indx[i + 3] = nl3;
1328c1611
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1330c1613
< index[i + 2] = index[i];
---
> indx[i + 2] = indx[i];
1332c1615
< index[i + 2] = nl3;
---
> indx[i + 2] = nl3;
1338c1621
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1340c1623
< index[i + 1] = index[i];
---
> indx[i + 1] = indx[i];
1342c1625
< index[i + 1] = nl3;
---
> indx[i + 1] = nl3;
1348c1631
< if (debug > 1)
---
> if (debug > 2)
1350,1351c1633,1635
< printf("select: endpoint %2d %.6f\n",
< endpoint[index[i]].type, endpoint[index[i]].val);
---
> printf("select: endpoint %2d %.6f\n",
> endpoint[indx[i]].type,
> endpoint[indx[i]].val);
1360c1644
< n += endpoint[index[i]].type;
---
> n += endpoint[indx[i]].type;
1363c1647
< if (endpoint[index[i]].type == 0)
---
> if (endpoint[indx[i]].type == 0)
1367c1651
< n += endpoint[index[j]].type;
---
> n += endpoint[indx[j]].type;
1370c1654
< if (endpoint[index[j]].type == 0)
---
> if (endpoint[indx[j]].type == 0)
1375,1376c1659,1660
< low = endpoint[index[i++]].val;
< high = endpoint[index[j--]].val;
---
> low = endpoint[indx[i++]].val;
> high = endpoint[indx[j--]].val;
1380,1383c1664,1667
< * If no survivors remain at this point, check if the acts or
< * local clock drivers have been found. If so, nominate one of
< * them as the only survivor. Otherwise, give up and declare us
< * unsynchronized.
---
> * If no survivors remain at this point, check if the local
> * clock or modem drivers have been found. If so, nominate one
> * of them as the only survivor. Otherwise, give up and declare
> * us unsynchronized.
1395,1397c1679,1680
< if (sys_peer != 0) {
< report_event(EVNT_PEERSTCHG,
< (struct peer *)0);
---
> if (osys_peer != NULL) {
> sys_poll = NTP_MINPOLL;
1399c1682
< msyslog(LOG_INFO,
---
> msyslog(LOG_INFO,
1400a1684,1685
> report_event(EVNT_PEERSTCHG,
> (struct peer *)0);
1402c1687,1690
< sys_peer = 0;
---
> sys_survivors = 0;
> #ifdef AUTOKEY
> resetmanycast();
> #endif /* AUTOKEY */
1407c1695
< if (debug > 1)
---
> if (debug > 2)
1412,1415c1700,1706
< * Clustering algorithm. Process intersection list to discard
< * outlyers. Construct candidate list in cluster order
< * determined by the sum of peer synchronization distance plus
< * scaled stratum. We must find at least one peer.
---
> * Clustering algorithm. Construct candidate list in order first
> * by stratum then by root distance. If we have more than
> * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
> * list to find falsetickers, who leave the island immediately.
> * If a falseticker is not configured, his association raft is
> * drowned as well. We must leave at least one peer to collect
> * the million bucks.
1420,1421c1711,1714
< if (nlist > 1 && (low >= peer->offset ||
< peer->offset >= high))
---
> if (nlist > 1 && (low >= peer->offset || peer->offset >=
> high)) {
> if (!(peer->flags & FLAG_CONFIG))
> unpeer(peer);
1423c1716,1717
< peer->status = CTL_PST_SEL_CORRECT;
---
> }
> peer->status = CTL_PST_SEL_DISTSYSPEER;
1434d1727
< synch[k] = synch[k - 1];
1435a1729,1730
> error[k] = error[k - 1];
> synch[k] = synch[k - 1];
1437a1733
> error[k] = peer->jitter;
1441a1738,1739
> for (i = 0; i < nlist; i++) {
> peer_list[i]->status = CTL_PST_SEL_SELCAND;
1444,1445c1742
< if (debug > 1)
< for (i = 0; i < nlist; i++)
---
> if (debug > 2)
1448a1746
> }
1451,1454c1749,1754
< * Now, prune outlyers by root dispersion. Continue as long as
< * there are more than NTP_MINCLOCK survivors and the minimum
< * select dispersion is greater than the maximum peer
< * dispersion. Stop if we are about to discard a prefer peer.
---
> * Now, vote outlyers off the island by select jitter weighted
> * by root dispersion. Continue voting as long as there are more
> * than NTP_MINCLOCK survivors and the minimum select jitter
> * squared is greater than the maximum peer jitter squared. Stop
> * if we are about to discard a prefer peer, who of course has
> * the immunity idol.
1456,1463d1755
< for (i = 0; i < nlist; i++) {
< peer = peer_list[i];
< error[i] = peer->variance;
< if (i < NTP_CANCLOCK)
< peer->status = CTL_PST_SEL_SELCAND;
< else
< peer->status = CTL_PST_SEL_DISTSYSPEER;
< }
1465,1468c1757,1760
< sys_maxd = 0;
< d = error[0];
< for (k = i = nlist - 1; i >= 0; i--) {
< double sdisp = 0;
---
> d = 1e9;
> e = -1e9;
> k = 0;
> for (i = 0; i < nlist; i++) {
1470,1473c1762,1769
< for (j = nlist - 1; j > 0; j--) {
< sdisp = NTP_SWEIGHT * (sdisp +
< DIFF(peer_list[i]->offset,
< peer_list[j]->offset));
---
> if (error[i] < d)
> d = error[i];
> f = 0;
> if (nlist > 1) {
> for (j = 0; j < nlist; j++)
> f += DIFF(peer_list[j]->offset,
> peer_list[i]->offset);
> f /= nlist - 1;
1475,1476c1771,1774
< if (sdisp > sys_maxd) {
< sys_maxd = sdisp;
---
> f = max(f, SQUARE(LOGTOD(sys_precision)));
> if (f * synch[i] > e) {
> sys_selerr = f;
> e = f * synch[i];
1479,1480d1776
< if (error[i] < d)
< d = error[i];
1484c1780
< if (debug > 1)
---
> if (debug > 2)
1487c1783
< nlist, SQRT(sys_maxd), SQRT(d));
---
> k, SQRT(sys_selerr), SQRT(d));
1489,1490c1785,1786
< if (nlist <= NTP_MINCLOCK || sys_maxd <= d ||
< peer_list[k]->flags & FLAG_PREFER)
---
> if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
> peer_list[k]->flags & FLAG_PREFER)
1491a1788,1789
> if (!(peer_list[k]->flags & FLAG_CONFIG))
> unpeer(peer_list[k]);
1497a1796,1811
>
> #ifdef AUTOKEY
> /*
> * In manycast client mode we may have spooked a sizeable number
> * of servers that we don't need. If there are at least
> * NTP_MINCLOCK of them, the manycast message will be turned
> * off. By the time we get here we nay be ready to prune some of
> * them back, but we want to make sure all the candicates have
> * had a chance. If they didn't pass the sanity and intersection
> * tests, they have already been voted off the island.
> */
> if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
> resetmanycast();
> #endif /* AUTOKEY */
> sys_survivors = nlist;
>
1499c1813
< if (debug > 1) {
---
> if (debug > 2) {
1503,1504c1817,1819
< ntoa(&peer_list[i]->srcadr), peer_list[i]->offset,
< synch[i], peer_list[i]->pollsw);
---
> ntoa(&peer_list[i]->srcadr),
> peer_list[i]->offset, synch[i],
> peer_list[i]->pollsw);
1522a1838,1843
> *
> * Note that we go no further, unless the number of survivors is
> * a majority of the suckers that have been found reachable and
> * no prior source is available. This avoids the transient when
> * one of a flock of sources is out to lunch and just happens
> * to be the first survivor.
1523a1845,1846
> if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
> return;
1526,1543c1849,1861
< peer_list[i]->status = CTL_PST_SEL_SYNCCAND;
< peer_list[i]->flags |= FLAG_SYSPEER;
< poll_update(peer_list[i], peer_list[i]->hpoll);
< if (peer_list[i]->stratum == peer_list[0]->stratum) {
< leap_consensus |= peer_list[i]->leap;
< if (peer_list[i]->refclktype == REFCLK_ATOM_PPS)
< typepps = peer_list[i];
< if (peer_list[i] == sys_peer)
< typesystem = peer_list[i];
< if (peer_list[i]->flags & FLAG_PREFER) {
< typeprefer = peer_list[i];
< if (fabs(typeprefer->offset) <
< clock_max)
< pps_update = 1;
< }
< } else {
< if (peer_list[i] == sys_peer)
< sys_peer = 0;
---
> peer = peer_list[i];
> peer->status = CTL_PST_SEL_SYNCCAND;
> peer->flags |= FLAG_SYSPEER;
> poll_update(peer, peer->hpoll);
> if (peer->stratum == peer_list[0]->stratum) {
> leap_consensus |= peer->leap;
> if (peer->refclktype == REFCLK_ATOM_PPS &&
> peer->stratum < STRATUM_UNSPEC)
> typepps = peer;
> if (peer == osys_peer)
> typesystem = peer;
> if (peer->flags & FLAG_PREFER)
> sys_prefer = peer;
1559,1563c1877,1884
< osys_peer = sys_peer;
< if (typeprefer && (typeprefer->refclktype == REFCLK_LOCALCLOCK
< || typeprefer->sstclktype == CTL_SST_TS_TELEPHONE ||
< !typepps)) {
< sys_peer = typeprefer;
---
> if (sys_prefer)
> sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
> sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
> !typepps;
> else
> sw = 0;
> if (sw) {
> sys_peer = sys_prefer;
1566c1887
< sys_epsil = sys_peer->variance;
---
> sys_syserr = sys_peer->jitter;
1572c1893
< } else if (typepps && pps_update) {
---
> } else if (typepps) {
1576c1897
< sys_epsil = sys_peer->variance;
---
> sys_syserr = sys_peer->jitter;
1578,1579c1899,1901
< NLOG(NLOG_SYSEVENT) /* conditional syslog */
< msyslog(LOG_INFO, "pps sync enabled");
---
> NLOG(NLOG_SYSEVENT)
> msyslog(LOG_INFO,
> "pps sync enabled");
1583c1905,1906
< printf("select: pps offset %.6f\n", sys_offset);
---
> printf("select: pps offset %.6f\n",
> sys_offset);
1586c1909,1911
< if (!typesystem)
---
> if (typesystem)
> sys_peer = osys_peer;
> else
1590c1915
< sys_epsil = sys_peer->variance + sys_maxd;
---
> sys_syserr = sys_peer->jitter + sys_selerr;
1630,1633c1955,1962
< return ((fabs(peer->delay) + peer->rootdelay) / 2 +
< peer->rootdispersion + peer->disp +
< SQRT(peer->variance) + CLOCK_PHI * (current_time -
< peer->update));
---
> /*
> * Careful squeak here. The value returned must be greater than
> * zero blamed on the peer jitter, which must be at least the
> * square of sys_precision.
> */
> return ((peer->rootdelay + peer->delay) / 2 +
> peer->rootdispersion + peer->disp + clock_phi *
> (current_time - peer->update) + SQRT(peer->jitter));
1644,1647c1973,1976
< struct pkt xpkt;
< int find_rtt = (peer->cast_flags & MDF_MCAST) &&
< peer->hmode != MODE_BROADCAST;
< int sendlen;
---
> struct pkt xpkt; /* transmit packet */
> int sendlen, authlen;
> keyid_t xkeyid; /* transmit key ID */
> l_fp xmt_tx;
1650c1979
< * Initialize protocol fields.
---
> * Initialize transmit packet header fields.
1652,1653c1981,1982
< xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
< peer->version, peer->hmode);
---
> xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
> peer->hmode);
1658,1659c1987
< xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion +
< LOGTOD(sys_precision)));
---
> xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
1666,1669c1994,2001
< * Authenticate the packet if enabled and either configured or
< * the previous packet was authenticated. If for some reason the
< * key associated with the key identifier is not in the key
< * cache, then honk key zero.
---
> * If the received packet contains a MAC, the transmitted packet
> * is authenticated and contains a MAC. If not, the transmitted
> * packet is not authenticated.
> *
> * In the current I/O semantics the default interface is set
> * until after receiving a packet and setting the right
> * interface. So, the first packet goes out unauthenticated.
> * That's why the really icky test next is here.
1672,1674c2004,2017
< if (peer->flags & FLAG_AUTHENABLE) {
< u_long xkeyid;
< l_fp xmt_tx;
---
> if (!(peer->flags & FLAG_AUTHENABLE)) {
> get_systime(&peer->xmt);
> HTONL_FP(&peer->xmt, &xpkt.xmt);
> sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
> sendlen);
> peer->sent++;
> #ifdef DEBUG
> if (debug)
> printf("transmit: at %ld %s->%s mode %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode);
> #endif
> return;
> }
1675a2019,2027
> /*
> * The received packet contains a MAC, so the transmitted packet
> * must be authenticated. If autokey is enabled, fuss with the
> * various modes; otherwise, private key cryptography is used.
> */
> #ifdef AUTOKEY
> if ((peer->flags & FLAG_SKEY)) {
> u_int cmmd;
>
1677,1678c2029,2048
< * Transmit encrypted packet compensated for the
< * encryption delay.
---
> * The Public Key Dance (PKD): Cryptographic credentials
> * are contained in extension fields, each including a
> * 4-octet length/code word followed by a 4-octet
> * association ID and optional additional data. Optional
> * data includes a 4-octet data length field followed by
> * the data itself. Request messages are sent from a
> * configured association; response messages can be sent
> * from a configured association or can take the fast
> * path without ever matching an association. Response
> * messages have the same code as the request, but have
> * a response bit and possibly an error bit set. In this
> * implementation, a message may contain no more than
> * one command and no more than one response.
> *
> * Cryptographic session keys include both a public and
> * a private componet. Request and response messages
> * using extension fields are always sent with the
> * private component set to zero. Packets without
> * extension fields indlude the private component when
> * the session key is generated.
1680,1682c2050,2051
< #ifdef MD5
< if (peer->flags & FLAG_SKEY) {
<
---
> while (1) {
>
1684,1692c2053,2070
< * In autokey mode, allocate and initialize a
< * key list if not already done. Then, use the
< * list in inverse order, discarding keys once
< * used. Keep the latest key around until the
< * next one, so clients can use client/server
< * packets to compute propagation delay. Note we
< * have to wait until the receive side of the
< * socket is bound and the server address
< * confirmed.
---
> * Allocate and initialize a keylist if not
> * already done. Then, use the list in inverse
> * order, discarding keys once used. Keep the
> * latest key around until the next one, so
> * clients can use client/server packets to
> * compute propagation delay.
> *
> * Note that once a key is used from the list,
> * it is retained in the key cache until the
> * next key is used. This is to allow a client
> * to retrieve the encrypted session key
> * identifier to verify authenticity.
> *
> * If for some reason a key is no longer in the
> * key cache, a birthday has happened and the
> * pseudo-random sequence is probably broken. In
> * that case, purge the keylist and regenerate
> * it.
1694,1716c2072,2080
< if (ntohl(peer->dstadr->sin.sin_addr.s_addr) ==
< 0 &&
< ntohl(peer->dstadr->bcast.sin_addr.s_addr) == 0)
< peer->keyid = 0;
< else {
< if (peer->keylist == 0) {
< make_keylist(peer);
< } else {
< authtrust(peer->keylist[peer->keynumber], 0);
< if (peer->keynumber == 0)
< make_keylist(peer);
< else {
< peer->keynumber--;
< xkeyid = peer->keylist[peer->keynumber];
< if (!authistrusted(xkeyid))
< make_keylist(peer);
< }
< }
< peer->keyid = peer->keylist[peer->keynumber];
< xpkt.keyid1 = htonl(2 * sizeof(u_int32));
< xpkt.keyid2 = htonl(sys_private);
< sendlen += 2 * sizeof(u_int32);
< }
---
> if (peer->keynumber == 0)
> make_keylist(peer, peer->dstadr);
> else
> peer->keynumber--;
> xkeyid = peer->keylist[peer->keynumber];
> if (authistrusted(xkeyid))
> break;
> else
> key_expire(peer);
1718,1729c2082,2083
< #endif /* MD5 */
< xkeyid = peer->keyid;
< get_systime(&peer->xmt);
< L_ADD(&peer->xmt, &sys_authdelay);
< HTONL_FP(&peer->xmt, &xpkt.xmt);
< sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt,
< sendlen);
< get_systime(&xmt_tx);
< sendpkt(&peer->srcadr, find_rtt ? any_interface :
< peer->dstadr, ((peer->cast_flags & MDF_MCAST) &&
< !find_rtt) ? ((peer->cast_flags & MDF_ACAST) ? -7 :
< peer->ttl) : -7, &xpkt, sendlen);
---
> peer->keyid = xkeyid;
> switch (peer->hmode) {
1732,1733c2086,2089
< * Calculate the encryption delay. Keep the minimum over
< * the latest two samples.
---
> * In broadcast mode the autokey values are required.
> * Send them when a new keylist is generated; otherwise,
> * send the association ID so the client can request
> * them at other times.
1735,1751c2091,2099
< L_SUB(&xmt_tx, &peer->xmt);
< L_ADD(&xmt_tx, &sys_authdelay);
< sys_authdly[1] = sys_authdly[0];
< sys_authdly[0] = xmt_tx.l_uf;
< if (sys_authdly[0] < sys_authdly[1])
< sys_authdelay.l_uf = sys_authdly[0];
< else
< sys_authdelay.l_uf = sys_authdly[1];
< peer->sent++;
< #ifdef DEBUG
< if (debug)
< printf(
< "transmit: at %ld to %s mode %d keyid %08lx index %d\n",
< current_time, ntoa(&peer->srcadr),
< peer->hmode, xkeyid, peer->keynumber);
< #endif
< } else {
---
> case MODE_BROADCAST:
> if (peer->flags & FLAG_ASSOC)
> cmmd = CRYPTO_AUTO | CRYPTO_RESP;
> else
> cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, cmmd, 0, peer->associd);
> break;
>
1753c2101,2119
< * Transmit non-authenticated packet.
---
> * In symmetric modes the public key, leapsecond table,
> * agreement parameters and autokey values are required.
> *
> * 1. If a response is pending, always send it first.
> *
> * 2. Don't send anything except a public-key request
> * until the public key has been stored.
> *
> * 3. Once the public key has been stored, don't send
> * anything except an agreement parameter request
> * until the agreement parameters have been stored.
> *
> * 4. Once the argeement parameters have been stored,
> * don't send anything except a public value request
> * until the agreed key has been stored.
> *
> * 5. When the agreed key has been stored and the key
> * list is regenerated, send the autokey values
> * gratis unless they have already been sent.
1755,1761c2121,2285
< get_systime(&(peer->xmt));
< HTONL_FP(&peer->xmt, &xpkt.xmt);
< sendpkt(&(peer->srcadr), find_rtt ? any_interface :
< peer->dstadr, ((peer->cast_flags & MDF_MCAST) &&
< !find_rtt) ? ((peer->cast_flags & MDF_ACAST) ? -7 :
< peer->ttl) : -8, &xpkt, sendlen);
< peer->sent++;
---
> case MODE_ACTIVE:
> case MODE_PASSIVE:
> #ifdef PUBKEY
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (!peer->crypto)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_ASSOC,
> peer->hcookie, peer->assoc);
> else if (!crypto_flags &&
> peer->pcookie.tstamp == 0 && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> else if (crypto_flags && peer->pubkey.ptr ==
> NULL)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_NAME, peer->hcookie,
> peer->assoc);
> else if (peer->crypto & CRYPTO_FLAG_CERT)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_CERT, peer->hcookie,
> peer->assoc);
> else if (crypto_flags && peer->crypto &
> CRYPTO_FLAG_DH && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_DHPAR,
> peer->hcookie, peer->assoc);
> else if (crypto_flags && peer->pcookie.tstamp ==
> 0 && sys_leap != LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_DH, peer->hcookie,
> peer->assoc);
> #else
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (peer->pcookie.tstamp == 0 && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> else if (!(peer->flags & FLAG_AUTOKEY))
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO, peer->hcookie,
> peer->assoc);
> else if ((peer->flags & FLAG_ASSOC) &&
> (peer->cmmd >> 16) != CRYPTO_AUTO)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO | CRYPTO_RESP,
> peer->hcookie, peer->associd);
> #ifdef PUBKEY
> else if (peer->crypto & CRYPTO_FLAG_TAI)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_TAI, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> peer->cmmd = 0;
> break;
>
> /*
> * In client mode, the public key, host cookie and
> * autokey values are required. In broadcast client
> * mode, these values must be acquired during the
> * client/server exchange to avoid having to wait until
> * the next key list regeneration. Otherwise, the poor
> * dude may die a lingering death until becoming
> * unreachable and attempting rebirth. Note that we ask
> * for the cookie at each key list regeneration anyway.
> */
> case MODE_CLIENT:
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (!peer->crypto)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_ASSOC,
> peer->hcookie, peer->assoc);
> #ifdef PUBKEY
> else if (crypto_flags && peer->pubkey.ptr ==
> NULL)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_NAME, peer->hcookie,
> peer->assoc);
> else if (peer->crypto & CRYPTO_FLAG_CERT)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_CERT, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> else if (peer->pcookie.tstamp == 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> else if (!(peer->flags & FLAG_AUTOKEY) &&
> (peer->cast_flags & MDF_BCLNT))
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO, peer->hcookie,
> peer->assoc);
> #ifdef PUBKEY
> else if (peer->crypto & CRYPTO_FLAG_TAI)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_TAI, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> peer->cmmd = 0;
> break;
> }
>
> /*
> * If extension fields are present, we must use a
> * private value of zero and force min poll interval.
> * Most intricate.
> */
> if (sendlen > LEN_PKT_NOMAC)
> session_key(&peer->dstadr->sin, &peer->srcadr,
> xkeyid, 0, 2);
> }
> #endif /* AUTOKEY */
> xkeyid = peer->keyid;
> get_systime(&peer->xmt);
> L_ADD(&peer->xmt, &sys_authdelay);
> HTONL_FP(&peer->xmt, &xpkt.xmt);
> authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
> if (authlen == 0) {
> msyslog(LOG_NOTICE,
> "transmit: no encryption key found");
> peer->flash |= TEST4 | TEST5;
> return;
> }
> sendlen += authlen;
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY)
> authtrust(xkeyid, 0);
> #endif /* AUTOKEY */
> get_systime(&xmt_tx);
> if (sendlen > sizeof(xpkt)) {
> msyslog(LOG_ERR, "buffer overflow %u", sendlen);
> exit(-1);
> }
> sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
>
> /*
> * Calculate the encryption delay. Keep the minimum over
> * the latest two samples.
> */
> L_SUB(&xmt_tx, &peer->xmt);
> L_ADD(&xmt_tx, &sys_authdelay);
> sys_authdly[1] = sys_authdly[0];
> sys_authdly[0] = xmt_tx.l_uf;
> if (sys_authdly[0] < sys_authdly[1])
> sys_authdelay.l_uf = sys_authdly[0];
> else
> sys_authdelay.l_uf = sys_authdly[1];
> peer->sent++;
> #ifdef AUTOKEY
1763,1766c2287,2292
< if (debug)
< printf("transmit: at %ld to %s mode %d\n",
< current_time, ntoa(&peer->srcadr),
< peer->hmode);
---
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
> authlen, peer->keynumber);
1768c2294,2303
< }
---
> #else
> #ifdef DEBUG
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
> authlen);
> #endif
> #endif /* AUTOKEY */
1770a2306
>
1772c2308,2309
< * fast_xmit - Send packet for nonpersistent association.
---
> * fast_xmit - Send packet for nonpersistent association. Note that
> * neither the source or destination can be a broadcast address.
1778c2315,2316
< u_long xkeyid /* transmit key ID */
---
> keyid_t xkeyid, /* transmit key ID */
> int mask /* restrict mask */
1781,1784c2319,2323
< struct pkt xpkt;
< struct pkt *rpkt;
< int sendlen;
< l_fp xmt_ts;
---
> struct pkt xpkt; /* transmit packet structure */
> struct pkt *rpkt; /* receive packet structure */
> l_fp xmt_ts; /* transmit timestamp */
> l_fp xmt_tx; /* transmit timestamp after authent */
> int sendlen, authlen;
1787,1788c2326,2329
< * Initialize transmit packet header fields in the receive
< * buffer provided. We leave some fields intact as received.
---
> * Initialize transmit packet header fields from the receive
> * buffer provided. We leave some fields intact as received. If
> * the gazinta was from a multicast address, the gazouta must go
> * out another way.
1791,1793c2332,2354
< xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
< PKT_VERSION(rpkt->li_vn_mode), xmode);
< xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
---
> if (rbufp->dstadr->flags & INT_MULTICAST)
> rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
>
> /*
> * If the caller is restricted, return a kiss-of-death packet;
> * otherwise, smooch politely.
> */
> if (mask & (RES_DONTSERVE | RES_LIMITED)) {
> if (!(mask & RES_DEMOBILIZE)) {
> return;
> } else {
> xpkt.li_vn_mode =
> PKT_LI_VN_MODE(LEAP_NOTINSYNC,
> PKT_VERSION(rpkt->li_vn_mode), xmode);
> xpkt.stratum = STRATUM_UNSPEC;
> memcpy(&xpkt.refid, "DENY", 4);
> }
> } else {
> xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
> PKT_VERSION(rpkt->li_vn_mode), xmode);
> xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
> xpkt.refid = sys_refid;
> }
1797,1799c2358,2359
< xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion +
< LOGTOD(sys_precision)));
< xpkt.refid = sys_refid;
---
> xpkt.rootdispersion =
> HTONS_FP(DTOUFP(sys_rootdispersion));
1803,1805d2362
< sendlen = LEN_PKT_NOMAC;
< if (rbufp->recv_length > sendlen) {
< l_fp xmt_tx;
1807,1815c2364,2370
< /*
< * Transmit encrypted packet compensated for the
< * encryption delay.
< */
< if (xkeyid > NTP_MAXKEY) {
< xpkt.keyid1 = htonl(2 * sizeof(u_int32));
< xpkt.keyid2 = htonl(sys_private);
< sendlen += 2 * sizeof(u_int32);
< }
---
> /*
> * If the received packet contains a MAC, the transmitted packet
> * is authenticated and contains a MAC. If not, the transmitted
> * packet is not authenticated.
> */
> sendlen = LEN_PKT_NOMAC;
> if (rbufp->recv_length == sendlen) {
1817d2371
< L_ADD(&xmt_ts, &sys_authdelay);
1819c2373
< sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt,
---
> sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
1821,1836d2374
< get_systime(&xmt_tx);
< sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, -9, &xpkt,
< sendlen);
<
< /*
< * Calculate the encryption delay. Keep the minimum over
< * the latest two samples.
< */
< L_SUB(&xmt_tx, &xmt_ts);
< L_ADD(&xmt_tx, &sys_authdelay);
< sys_authdly[1] = sys_authdly[0];
< sys_authdly[0] = xmt_tx.l_uf;
< if (sys_authdly[0] < sys_authdly[1])
< sys_authdelay.l_uf = sys_authdly[0];
< else
< sys_authdelay.l_uf = sys_authdly[1];
1839,1842c2377,2379
< printf(
< "transmit: at %ld to %s mode %d keyid %08lx\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< xmode, xkeyid);
---
> printf("transmit: at %ld %s->%s mode %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), xmode);
1844c2381,2382
< } else {
---
> return;
> }
1845a2384,2396
> /*
> * The received packet contains a MAC, so the transmitted packet
> * must be authenticated. For private-key cryptography, use the
> * predefined private keys to generate the cryptosum. For
> * autokey cryptography, use the server private value to
> * generate the cookie, which is unique for every source-
> * destination-key ID combination.
> */
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY) {
> keyid_t cookie;
> u_int code, associd;
>
1847c2398,2404
< * Transmit non-authenticated packet.
---
> * The only way to get here is a reply to a legitimate
> * client request message, so the mode must be
> * MODE_SERVER. If an extension field is present, there
> * can be only one and that must be a command. Do what
> * needs, but with private value of zero so the poor
> * jerk can decode it. If no extension field is present,
> * use the cookie to generate the session key.
1849,1852c2406,2449
< get_systime(&xmt_ts);
< HTONL_FP(&xmt_ts, &xpkt.xmt);
< sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, -10, &xpkt,
< sendlen);
---
> code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
> cookie = session_key(&rbufp->recv_srcadr,
> &rbufp->dstadr->sin, 0, sys_private, 0);
> associd = htonl(rpkt->exten[1]);
> if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
> sizeof(u_int32)) {
> session_key(&rbufp->dstadr->sin,
> &rbufp->recv_srcadr, xkeyid, 0, 2);
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, code, cookie, associd);
> } else {
> session_key(&rbufp->dstadr->sin,
> &rbufp->recv_srcadr, xkeyid, cookie, 2);
> }
> }
> #endif /* AUTOKEY */
> get_systime(&xmt_ts);
> L_ADD(&xmt_ts, &sys_authdelay);
> HTONL_FP(&xmt_ts, &xpkt.xmt);
> authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
> sendlen += authlen;
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY)
> authtrust(xkeyid, 0);
> #endif /* AUTOKEY */
> get_systime(&xmt_tx);
> if (sendlen > sizeof(xpkt)) {
> msyslog(LOG_ERR, "buffer overflow %u", sendlen);
> exit(-1);
> }
> sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
>
> /*
> * Calculate the encryption delay. Keep the minimum over the
> * latest two samples.
> */
> L_SUB(&xmt_tx, &xmt_ts);
> L_ADD(&xmt_tx, &sys_authdelay);
> sys_authdly[1] = sys_authdly[0];
> sys_authdly[0] = xmt_tx.l_uf;
> if (sys_authdly[0] < sys_authdly[1])
> sys_authdelay.l_uf = sys_authdly[0];
> else
> sys_authdelay.l_uf = sys_authdly[1];
1854,1857c2451,2456
< if (debug)
< printf("transmit: at %ld to %s mode %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< xmode);
---
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
> authlen);
1859d2457
< }
1862c2460,2461
< #ifdef MD5
---
>
> #ifdef AUTOKEY
1864c2463
< * Compute key list
---
> * key_expire - purge the key list
1866,1868c2465,2467
< static void
< make_keylist(
< struct peer *peer
---
> void
> key_expire(
> struct peer *peer /* peer structure pointer */
1872,1873d2470
< u_long keyid;
< u_long ltemp;
1875,1892c2472,2476
< /*
< * Allocate the key list if necessary.
< */
< if (peer->keylist == 0)
< peer->keylist = (u_long *)emalloc(sizeof(u_long) *
< NTP_MAXSESSION);
<
< /*
< * Generate an initial key ID which is unique and greater than
< * NTP_MAXKEY.
< */
< while (1) {
< keyid = (u_long)RANDOM & 0xffffffff;
< if (keyid <= NTP_MAXKEY)
< continue;
< if (authhavekey(keyid))
< continue;
< break;
---
> if (peer->keylist != NULL) {
> for (i = 0; i <= peer->keynumber; i++)
> authtrust(peer->keylist[i], 0);
> free(peer->keylist);
> peer->keylist = NULL;
1894,1914c2478,2482
<
< /*
< * Generate up to NTP_MAXSESSION session keys. Stop if the
< * next one would not be unique or not a session key ID or if
< * it would expire before the next poll.
< */
< ltemp = sys_automax;
< for (i = 0; i < NTP_MAXSESSION; i++) {
< peer->keylist[i] = keyid;
< peer->keynumber = i;
< keyid = session_key(
< ntohl(peer->dstadr->sin.sin_addr.s_addr),
< (peer->hmode == MODE_BROADCAST || (peer->flags &
< FLAG_MCAST2)) ?
< ntohl(peer->dstadr->bcast.sin_addr.s_addr):
< ntohl(peer->srcadr.sin_addr.s_addr), keyid, ltemp);
< ltemp -= 1 << peer->hpoll;
< if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
< ltemp <= (1 << (peer->hpoll + 1)))
< break;
< }
---
> peer->keynumber = peer->sndauto.seq = 0;
> #ifdef DEBUG
> if (debug)
> printf("key_expire: at %lu\n", current_time);
> #endif
1916c2484
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
2035a2604
> sys_jitter = LOGTOD(sys_precision);
2040c2609,2610
< sys_peer = 0;
---
> sys_peer = NULL;
> sys_survivors = 0;
2044d2613
< #if defined(DES) || defined(MD5)
2046,2048d2614
< #else
< sys_authenticate = 0;
< #endif
2059a2626
> #ifdef AUTOKEY
2060a2628
> #endif /* AUTOKEY */
2069c2637
< msyslog(LOG_DEBUG, "kern_enable is %d", kern_enable);
---
> pps_enable = 0;
2073c2641,2642
< * Some system clocks should only be adjusted in 10ms increments.
---
> * Some system clocks should only be adjusted in 10ms
> * increments.
2178a2748,2765
> case PROTO_PPS:
>
> /*
> * Turn on/off PPS discipline
> */
> pps_enable = (int)value;
> break;
>
> #ifdef REFCLOCK
> case PROTO_CAL:
>
> /*
> * Turn on/off refclock calibrate
> */
> cal_enable = (int)value;
> break;
> #endif
>
< * $FreeBSD: head/contrib/ntp/ntpd/ntp_proto.c 56749 2000-01-28 15:02:35Z roberto $
---
> * $FreeBSD: head/contrib/ntp/ntpd/ntp_proto.c 82505 2001-08-29 15:15:59Z roberto $
10,13d9
< #include <stdio.h>
< #include <sys/types.h>
< #include <sys/time.h>
<
18a15
> #include "ntp_crypto.h"
19a17,18
> #include <stdio.h>
>
29c28
< * System variables are declared here. See Section 3.2 of the
---
> * System variables are declared here. See Section 3.2 of the
35,36c34,35
< double sys_rootdelay; /* distance to current sync source */
< double sys_rootdispersion; /* dispersion of system clock */
---
> double sys_rootdelay; /* roundtrip delay to primary source */
> double sys_rootdispersion; /* dispersion to primary source */
40a40,41
> struct peer *sys_prefer; /* our cherished peer */
> #ifdef AUTOKEY
41a43
> #endif /* AUTOKEY */
52,55c54,62
< static double sys_maxd; /* select error (squares) */
< static double sys_epsil; /* system error (squares) */
< u_long sys_private; /* private value for session seed */
< int sys_manycastserver; /* 1 => respond to manycast client pkts */
---
> static double sys_selerr; /* select error (squares) */
> static double sys_syserr; /* system error (squares) */
> keyid_t sys_private; /* private value for session seed */
> int sys_manycastserver; /* respond to manycast client pkts */
> u_int sys_survivors; /* truest of the truechimers */
> int peer_ntpdate; /* active peers in ntpdate mode */
> #ifdef AUTOKEY
> char *sys_hostname; /* gethostname() name */
> #endif /* AUTOKEY */
73c80
< static void fast_xmit P((struct recvbuf *, int, u_long));
---
> static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
76,78d82
< #ifdef MD5
< static void make_keylist P((struct peer *));
< #endif /* MD5 */
79a84
>
96,99c101,104
< * Determine reachability and diddle things if we
< * haven't heard from the host for a while. If the peer
< * is not configured and not likely to stay around,
< * we exhaust it.
---
> * The polling state machine. There are two kinds of
> * machines, those that never expect a reply (broadcast
> * and manycast server modes) and those that do (all
> * other modes). The dance is intricate...
100a106,163
> if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
>
> /*
> * In broadcast mode the poll interval is fixed
> * at minpoll and the ttl at ttlmax.
> */
> hpoll = peer->minpoll;
> peer->ttl = peer->ttlmax;
> #ifdef AUTOKEY
> } else if (peer->cast_flags & MDF_ACAST) {
>
> /*
> * In manycast mode we start with the minpoll
> * interval and ttl. However, the actual poll
> * interval is eight times the nominal poll
> * interval shown here. If fewer than three
> * servers are found, the ttl is increased by
> * one and we try again. If this continues to
> * the max ttl, the poll interval is bumped by
> * one and we try again. If at least three
> * servers are found, the poll interval
> * increases with the system poll interval to
> * the max and we continue indefinately.
> * However, about once per day when the
> * agreement parameters are refreshed, the
> * manycast clients are reset and we start from
> * the beginning. This is to catch and clamp the
> * ttl to the lowest practical value and avoid
> * knocking on spurious doors.
> */
> if (sys_survivors < NTP_MINCLOCK && peer->ttl <
> peer->ttlmax)
> peer->ttl++;
> hpoll = sys_poll;
> #endif /* AUTOKEY */
> } else {
>
> /*
> * For associations expecting a reply, the
> * watchdog counter is bumped by one if the peer
> * has not been heard since the previous poll.
> * If the counter reaches the max, the peer is
> * demobilized if not configured and just
> * cleared if it is, but in this case the poll
> * interval is bumped by one.
> */
> if (peer->unreach < NTP_UNREACH) {
> peer->unreach++;
> } else if (!(peer->flags & FLAG_CONFIG)) {
> unpeer(peer);
> clock_select();
> return;
>
> } else {
> peer_clear(peer);
> hpoll++;
> }
> }
102,109d164
< if (oreach & 0x01)
< peer->valid++;
< if (oreach & 0x80)
< peer->valid--;
< if (!(peer->flags & FLAG_CONFIG) && peer->valid >
< NTP_SHIFT / 2 && (peer->reach & 0x80) &&
< peer->status < CTL_PST_SEL_SYNCCAND)
< peer->reach = 0;
114,115c169,170
< * If this is an uncofigured association and
< * has become unreachable, demobilize it.
---
> * If this association has become unreachable,
> * clear it and raise a trap.
120d174
< peer_clear(peer);
122a177
> clock_select();
123a179,181
> } else {
> peer_clear(peer);
> hpoll = peer->minpoll;
126,146c184,185
<
< /*
< * We would like to respond quickly when the
< * peer comes back to life. If the probes since
< * becoming unreachable are less than
< * NTP_UNREACH, clamp the poll interval to the
< * minimum. In order to minimize the network
< * traffic, the interval gradually ramps up the
< * the maximum after that.
< */
< peer->ppoll = peer->maxpoll;
< if (peer->unreach < NTP_UNREACH) {
< if (peer->hmode == MODE_CLIENT)
< peer->unreach++;
< hpoll = peer->minpoll;
< } else {
< hpoll++;
< }
< if (peer->flags & FLAG_BURST)
< peer->burst = 2;
<
---
> if (peer->flags & FLAG_IBURST)
> peer->burst = NTP_SHIFT;
150,156c189,198
< * Here the peer is reachable. If there is no
< * system peer or if the stratum of the system
< * peer is greater than this peer, clamp the
< * poll interval to the minimum. If less than
< * two samples are in the reachability register,
< * reduce the interval; if more than six samples
< * are in the register, increase the interval.
---
> * Here the peer is reachable. If it has not
> * been heard for three consecutive polls, stuff
> * the clock filter. Next, determine the poll
> * interval. If the peer is a synchronization
> * candidate, use the system poll interval. If
> * the peer is not sane, increase it by one. If
> * the number of valid updates is not greater
> * than half the register size, clamp it to the
> * minimum. This is to quickly recover the time
> * variables when a noisy peer shows life.
158,163c200
< peer->unreach = 0;
< if (sys_peer == 0)
< hpoll = peer->minpoll;
< else if (sys_peer->stratum > peer->stratum)
< hpoll = peer->minpoll;
< if ((peer->reach & 0x03) == 0) {
---
> if (!(peer->reach & 0x07)) {
167,169c204,206
< if (peer->valid <= 2)
< hpoll--;
< else if (peer->valid >= NTP_SHIFT - 2)
---
> if ((peer->stratum > 1 && peer->refid ==
> peer->dstadr->sin.sin_addr.s_addr) ||
> peer->stratum >= STRATUM_UNSPEC)
170a208,209
> else
> hpoll = sys_poll;
177,178c216,223
< if (peer->flags & FLAG_MCAST2) {
< peer->flags &= ~FLAG_BURST;
---
>
> /*
> * If a broadcast client at this point, the
> * burst has concluded, so we switch to client
> * mode and purge the keylist, since no further
> * transmissions will be made.
> */
> if (peer->cast_flags & MDF_BCLNT) {
179a225,227
> #ifdef AUTOKEY
> key_expire(peer);
> #endif /* AUTOKEY */
181d228
< clock_select();
182a230,247
> clock_select();
>
> /*
> * If ntpdate mode and the clock has not been
> * set and all peers have completed the burst,
> * we declare a successful failure.
> */
> if (mode_ntpdate) {
> peer_ntpdate--;
> if (peer_ntpdate > 0)
> return;
> NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
> msyslog(LOG_NOTICE,
> "no reply; clock not set");
> printf(
> "ntpd: no reply; clock not set\n");
> exit(0);
> }
183a249
>
185a252,253
> peer->outdate = current_time;
> poll_update(peer, hpoll);
188,194c256,259
< * We need to be very careful about honking uncivilized time. If
< * not operating in broadcast mode, honk in all except broadcast
< * client mode. If operating in broadcast mode and synchronized
< * to a real source, honk except when the peer is the local-
< * clock driver and the prefer flag is not set. In other words,
< * in broadcast mode we never honk unless known to be
< * synchronized to real time.
---
> * We need to be very careful about honking uncivilized time.
> * Never transmit if in broadcast client mode or access denied.
> * If in broadcast mode, transmit only if synchronized to a
> * valid source.
196,202c261,265
< if (peer->hmode != MODE_BROADCAST) {
< if (peer->hmode != MODE_BCLIENT)
< peer_xmit(peer);
< } else if (sys_peer != 0 && sys_leap != LEAP_NOTINSYNC) {
< if (!(sys_peer->refclktype == REFCLK_LOCALCLOCK &&
< !(sys_peer->flags & FLAG_PREFER)))
< peer_xmit(peer);
---
> if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
> return;
> } else if (peer->hmode == MODE_BROADCAST) {
> if (sys_peer == NULL)
> return;
204,205c267
< peer->outdate = current_time;
< poll_update(peer, hpoll);
---
> peer_xmit(peer);
221,222c283,284
< int has_mac; /* has MAC field */
< int authlen; /* length of MAC field */
---
> int has_mac; /* length of MAC field */
> int authlen; /* offset of MAC field */
224,227c286,290
< int is_mystic; /* session key exists */
< int is_error; /* parse error */
< /* u_long pkeyid; */
< u_long skeyid, tkeyid;
---
> keyid_t skeyid; /* cryptographic keys */
> struct sockaddr_in *dstadr_sin; /* active runway */
> #ifdef AUTOKEY
> keyid_t pkeyid, tkeyid; /* cryptographic keys */
> #endif /* AUTOKEY */
232c295,302
< * Monitor the packet and get restrictions
---
> * Monitor the packet and get restrictions. Note that the packet
> * length for control and private mode packets must be checked
> * by the service routines. Note that no statistics counters are
> * recorded for restrict violations, since these counters are in
> * the restriction routine. Note the careful distinctions here
> * between a packet with a format error and a packet that is
> * simply discarded without prejudice. Some restrictions have to
> * be handled later in order to generate a kiss-of-death packet.
237,238c307,309
< if (debug > 1)
< printf("receive: from %s restrict %02x\n",
---
> if (debug > 2)
> printf("receive: at %ld %s<-%s restrict %02x\n",
> current_time, ntoa(&rbufp->dstadr->sin),
242,246c313,318
< return;
<
< /*
< * Discard packets with invalid version number.
< */
---
> return; /* no anything */
> if (!(SRCPORT(&rbufp->recv_srcadr) == NTP_PORT ||
> SRCPORT(&rbufp->recv_srcadr) >= IPPORT_RESERVED)) {
> sys_badlength++;
> return; /* invalid port */
> }
248,252c320,325
< if (PKT_VERSION(pkt->li_vn_mode) >= NTP_VERSION)
< sys_newversionpkt++;
< else if (PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION)
< sys_oldversionpkt++;
< else {
---
> if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
> sys_newversionpkt++; /* new version */
> } else if (!(restrict_mask & RES_VERSION) &&
> PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
> sys_oldversionpkt++; /* old version */
> } else {
254c327
< return;
---
> return; /* invalid version */
256,261d328
<
< /*
< * Restrict control/private mode packets. Note that packet
< * length has to be checked in the control/private mode protocol
< * module.
< */
264c331
< return;
---
> return; /* no query private */
271c338
< return;
---
> return; /* no query control */
274a342,345
> if (rbufp->recv_length < LEN_PKT_NOMAC) {
> sys_badlength++;
> return; /* runt packet */
> }
277c348
< * Restrict revenue packets.
---
> * Validate mode. Note that NTPv1 is no longer supported.
279,280c350,354
< if (restrict_mask & RES_DONTSERVE)
< return;
---
> hismode = (int)PKT_MODE(pkt->li_vn_mode);
> if (hismode == MODE_UNSPEC) {
> sys_badlength++;
> return; /* invalid mode */
> }
282,291d355
< /*
< * See if we only accept limited number of clients from the net
< * this guy is from. Note: the flag is determined dynamically
< * within restrictions()
< */
< if (restrict_mask & RES_LIMITED) {
< sys_limitrejected++;
< return;
< }
<
293c357,358
< * If we are not a broadcast client, ignore broadcast packets.
---
> * Discard broadcast packets received on the wildcard interface
> * or if not enabled as broadcast client.
295,296c360,361
< if ((PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
< !sys_bclient))
---
> if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
> (rbufp->dstadr == any_interface || !sys_bclient))
300,306c365,373
< * This is really awful ugly. We figure out whether an extension
< * field is present and then measure the MAC size. If the number
< * of words following the packet header is less than or equal to
< * 5, no extension field is present and these words constitute
< * the MAC. If the number of words is greater than 5, an
< * extension field is present and the first word contains the
< * length of the extension field and the MAC follows that.
---
> * Parse the extension field if present. We figure out whether
> * an extension field is present by measuring the MAC size. If
> * the number of words following the packet header is 0 or 1, no
> * MAC is present and the packet is not authenticated. If 1, the
> * packet is a reply to a previous request that failed to
> * authenticate. If 3, the packet is authenticated with DES; if
> * 5, the packet is authenticated with MD5. If greater than 5,
> * an extension field is present. If 2 or 4, the packet is a
> * runt and goes poof! with a brilliant flash.
308,310c375,378
< has_mac = 0;
< /* pkeyid = 0; */
< skeyid = tkeyid = 0;
---
> skeyid = 0;
> #ifdef AUTOKEY
> pkeyid = tkeyid = 0;
> #endif /* AUTOKEY */
312,318c380,383
< has_mac = rbufp->recv_length - authlen;
< if (has_mac <= 5 * sizeof(u_int32)) {
< skeyid = (u_long)ntohl(pkt->keyid1) & 0xffffffff;
< } else {
< authlen += (u_long)ntohl(pkt->keyid1) & 0xffffffff;
< has_mac = rbufp->recv_length - authlen;
< if (authlen <= 0) {
---
> while ((has_mac = rbufp->recv_length - authlen) > 0) {
> int temp;
>
> if (has_mac % 4 != 0 || has_mac < 0) {
321a387,390
> if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
> MAX_MAC_LEN) {
> skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
> break;
323,349c392,401
< /*
< * Note that keyid3 is actually the key ident of the
< * MAC itself.
< */
< /* pkeyid = (u_long)ntohl(pkt->keyid2) & 0xffffffff; */
< skeyid = tkeyid = (u_long)ntohl(pkt->keyid3) &
< 0xffffffff;
< }
<
< /*
< * Figure out his mode and validate it.
< */
< hismode = (int)PKT_MODE(pkt->li_vn_mode);
< if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION && hismode ==
< 0) {
< /*
< * Easy. If it is from the NTP port it is
< * a sym act, else client.
< */
< if (SRCPORT(&rbufp->recv_srcadr) == NTP_PORT)
< hismode = MODE_ACTIVE;
< else
< hismode = MODE_CLIENT;
< } else {
< if (hismode != MODE_ACTIVE && hismode != MODE_PASSIVE &&
< hismode != MODE_SERVER && hismode != MODE_CLIENT &&
< hismode != MODE_BROADCAST)
---
> } else if (has_mac > MAX_MAC_LEN) {
> temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
> 0xffff;
> if (temp < 4 || temp % 4 != 0) {
> sys_badlength++;
> return;
> }
> authlen += temp;
> } else {
> sys_badlength++;
350a403
> }
354,355c407,423
< * If he included a mac field, decrypt it to see if it is
< * authentic.
---
> * We have tossed out as many buggy packets as possible early in
> * the game to reduce the exposure to a clogging attack. Now we
> * have to burn some cycles to find the association and
> * authenticate the packet if required. Note that we burn only
> * MD5 or DES cycles, again to reduce exposure. There may be no
> * matching association and that's okay.
> *
> * More on the autokey mambo. Normally the local interface is
> * found when the association was mobilized with respect to a
> * designated remote address. We assume packets arriving from
> * the remote address arrive via this interface and the local
> * address used to construct the autokey is the unicast address
> * of the interface. However, if the sender is a broadcaster,
> * the interface broadcast address is used instead.
> * Notwithstanding this technobabble, if the sender is a
> * multicaster, the broadcast address is null, so we use the
> * unicast address anyway. Don't ask.
357c425,428
< is_authentic = is_mystic = 0;
---
> peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
> hismode, &retcode);
> is_authentic = 0;
> dstadr_sin = &rbufp->dstadr->sin;
361,363c432,434
< printf("receive: at %ld from %s mode %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< hismode);
---
> printf("receive: at %ld %s<-%s mode %d code %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), hismode, retcode);
366,369c437,444
< is_mystic = authistrusted(skeyid);
< #ifdef MD5
< if (skeyid > NTP_MAXKEY && !is_mystic) {
<
---
> #ifdef AUTOKEY
> /*
> * For autokey modes, generate the session key
> * and install in the key cache. Use the socket
> * broadcast or unicast address as appropriate.
> */
> if (skeyid > NTP_MAXKEY) {
>
371,377c446,468
< * For multicast mode, generate the session key
< * and install in the key cache. For client
< * mode, generate the session key for the
< * unicast address. For server mode, the session
< * key should already be in the key cache, since
< * it was generated when the last request was
< * sent.
---
> * More on the autokey dance (AKD). A cookie is
> * constructed from public and private values.
> * For broadcast packets, the cookie is public
> * (zero). For packets that match no
> * association, the cookie is hashed from the
> * addresses and private value. For server
> * packets, the cookie was previously obtained
> * from the server. For symmetric modes, the
> * cookie was previously constructed using an
> * agreement protocol; however, should PKI be
> * unavailable, we construct a fake agreement as
> * the EXOR of the peer and host cookies.
> *
> * hismode ephemeral persistent
> * =======================================
> * active 0 cookie#
> * passive 0% cookie#
> * client sys cookie 0%
> * server 0% sys cookie
> * broadcast 0 0
> *
> * # if unsync, 0
> * % can't happen
379a471,501
>
> /*
> * For broadcaster, use the interface
> * broadcast address when available;
> * otherwise, use the unicast address
> * found when the association was
> * mobilized.
> */
> pkeyid = 0;
> if (rbufp->dstadr->bcast.sin_addr.s_addr
> != 0)
> dstadr_sin =
> &rbufp->dstadr->bcast;
> } else if (peer == NULL) {
> pkeyid = session_key(
> &rbufp->recv_srcadr, dstadr_sin, 0,
> sys_private, 0);
> } else {
> pkeyid = peer->pcookie.key;
> }
>
> /*
> * The session key includes both the public
> * values and cookie. In case of an extension
> * field, the cookie used for authentication
> * purposes is zero. Note the hash is saved for
> * use later in the autokey mambo.
> */
> if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
> session_key(&rbufp->recv_srcadr,
> dstadr_sin, skeyid, 0, 2);
381,384c503,505
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->bcast.sin_addr.s_addr),
< skeyid, (u_long)(4 * (1 << pkt->ppoll)));
< } else if (hismode != MODE_SERVER) {
---
> &rbufp->recv_srcadr, dstadr_sin,
> skeyid, pkeyid, 0);
> } else {
386,388c507,508
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->sin.sin_addr.s_addr),
< skeyid, (u_long)(4 * (1 << pkt->ppoll)));
---
> &rbufp->recv_srcadr, dstadr_sin,
> skeyid, pkeyid, 2);
392c512
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
396c516,518
< * succceed in bloating the key cache.
---
> * succeed in bloating the key cache. If an autokey,
> * purge it immediately, since we won't be needing it
> * again.
402a525,528
> #ifdef AUTOKEY
> if (skeyid > NTP_MAXKEY)
> authtrust(skeyid, 0);
> #endif /* AUTOKEY */
406,408c532,536
< "receive: at %ld %s mode %d keyid %08lx mac %d auth %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< hismode, skeyid, has_mac, is_authentic);
---
> "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
> current_time, ntoa(dstadr_sin),
> ntoa(&rbufp->recv_srcadr), hismode, retcode,
> skeyid, authlen, has_mac,
> is_authentic);
413,414c541,548
< * Find the peer. This will return a null if this guy isn't in
< * the database.
---
> * The association matching rules are implemented by a set of
> * routines and a table in ntp_peer.c. A packet matching an
> * association is processed by that association. If not and
> * certain conditions prevail, then an ephemeral association is
> * mobilized: a broadcast packet mobilizes a broadcast client
> * aassociation; a server packet mobilizes a client association;
> * a symmetric active packet mobilizes a symmetric passive
> * association. And, the adventure continues...
416,428d549
< peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
< hismode, &retcode);
< /*
< * The new association matching rules are driven by a table
< * specified in ntp.h. We have replaced the *default* behaviour
< * of replying to bogus packets in server mode in this version.
< * A packet must now match an association in order to be
< * processed. In the event that no association exists, then an
< * association is mobilized if need be. Two different
< * associations can be mobilized a) passive associations b)
< * client associations due to broadcasts or manycasts.
< */
< is_error = 0;
433,439c554,558
< * If the client is configured purely as a broadcast
< * client and not as an manycast server, it has no
< * business being a server. Simply go home. Otherwise,
< * send a MODE_SERVER response and go home. Note that we
< * don't do a authentication check here, since we can't
< * set the system clock; but, we do set the key ID to
< * zero to tell the caller about this.
---
> * This is a client mode packet not matching a known
> * association. If from a manycast client we run a few
> * sanity checks before deciding to send a unicast
> * server response. Otherwise, it must be a client
> * request, so send a server response and go home.
441,445c560,578
< if (!sys_bclient || sys_manycastserver) {
< if (is_authentic)
< fast_xmit(rbufp, MODE_SERVER, skeyid);
< else
< fast_xmit(rbufp, MODE_SERVER, 0);
---
> if (sys_manycastserver && (rbufp->dstadr->flags &
> INT_MULTICAST)) {
>
> /*
> * We are picky about responding to a
> * manycaster. There is no reason to respond to
> * a request if our time is worse than the
> * manycaster. We certainly don't reply if not
> * synchronized to proventic time.
> */
> if (sys_peer == NULL)
> return;
>
> /*
> * We don't reply if the our stratum is greater
> * than the manycaster.
> */
> if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
> return;
449,450c582,584
< * We can't get here if an association is mobilized, so
< * just toss the key, if appropriate.
---
> * Note that we don't require an authentication check
> * here, since we can't set the system clock; but, we do
> * set the key ID to zero to tell the caller about this.
452,454c586,591
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< return;
---
> if (is_authentic)
> fast_xmit(rbufp, MODE_SERVER, skeyid,
> restrict_mask);
> else
> fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
> return;
459,465c596,611
< * This could be in response to a multicast packet sent
< * by the "manycast" mode association. Find peer based
< * on the originate timestamp in the packet. Note that
< * we don't mobilize a new association, unless the
< * packet is properly authenticated. The response must
< * be properly authenticated and it's darn funny of the
< * manycaster isn't around now.
---
> * This is a server mode packet returned in response to
> * a client mode packet sent to a multicast group
> * address. The originate timestamp is a good nonce to
> * reliably associate the reply with what was sent. If
> * there is no match, that's curious and could be an
> * intruder attempting to clog, so we just ignore it.
> *
> * First, make sure the packet is authentic. If so and
> * the manycast association is found, we mobilize a
> * client mode association, copy pertinent variables
> * from the manycast to the client mode association and
> * wind up the spring.
> *
> * There is an implosion hazard at the manycast client,
> * since the manycast servers send the server packet
> * immediately.
467,475c613,616
< if ((sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
< }
< peer2 = (struct peer *)findmanycastpeer(&pkt->org);
< if (peer2 == 0) {
< is_error = 1;
< break;
< }
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic))
> return;
477,482c618,621
< /*
< * Create a new association and copy the peer variables
< * to it. If something goes wrong, carefully pry the new
< * association away and return its marbles to the candy
< * store.
< */
---
> peer2 = findmanycastpeer(rbufp);
> if (peer2 == 0)
> return;
>
485,490c624,628
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
< if (peer == 0) {
< is_error = 1;
< break;
< }
< peer_config_manycast(peer2, peer);
---
> sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
> (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
> MDF_UCAST, 0, skeyid);
> if (peer == NULL)
> return;
493,501d630
< case AM_ERR:
<
< /*
< * Something bad happened. Dirty floor will be mopped by
< * the code at the end of this adventure.
< */
< is_error = 1;
< break;
<
505,507c634,637
< * Okay, we're going to keep him around. Allocate him
< * some memory. But, don't do that unless the packet is
< * properly authenticated.
---
> * This is the first packet received from a symmetric
> * active peer. First, make sure the packet is
> * authentic. If so, mobilize a symmetric passive
> * association.
509,511c639,644
< if ((sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic)) {
> fast_xmit(rbufp, MODE_PASSIVE, 0,
> restrict_mask);
> return;
515c648,651
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
---
> sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
> FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
> if (peer == NULL)
> return;
521,522c657,661
< * Broadcast client being set up now. Do this only if
< * the packet is properly authenticated.
---
> * This is the first packet received from a broadcast
> * server. First, make sure the packet is authentic, not
> * restricted and that we are a broadcast or multicast
> * client. If so, mobilize a broadcast client
> * association.
524,528c663,667
< if ((restrict_mask & RES_NOPEER) || !sys_bclient ||
< (sys_authenticate && !is_authentic)) {
< is_error = 1;
< break;
< }
---
> if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
> RES_NOPEER)) || (sys_authenticate &&
> !is_authentic) || !sys_bclient)
> return;
>
530,536c669,681
< MODE_MCLIENT, PKT_VERSION(pkt->li_vn_mode),
< NTP_MINDPOLL, NTP_MAXDPOLL, 0, skeyid);
< if (peer == 0)
< break;
< peer->flags |= FLAG_MCAST1 | FLAG_MCAST2 | FLAG_BURST;
< peer->hmode = MODE_CLIENT;
< break;
---
> MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
> sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
> FLAG_IBURST | (sys_authenticate ?
> FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
> #ifdef AUTOKEY
> #ifdef PUBKEY
> if (peer == NULL)
> return;
> if (peer->flags & FLAG_SKEY)
> crypto_recv(peer, rbufp);
> #endif /* PUBKEY */
> #endif /* AUTOKEY */
> return;
542c687
< * It seems like it is okay to process the packet now
---
> * Happiness and nothing broke. Earn some revenue.
549c694,695
< * shouldn't be getting here, but simply return anyway!
---
> * Invalid mode combination. Leave the island
> * immediately.
551,566d696
< is_error = 1;
< }
< if (is_error) {
<
< /*
< * Error stub. If we get here, something broke. We
< * scuttle the autokey if necessary and sink the ship.
< * This can occur only upon mobilization, so we can
< * throw the structure away without fear of breaking
< * anything.
< */
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< if (peer != 0)
< if (!(peer->flags & FLAG_CONFIG))
< unpeer(peer);
569,570c699
< printf("match error code %d assoc %d\n",
< retcode, peer_associations);
---
> printf("receive: bad protocol %d\n", retcode);
576,577c705,710
< * If the peer isn't configured, set his keyid and authenable
< * status based on the packet.
---
> * If the peer isn't configured, set his authenable and autokey
> * status based on the packet. Once the status is set, it can't
> * be unset. It seems like a silly idea to do this here, rather
> * in the configuration routine, but in some goofy cases the
> * first packet sent cannot be authenticated and we need a way
> * for the dude to change his mind.
580a714
> peer->received++;
583,588c717,720
< if (skeyid > NTP_MAXKEY) {
< if (peer->flags & FLAG_MCAST2)
< peer->keyid = skeyid;
< else
< peer->flags |= FLAG_SKEY;
< }
---
> #ifdef AUTOKEY
> if (skeyid > NTP_MAXKEY)
> peer->flags |= FLAG_SKEY;
> #endif /* AUTOKEY */
592,595c724,730
< * Determine if this guy is basically trustable. If not, flush
< * the bugger. If this is the first packet that is
< * authenticated, flush the clock filter. This is to foil
< * clogging attacks that might starve the poor dear.
---
> * A valid packet must be from an authentic and allowed source.
> * All packets must pass the authentication allowed tests.
> * Autokey authenticated packets must pass additional tests and
> * public-key authenticated packets must have the credentials
> * verified. If all tests are passed, the packet is forwarded
> * for processing. If not, the packet is discarded and the
> * association demobilized if appropriate.
598c733
< if (is_authentic)
---
> if (is_authentic) {
600c735
< else
---
> } else {
602,604c737,740
< if (peer->hmode == MODE_BROADCAST && (restrict_mask &
< RES_DONTTRUST))
< peer->flash |= TEST10; /* access denied */
---
> }
> if (peer->hmode == MODE_BROADCAST &&
> (restrict_mask & RES_DONTTRUST)) /* test 4 */
> peer->flash |= TEST4; /* access denied */
606c742
< if (!(peer->flags & FLAG_AUTHENTIC))
---
> if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
608,611c744
< else if (skeyid == 0)
< peer->flash |= TEST9; /* peer not auth */
< else if (!(oflags & FLAG_AUTHENABLE)) {
< peer_clear(peer);
---
> else if (!(oflags & FLAG_AUTHENABLE))
613d745
< }
615,626c747
< if ((peer->flash & ~(u_int)TEST9) != 0) {
<
< /*
< * The packet is bogus, so we throw it away before
< * becoming a denial-of-service hazard. We don't throw
< * the current association away if it is configured or
< * if it has prior reachable friends.
< */
< if (!is_mystic && skeyid > NTP_MAXKEY)
< authtrust(skeyid, 0);
< if (!(peer->flags & FLAG_CONFIG) && peer->reach == 0)
< unpeer(peer);
---
> if (peer->flash) {
629,631c750
< printf(
< "invalid packet 0x%02x code %d assoc %d\n",
< peer->flash, retcode, peer_associations);
---
> printf("receive: bad auth %03x\n", peer->flash);
636c755
< #ifdef MD5
---
> #ifdef AUTOKEY
638,640c757,770
< * The autokey dance. The cha-cha requires that the hash of the
< * current session key matches the previous key identifier.
< * Heaps of trouble if the steps falter.
---
> * More autokey dance. The rules of the cha-cha are as follows:
> *
> * 1. If there is no key or the key is not auto, do nothing.
> *
> * 2. If an extension field contains a verified signature, it is
> * self-authenticated and we sit the dance.
> *
> * 3. If this is a server reply, check only to see that the
> * transmitted key ID matches the received key ID.
> *
> * 4. Check to see that one or more hashes of the current key ID
> * matches the previous key ID or ultimate original key ID
> * obtained from the broadcaster or symmetric peer. If no
> * match, sit the dance and wait for timeout.
642,649c772,775
< if (skeyid > NTP_MAXKEY) {
< int i;
<
< /*
< * In the case of a new autokey, verify the hash matches
< * one of the previous four hashes. If not, raise the
< * authentication flasher and hope the next one works.
< */
---
> if (peer->flags & FLAG_SKEY) {
> peer->flash |= TEST10;
> crypto_recv(peer, rbufp);
> poll_update(peer, peer->hpoll);
651,661c777,780
< peer->pkeyid = peer->keyid;
< } else if (peer->flags & FLAG_MCAST2) {
< if (peer->pkeyid > NTP_MAXKEY)
< authtrust(peer->pkeyid, 0);
< for (i = 0; i < 4 && tkeyid != peer->pkeyid;
< i++) {
< tkeyid = session_key(
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->bcast.sin_addr.s_addr),
< tkeyid, 0);
< }
---
> if (skeyid == peer->keyid)
> peer->flash &= ~TEST10;
> } else if (!peer->flash & TEST10) {
> peer->pkeyid = skeyid;
663,666c782,792
< if (peer->pkeyid > NTP_MAXKEY)
< authtrust(peer->pkeyid, 0);
< for (i = 0; i < 4 && tkeyid != peer->pkeyid;
< i++) {
---
> int i;
>
> for (i = 0; ; i++) {
> if (tkeyid == peer->pkeyid ||
> tkeyid == peer->recauto.key) {
> peer->flash &= ~TEST10;
> peer->pkeyid = skeyid;
> break;
> }
> if (i > peer->recauto.seq)
> break;
668,670c794,795
< ntohl((&rbufp->recv_srcadr)->sin_addr.s_addr),
< ntohl(rbufp->dstadr->sin.sin_addr.s_addr),
< tkeyid, 0);
---
> &rbufp->recv_srcadr, dstadr_sin,
> tkeyid, pkeyid, 0);
673,675c798,814
< #ifdef XXX /* temp until certificate code is mplemented */
< if (tkeyid != peer->pkeyid)
< peer->flash |= TEST9; /* peer not authentic */
---
> #ifdef PUBKEY
>
> /*
> * This is delicious. Ordinarily, we kick out all errors
> * at this point; however, in symmetric mode and just
> * warming up, an unsynchronized peer must inject the
> * timestamps, even if it fails further up the road. So,
> * let the dude by here, but only if the jerk is not yet
> * reachable. After that, he's on his own.
> */
> if (!(peer->flags & FLAG_PROVEN))
> peer->flash |= TEST11;
> if (peer->flash && peer->reach) {
> #ifdef DEBUG
> if (debug)
> printf("packet: bad autokey %03x\n",
> peer->flash);
677c816,818
< peer->pkeyid = skeyid;
---
> return;
> }
> #endif /* PUBKEY */
679c820
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
682,685c823,826
< * Gawdz, it's come to this. Process the dang packet. If
< * something breaks and the association doesn't deserve to live,
< * toss it. Be careful in active mode and return a packet
< * anyway.
---
> * We have survived the gaunt. Forward to the packet routine. If
> * a symmetric passive association has been mobilized and the
> * association doesn't deserve to live, it will die in the
> * transmit routine if not reachable after timeout.
687,696c828
< process_packet(peer, pkt, &(rbufp->recv_time));
< if (!(peer->flags & FLAG_CONFIG) && peer->reach == 0) {
< if (peer->hmode == MODE_PASSIVE) {
< if (is_authentic)
< fast_xmit(rbufp, MODE_PASSIVE, skeyid);
< else
< fast_xmit(rbufp, MODE_PASSIVE, 0);
< }
< unpeer(peer);
< }
---
> process_packet(peer, pkt, &rbufp->recv_time);
706c838
< int
---
> void
718c850
< int pmode;
---
> int pmode, pleap, pstratum;
721c853,856
< * Swap header fields and keep the books.
---
> * Swap header fields and keep the books. The books amount to
> * the receive timestamp and poll interval in the header. We
> * need these even if there are other problems in order to crank
> * up the state machine.
734,736d868
< peer->rec = *recv_ts;
< peer->ppoll = pkt->ppoll;
< pmode = PKT_MODE(pkt->li_vn_mode);
739c871
< * Test for old or duplicate packets (tests 1 through 3).
---
> * Test for old, duplicate or unsynch packets (tests 1-3).
740a873,876
> peer->rec = *recv_ts;
> pmode = PKT_MODE(pkt->li_vn_mode);
> pleap = PKT_LEAP(pkt->li_vn_mode);
> pstratum = PKT_TO_STRATUM(pkt->stratum);
743,754c879,885
< if (L_ISEQU(&peer->org, &p_xmt)) /* test 1 */
< peer->flash |= TEST1; /* duplicate packet */
< if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST) {
< if (!L_ISEQU(&peer->xmt, &p_org)) { /* test 2 */
< peer->bogusorg++;
< peer->flash |= TEST2; /* bogus packet */
< }
< if (L_ISZERO(&p_rec) || L_ISZERO(&p_org))
< peer->flash |= TEST3; /* unsynchronized */
< } else {
< if (L_ISZERO(&p_org))
< peer->flash |= TEST3; /* unsynchronized */
---
> if (L_ISEQU(&peer->org, &p_xmt)) /* 1 */
> peer->flash |= TEST1; /* dupe */
> if (pmode != MODE_BROADCAST) {
> if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
> peer->flash |= TEST2; /* bogus */
> if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
> peer->flash |= TEST3; /* unsynch */
755a887,888
> if (L_ISZERO(&p_xmt)) /* 3 */
> peer->flash |= TEST3; /* unsynch */
759c892,894
< * Test for valid header (tests 5 through 10)
---
> * If tests 1-3 fail, the packet is discarded leaving only the
> * receive and origin timestamps and poll interval, which is
> * enough to get the protocol started.
760a896,932
> if (peer->flash) {
> #ifdef DEBUG
> if (debug)
> printf("packet: bad data %03x\n",
> peer->flash);
> #endif
> return;
> }
>
> /*
> * A kiss-of-death (kod) packet is returned by a server in case
> * the client is denied access. It consists of the client
> * request packet with the leap bits indicating never
> * synchronized, stratum zero and reference ID field the ASCII
> * string "DENY". If the packet originate timestamp matches the
> * association transmit timestamp the kod is legitimate. If the
> * peer leap bits indicate never synchronized, this must be
> * access deny and the association is disabled; otherwise this
> * must be a limit reject. In either case a naughty message is
> * forced to the system log.
> */
> if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
> memcmp(&pkt->refid, "DENY", 4) == 0) {
> if (peer->leap == LEAP_NOTINSYNC) {
> peer->stratum = STRATUM_UNSPEC;
> peer->flash |= TEST4;
> memcpy(&peer->refid, &pkt->refid, 4);
> msyslog(LOG_INFO, "access denied");
> } else {
> msyslog(LOG_INFO, "limit reject");
> }
> return;
> }
>
> /*
> * Test for valid peer data (tests 6-8)
> */
764,770c936,941
< if (PKT_LEAP(pkt->li_vn_mode) == LEAP_NOTINSYNC || /* test 6 */
< PKT_TO_STRATUM(pkt->stratum) >= NTP_MAXSTRATUM ||
< dtemp < 0)
< peer->flash |= TEST6; /* peer clock unsynchronized */
< if (!(peer->flags & FLAG_CONFIG) && sys_peer != 0) { /* test 7 */
< if (PKT_TO_STRATUM(pkt->stratum) > sys_stratum) {
< peer->flash |= TEST7; /* peer stratum too high */
---
> if (pleap == LEAP_NOTINSYNC || /* 6 */
> pstratum >= STRATUM_UNSPEC || dtemp < 0)
> peer->flash |= TEST6; /* bad synch */
> if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
> if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
> peer->flash |= TEST7; /* bad stratum */
774,783c945,948
< if (fabs(p_del) >= MAXDISPERSE /* test 8 */
< || p_disp >= MAXDISPERSE)
< peer->flash |= TEST8; /* delay/dispersion too high */
<
< /*
< * If the packet header is invalid (tests 5 through 10), exit.
< * XXX we let TEST9 sneak by until the certificate code is
< * implemented, but only to mobilize the association.
< */
< if (peer->flash & (TEST5 | TEST6 | TEST7 | TEST8 | TEST10)) {
---
> if (p_del < 0 || p_disp < 0 || p_del / /* 8 */
> 2 + p_disp >= MAXDISPERSE)
> peer->flash |= TEST8; /* bad peer distance */
> if (peer->flash) {
786,788c951,952
< printf(
< "invalid packet header 0x%02x mode %d\n",
< peer->flash, pmode);
---
> printf("packet: bad header %03x\n",
> peer->flash);
790c954
< return (0);
---
> return;
794c958,959
< * Valid header; update our state.
---
> * The header is valid. Capture the remaining header values and
> * mark as reachable.
796,801c961,966
< record_raw_stats(&peer->srcadr, &peer->dstadr->sin,
< &p_org, &p_rec, &p_xmt, &peer->rec);
<
< peer->leap = PKT_LEAP(pkt->li_vn_mode);
< peer->pmode = pmode; /* unspec */
< peer->stratum = PKT_TO_STRATUM(pkt->stratum);
---
> record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
> &p_rec, &p_xmt, &peer->rec);
> peer->leap = pleap;
> peer->pmode = pmode;
> peer->stratum = pstratum;
> peer->ppoll = pkt->ppoll;
807c972
< if (peer->reach == 0) {
---
> if (!(peer->reach)) {
811a977
> peer->unreach = 0;
832c998
< p_disp = CLOCK_PHI * (peer->rec.l_ui - p_org.l_ui);
---
> p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
837,850c1003,1007
< * measure that directly; therefore, we start up in
< * client/server mode, calculate the clock offset, using the
< * engineered refinement algorithms, while also receiving
< * broadcasts. When a broadcast is received in client/server
< * mode, we calculate a correction factor to use after switching
< * back to broadcast mode. We know NTP_SKEWFACTOR == 16, which
< * accounts for the simplified ei calculation.
< *
< * If FLAG_MCAST2 is set, we are a broadcast/multicast client.
< * If FLAG_MCAST1 is set, we haven't calculated the propagation
< * delay. If hmode is MODE_CLIENT, we haven't set the local
< * clock in client/server mode. Initially, we come up
< * MODE_CLIENT. When the clock is first updated and FLAG_MCAST2
< * is set, we switch from MODE_CLIENT to MODE_BCLIENT.
---
> * measure that directly. Therefore, we start up in MODE_CLIENT
> * mode, set FLAG_MCAST and exchange eight messages to determine
> * the clock offset. When the last message is sent, we switch to
> * MODE_BCLIENT mode. The next broadcast message after that
> * computes the broadcast offset and clears FLAG_MCAST.
853,855c1010
< if (peer->flags & FLAG_MCAST1) {
< if (peer->hmode == MODE_BCLIENT)
< peer->flags &= ~FLAG_MCAST1;
---
> if (peer->flags & FLAG_MCAST) {
858c1013,1014
< return (1);
---
> if (peer->hmode == MODE_CLIENT)
> return;
859a1016
> peer->flags &= ~FLAG_MCAST;
869a1027
> p_del = max(p_del, LOGTOD(sys_precision));
871,872c1029,1031
< if (fabs(p_del) >= MAXDISPERSE || p_disp >= MAXDISPERSE) /* test 4 */
< peer->flash |= TEST4; /* delay/dispersion too big */
---
> if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
> p_disp >= MAXDISPERSE) /* 9 */
> peer->flash |= TEST9; /* bad peer distance */
875c1034,1035
< * If the packet data are invalid (tests 1 through 4), exit.
---
> * If any flasher bits remain set at this point, abandon ship.
> * Otherwise, forward to the clock filter.
880,881c1040,1041
< printf("invalid packet data 0x%02x mode %d\n",
< peer->flash, pmode);
---
> printf("packet: bad packet data %03x\n",
> peer->flash);
883c1043
< return(1);
---
> return;
885,890c1045
<
<
< /*
< * This one is valid. Mark it so, give it to clock_filter().
< */
< clock_filter(peer, p_offset, p_del, fabs(p_disp));
---
> clock_filter(peer, p_offset, p_del, p_disp);
894,895c1049
< SQRT(peer->variance));
< return(1);
---
> SQRT(peer->jitter));
907,908d1060
< int i;
< struct peer *peer;
915c1067
< if (sys_peer == 0)
---
> if (sys_peer == NULL)
927c1079
< switch (local_clock(sys_peer, sys_offset, sys_epsil)) {
---
> switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
929,932c1081,1084
< case -1:
< /*
< * Clock is too screwed up. Just exit for now.
< */
---
> /*
> * Clock is too screwed up. Just exit for now.
> */
> case -1:
937,949c1089,1094
< case 1:
< /*
< * Clock was stepped. Clear filter registers
< * of all peers.
< */
< for (i = 0; i < HASH_SIZE; i++) {
< for (peer = peer_hash[i]; peer != 0;
< peer =peer->next)
< peer_clear(peer);
< }
< NLOG(NLOG_SYNCSTATUS)
< msyslog(LOG_INFO, "synchronisation lost");
< sys_peer = 0;
---
> /*
> * Clock was stepped. Flush all time values of all peers.
> */
> case 1:
> clear_all();
> sys_peer = NULL;
950a1096,1098
> sys_poll = NTP_MINPOLL;
> NLOG(NLOG_SYNCSTATUS)
> msyslog(LOG_INFO, "synchronisation lost");
954,960c1102,1108
< default:
< /*
< * Update the system stratum, leap bits, root delay,
< * root dispersion, reference ID and reference time. We
< * also update select dispersion and max frequency
< * error.
< */
---
> /*
> * Update the system stratum, leap bits, root delay, root
> * dispersion, reference ID and reference time. We also update
> * select dispersion and max frequency error. If the leap
> * changes, we gotta reroll the keys.
> */
> default:
967,968c1115
< sys_rootdelay = sys_peer->rootdelay +
< fabs(sys_peer->delay);
---
> sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
971c1118
< if (oleap != sys_leap)
---
> if (oleap == LEAP_NOTINSYNC) {
972a1120,1123
> #ifdef AUTOKEY
> expire_all();
> #endif /* AUTOKEY */
> }
979,980c1130
< * poll_update - update peer poll interval. See Section 3.4.9 of the
< * spec.
---
> * poll_update - update peer poll interval
988c1138,1140
< long update;
---
> #ifdef AUTOKEY
> int oldpoll;
> #endif /* AUTOKEY */
991,995c1143,1148
< * The wiggle-the-poll-interval dance. Broadcasters dance only
< * the minpoll beat. Reference clock partners sit this one out.
< * Dancers surviving the clustering algorithm beat to the system
< * clock. Broadcast clients are usually lead by their broadcast
< * partner, but faster in the initial mating dance.
---
> * A little foxtrot to determine what controls the poll
> * interval. If the peer is reachable, but the last four polls
> * have not been answered, use the minimum. If declared
> * truechimer, use the system poll interval. This allows each
> * association to ramp up the poll interval for useless sources
> * and to clamp it to the minimum when first starting up.
997c1150,1155
< if (peer->hmode == MODE_BROADCAST) {
---
> #ifdef AUTOKEY
> oldpoll = peer->kpoll;
> #endif /* AUTOKEY */
> if (hpoll > peer->maxpoll)
> peer->hpoll = peer->maxpoll;
> else if (hpoll < peer->minpoll)
999,1008c1157,1174
< } else if (peer->flags & FLAG_SYSPEER) {
< peer->hpoll = sys_poll;
< } else {
< if (hpoll > peer->maxpoll)
< peer->hpoll = peer->maxpoll;
< else if (hpoll < peer->minpoll)
< peer->hpoll = peer->minpoll;
< else
< peer->hpoll = hpoll;
< }
---
> else
> peer->hpoll = hpoll;
>
> /*
> * Bit of adventure here. If during a burst and not timeout,
> * just slink away. If timeout, figure what the next timeout
> * should be. If IBURST or a reference clock, use one second. If
> * not and the dude was reachable during the previous poll
> * interval, randomize over 1-4 seconds; otherwise, randomize
> * over 15-18 seconds. This is to give time for a modem to
> * complete the call, for example. If not during a burst,
> * randomize over the poll interval -1 to +2 seconds.
> *
> * In case of manycast server, make the poll interval, which is
> * axtually the manycast beacon interval, eight times the system
> * poll interval. Normally when the host poll interval settles
> * up to 17.1 s, the beacon interval settles up to 2.3 hours.
> */
1012c1178,1179
< if (peer->flags & FLAG_REFCLOCK)
---
> #ifdef REFCLOCK
> else if (peer->flags & FLAG_REFCLOCK)
1013a1181
> #endif
1017a1186,1191
> } else if (peer->cast_flags & MDF_ACAST) {
> if (sys_survivors < NTP_MINCLOCK)
> peer->kpoll = peer->hpoll;
> else
> peer->kpoll = peer->hpoll + 3;
> peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1019c1193
< update = max(min(peer->ppoll, peer->hpoll),
---
> peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1021c1195
< peer->nextdate = peer->outdate + RANDPOLL(update);
---
> peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1022a1197,1208
> if (peer->nextdate < current_time)
> peer->nextdate = current_time;
> #ifdef AUTOKEY
> /*
> * Bit of crass arrogance at this point. If the poll interval
> * has changed and we have a keylist, the lifetimes in the
> * keylist are probably bogus. In this case purge the keylist
> * and regenerate it later.
> */
> if (peer->kpoll != oldpoll)
> key_expire(peer);
> #endif /* AUTOKEY */
1025,1027c1211,1214
< printf("poll_update: at %lu %s poll %d burst %d last %lu next %lu\n",
< current_time, ntoa(&peer->srcadr), hpoll,
< peer->burst, peer->outdate, peer->nextdate);
---
> printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
> current_time, ntoa(&peer->srcadr), peer->flags,
> peer->kpoll, peer->burst, peer->outdate,
> peer->nextdate);
1040a1228
> u_long u_rand;
1041a1230,1254
> /*
> * If cryptographic credentials have been acquired, toss them to
> * Valhalla. Note that autokeys are ephemeral, in that they are
> * tossed immediately upon use. Therefore, the keylist can be
> * purged anytime without needing to preserve random keys. Note
> * that, if the peer is purged, the cryptographic variables are
> * purged, too. This makes it much harder to sneak in some
> * unauthenticated data in the clock filter.
> */
> #ifdef DEBUG
> if (debug)
> printf("peer_clear: at %ld assoc ID %d\n", current_time,
> peer->associd);
> #endif
> #ifdef AUTOKEY
> key_expire(peer);
> #ifdef PUBKEY
> if (peer->keystr != NULL)
> free(peer->keystr);
> if (peer->pubkey.ptr != NULL)
> free(peer->pubkey.ptr);
> if (peer->certif.ptr != NULL)
> free(peer->certif.ptr);
> #endif /* PUBKEY */
> #endif /* AUTOKEY */
1042a1256,1268
>
> /*
> * If he dies as a broadcast client, he comes back to life as
> * a broadcast client in client mode in order to recover the
> * initial autokey values. Note that there is no need to call
> * clock_select(), since the perp has already been voted off
> * the island at this point.
> */
> if (peer->cast_flags & MDF_BCLNT) {
> peer->flags |= FLAG_MCAST;
> peer->hmode = MODE_CLIENT;
> }
> peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1044c1270,1271
< peer->hpoll = peer->minpoll;
---
> peer->hpoll = peer->kpoll = peer->minpoll;
> peer->ppoll = peer->maxpoll;
1046c1273
< peer->variance = MAXDISPERSE;
---
> peer->jitter = MAXDISPERSE;
1047a1275,1280
> #ifdef REFCLOCK
> if (!(peer->flags & FLAG_REFCLOCK)) {
> peer->leap = LEAP_NOTINSYNC;
> peer->stratum = STRATUM_UNSPEC;
> }
> #endif
1053d1285
< poll_update(peer, peer->minpoll);
1056,1059c1288
< * Since we have a chance to correct possible funniness in
< * our selection of interfaces on a multihomed host, do so
< * by setting us to no particular interface.
< * WARNING: do so only in non-broadcast mode!
---
> * Randomize the first poll over 1-16s to avoid bunching.
1061,1062c1290,1293
< if (peer->hmode != MODE_BROADCAST)
< peer->dstadr = any_interface;
---
> peer->update = peer->outdate = current_time;
> u_rand = RANDOM;
> peer->nextdate = current_time + (u_rand & ((1 <<
> BURST_INTERVAL1) - 1)) + 1;
1072,1075c1303,1306
< register struct peer *peer,
< double sample_offset,
< double sample_delay,
< double sample_disp
---
> register struct peer *peer, /* peer structure pointer */
> double sample_offset, /* clock offset */
> double sample_delay, /* roundtrip delay */
> double sample_disp /* dispersion */
1078,1081c1309,1312
< register int i, j, k, n = 0;
< register u_char *ord;
< double distance[NTP_SHIFT];
< double x, y, z, off;
---
> double dst[NTP_SHIFT]; /* distance vector */
> int ord[NTP_SHIFT]; /* index vector */
> register int i, j, k, m;
> double dsp, jit, dtemp, etemp;
1084,1085c1315,1321
< * Update error bounds and calculate distances. Also initialize
< * sort index vector.
---
> * Shift the new sample into the register and discard the oldest
> * one. The new offset and delay come directly from the
> * timestamp calculations. The dispersion grows from the last
> * outbound packet or reference clock update to the present time
> * and increased by the sum of the peer precision and the system
> * precision. The delay can sometimes swing negative due to
> * frequency skew, so it is clamped non-negative.
1087,1089c1323,1324
< x = CLOCK_PHI * (current_time - peer->update);
< peer->update = current_time;
< ord = peer->filter_order;
---
> dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
> sample_disp, MAXDISPERSE);
1091,1100c1326,1331
< for (i = 0; i < NTP_SHIFT; i++) {
< peer->filter_disp[j] += x;
< if (peer->filter_disp[j] > MAXDISPERSE)
< peer->filter_disp[j] = MAXDISPERSE;
< distance[i] = fabs(peer->filter_delay[j]) / 2 +
< peer->filter_disp[j];
< ord[i] = j;
< if (--j < 0)
< j += NTP_SHIFT;
< }
---
> peer->filter_offset[j] = sample_offset;
> peer->filter_delay[j] = max(0, sample_delay);
> peer->filter_disp[j] = dsp;
> peer->filter_epoch[j] = current_time;
> j++; j %=NTP_SHIFT;
> peer->filter_nextpt = j;
1103c1334,1338
< * Insert the new sample at the beginning of the register.
---
> * Update dispersions since the last update and at the same
> * time initialize the distance and index lists. The distance
> * list uses a compound metric. If the sample is valid and
> * younger than the minimum Allan intercept, use delay;
> * otherwise, use biased dispersion.
1105,1114c1340,1357
< peer->filter_offset[peer->filter_nextpt] = sample_offset;
< peer->filter_delay[peer->filter_nextpt] = sample_delay;
< x = LOGTOD(peer->precision) + LOGTOD(sys_precision) +
< sample_disp;
< peer->filter_disp[peer->filter_nextpt] = min(x, MAXDISPERSE);
< peer->filter_epoch[peer->filter_nextpt] = current_time;
< distance[0] = min(x + fabs(sample_delay) / 2, MAXDISTANCE);
< peer->filter_nextpt++;
< if (peer->filter_nextpt >= NTP_SHIFT)
< peer->filter_nextpt = 0;
---
> dtemp = clock_phi * (current_time - peer->update);
> peer->update = current_time;
> for (i = NTP_SHIFT - 1; i >= 0; i--) {
> if (i != 0) {
> peer->filter_disp[j] += dtemp;
> if (peer->filter_disp[j] > MAXDISPERSE)
> peer->filter_disp[j] = MAXDISPERSE;
> }
> if (peer->filter_disp[j] >= MAXDISPERSE)
> dst[i] = MAXDISPERSE;
> else if (peer->update - peer->filter_epoch[j] >
> allan_xpt)
> dst[i] = MAXDISTANCE + peer->filter_disp[j];
> else
> dst[i] = peer->filter_delay[j];
> ord[i] = j;
> j++; j %= NTP_SHIFT;
> }
1116,1119c1359,1360
< /*
< * Sort the samples in the register by distance. The winning
< * sample will be in ord[0]. Sort the samples only if they
< * are younger than the Allen intercept.
---
> /*
> * Sort the samples in both lists by distance.
1121,1126c1362,1364
< y = min(allan_xpt, NTP_SHIFT * ULOGTOD(sys_poll));
< for (n = 0; n < NTP_SHIFT && current_time -
< peer->filter_epoch[ord[n]] <= y; n++) {
< for (j = 0; j < n; j++) {
< if (distance[j] > distance[n]) {
< x = distance[j];
---
> for (i = 1; i < NTP_SHIFT; i++) {
> for (j = 0; j < i; j++) {
> if (dst[j] > dst[i]) {
1128,1131c1366,1370
< distance[j] = distance[n];
< ord[j] = ord[n];
< distance[n] = x;
< ord[n] = k;
---
> ord[j] = ord[i];
> ord[i] = k;
> etemp = dst[j];
> dst[j] = dst[i];
> dst[i] = etemp;
1134c1373,1388
< }
---
> }
>
> /*
> * Copy the index list to the association structure so ntpq
> * can see it later. Prune the distance list to samples less
> * than MAXDISTANCE, but keep at least two valid samples for
> * jitter calculation.
> */
> m = 0;
> for (i = 0; i < NTP_SHIFT; i++) {
> peer->filter_order[i] = ord[i];
> if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
> MAXDISTANCE))
> continue;
> m++;
> }
1137c1391,1397
< * Compute the error bound and standard error.
---
> * Compute the dispersion and jitter squares. The dispersion
> * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
> * normalized close to 1.0. The jitter is the mean of the square
> * differences relative to the lowest delay sample. If no
> * acceptable samples remain in the shift register, quietly
> * tiptoe home leaving only the
> * dispersion.
1139c1399,1401
< x = y = z = off = 0.;
---
> jit = 0;
> peer->disp = 0;
> k = ord[0];
1141,1148c1403,1409
< x = NTP_FWEIGHT * (x + peer->filter_disp[ord[i]]);
< if (i < n) {
< z += 1. / distance[i];
< off += peer->filter_offset[ord[i]] /
< distance[i];
< y += DIFF(peer->filter_offset[ord[i]],
< peer->filter_offset[ord[0]]);
< }
---
>
> j = ord[i];
> peer->disp = NTP_FWEIGHT * (peer->disp +
> peer->filter_disp[j]);
> if (i < m)
> jit += DIFF(peer->filter_offset[j],
> peer->filter_offset[k]);
1150,1158d1410
< peer->delay = peer->filter_delay[ord[0]];
< peer->variance = min(y / n, MAXDISPERSE);
< peer->disp = min(x, MAXDISPERSE);
< peer->epoch = current_time;
< x = peer->offset;
< if (peer->flags & FLAG_BURST)
< peer->offset = off / z;
< else
< peer->offset = peer->filter_offset[ord[0]];
1160a1413,1427
> * If no acceptable samples remain in the shift register,
> * quietly tiptoe home leaving only the dispersion. Otherwise,
> * save the offset, delay and jitter average. Note the jitter
> * must not be less than the system precision.
> */
> if (m == 0)
> return;
> etemp = peer->offset;
> peer->offset = peer->filter_offset[k];
> peer->delay = peer->filter_delay[k];
> if (m > 1)
> jit /= m - 1;
> peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
>
> /*
1164c1431
< if (peer->filter_epoch[ord[0]] > peer->epoch) {
---
> if (peer->filter_epoch[k] <= peer->epoch) {
1168c1435
< peer->filter_epoch[ord[0]] - peer->epoch);
---
> peer->epoch - peer->filter_epoch[k]);
1174,1177c1441,1444
< * If the offset exceeds the dispersion by CLOCK_SGATE and the
< * interval since the last update is less than twice the system
< * poll interval, consider the update a popcorn spike and ignore
< * it.
---
> * If the difference between the last offset and the current one
> * exceeds the jitter by CLOCK_SGATE (4) and the interval since
> * the last update is less than twice the system poll interval,
> * consider the update a popcorn spike and ignore it.
1179,1181c1446,1448
< if (fabs(x - peer->offset) > CLOCK_SGATE &&
< peer->filter_epoch[ord[0]] - peer->epoch < (1 <<
< (sys_poll + 1))) {
---
> if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
> CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
> (1 << (sys_poll + 1))) {
1184c1451,1452
< printf("clock_filter: popcorn spike %.6f\n", x);
---
> printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
> m, peer->offset, SQRT(peer->jitter));
1188c1456,1461
< peer->epoch = peer->filter_epoch[ord[0]];
---
>
> /*
> * The mitigated sample statistics are saved for later
> * processing, but can be processed only once.
> */
> peer->epoch = peer->filter_epoch[k];
1193,1195c1466,1468
< "clock_filter: offset %.6f delay %.6f disp %.6f std %.6f, age %lu\n",
< peer->offset, peer->delay, peer->disp,
< SQRT(peer->variance), current_time - peer->epoch);
---
> "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
> m, peer->offset, peer->delay, peer->disp,
> SQRT(peer->jitter), peer->update - peer->epoch);
1207,1208c1480,1481
< int i;
< int nlist, nl3;
---
> int i, j, k, n;
> int nreach, nlist, nl3;
1210,1212c1483
< int j;
< int n;
< int allow, found, k;
---
> int allow, found, sw;
1216,1220c1487,1490
< struct peer *typeacts = 0;
< struct peer *typelocal = 0;
< struct peer *typepps = 0;
< struct peer *typeprefer = 0;
< struct peer *typesystem = 0;
---
> struct peer *typeacts = NULL;
> struct peer *typelocal = NULL;
> struct peer *typepps = NULL;
> struct peer *typesystem = NULL;
1224c1494
< static int *index = NULL;
---
> static int *indx = NULL;
1227c1497
< static u_int index_size = 0;
---
> static u_int indx_size = 0;
1231,1232c1501,1502
< * Initialize. If a prefer peer does not survive this thing,
< * the pps_update switch will remain zero.
---
> * Initialize and create endpoint, index and peer lists big
> * enough to handle all associations.
1234,1235c1504,1507
< pps_update = 0;
< nlist = 0;
---
> osys_peer = sys_peer;
> sys_peer = NULL;
> sys_prefer = NULL;
> nreach = nlist = 0;
1243c1515
< free(index);
---
> free(indx);
1248,1250c1520,1522
< endpoint_size += 5 * 3 * sizeof *endpoint;
< index_size += 5 * 3 * sizeof *index;
< peer_list_size += 5 * sizeof *peer_list;
---
> endpoint_size += 5 * 3 * sizeof(*endpoint);
> indx_size += 5 * 3 * sizeof(*indx);
> peer_list_size += 5 * sizeof(*peer_list);
1253c1525
< index = (int *)emalloc(index_size);
---
> indx = (int *)emalloc(indx_size);
1258,1261c1530,1537
< * This first chunk of code is supposed to go through all
< * peers we know about to find the peers which are most likely
< * to succeed. We run through the list doing the sanity checks
< * and trying to insert anyone who looks okay.
---
> * Initially, we populate the island with all the rifraff peers
> * that happen to be lying around. Those with seriously
> * defective clocks are immediately booted off the island. Then,
> * the falsetickers are culled and put to sea. The truechimers
> * remaining are subject to repeated rounds where the most
> * unpopular at each round is kicked off. When the population
> * has dwindled to NTP_MINCLOCK (3), the survivors split a
> * million bucks and collectively crank the chimes.
1265c1541,1542
< for (peer = peer_hash[n]; peer != 0; peer = peer->next) {
---
> for (peer = peer_hash[n]; peer != NULL; peer =
> peer->next) {
1268,1279d1544
< if (peer->flags & FLAG_NOSELECT)
< continue; /* noselect (survey) */
< if (peer->reach == 0)
< continue; /* unreachable */
< if (peer->stratum > 1 && peer->refid ==
< peer->dstadr->sin.sin_addr.s_addr)
< continue; /* sync loop */
< if (root_distance(peer) >= MAXDISTANCE + 2 *
< CLOCK_PHI * ULOGTOD(sys_poll)) {
< peer->seldisptoolarge++;
< continue; /* noisy or broken */
< }
1282c1547,1562
< * Don't allow the local-clock or acts drivers
---
> * A peer leaves the island immediately if
> * unreachable, synchronized to us or suffers
> * excessive root distance. Careful with the
> * root distance, since the poll interval can
> * increase to a day and a half.
> */
> if (!peer->reach || (peer->stratum > 1 &&
> peer->refid ==
> peer->dstadr->sin.sin_addr.s_addr) ||
> peer->stratum >= STRATUM_UNSPEC ||
> (root_distance(peer) >= MAXDISTANCE + 2 *
> clock_phi * ULOGTOD(sys_poll)))
> continue;
>
> /*
> * Don't allow the local clock or modem drivers
1285c1565,1566
< * nobody else is around.
---
> * nobody else is around. These guys are all
> * configured, so we never throw them away.
1304,1305c1585,1587
< * If we get this far, we assume the peer is
< * acceptable.
---
> * If we get this far, the peer can stay on the
> * island, but does not yet have the immunity
> * idol.
1306a1589
> nreach++;
1318c1601
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1320c1603
< index[i + 3] = index[i];
---
> indx[i + 3] = indx[i];
1322c1605
< index[i + 3] = nl3;
---
> indx[i + 3] = nl3;
1328c1611
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1330c1613
< index[i + 2] = index[i];
---
> indx[i + 2] = indx[i];
1332c1615
< index[i + 2] = nl3;
---
> indx[i + 2] = nl3;
1338c1621
< if (e >= endpoint[index[i]].val)
---
> if (e >= endpoint[indx[i]].val)
1340c1623
< index[i + 1] = index[i];
---
> indx[i + 1] = indx[i];
1342c1625
< index[i + 1] = nl3;
---
> indx[i + 1] = nl3;
1348c1631
< if (debug > 1)
---
> if (debug > 2)
1350,1351c1633,1635
< printf("select: endpoint %2d %.6f\n",
< endpoint[index[i]].type, endpoint[index[i]].val);
---
> printf("select: endpoint %2d %.6f\n",
> endpoint[indx[i]].type,
> endpoint[indx[i]].val);
1360c1644
< n += endpoint[index[i]].type;
---
> n += endpoint[indx[i]].type;
1363c1647
< if (endpoint[index[i]].type == 0)
---
> if (endpoint[indx[i]].type == 0)
1367c1651
< n += endpoint[index[j]].type;
---
> n += endpoint[indx[j]].type;
1370c1654
< if (endpoint[index[j]].type == 0)
---
> if (endpoint[indx[j]].type == 0)
1375,1376c1659,1660
< low = endpoint[index[i++]].val;
< high = endpoint[index[j--]].val;
---
> low = endpoint[indx[i++]].val;
> high = endpoint[indx[j--]].val;
1380,1383c1664,1667
< * If no survivors remain at this point, check if the acts or
< * local clock drivers have been found. If so, nominate one of
< * them as the only survivor. Otherwise, give up and declare us
< * unsynchronized.
---
> * If no survivors remain at this point, check if the local
> * clock or modem drivers have been found. If so, nominate one
> * of them as the only survivor. Otherwise, give up and declare
> * us unsynchronized.
1395,1397c1679,1680
< if (sys_peer != 0) {
< report_event(EVNT_PEERSTCHG,
< (struct peer *)0);
---
> if (osys_peer != NULL) {
> sys_poll = NTP_MINPOLL;
1399c1682
< msyslog(LOG_INFO,
---
> msyslog(LOG_INFO,
1400a1684,1685
> report_event(EVNT_PEERSTCHG,
> (struct peer *)0);
1402c1687,1690
< sys_peer = 0;
---
> sys_survivors = 0;
> #ifdef AUTOKEY
> resetmanycast();
> #endif /* AUTOKEY */
1407c1695
< if (debug > 1)
---
> if (debug > 2)
1412,1415c1700,1706
< * Clustering algorithm. Process intersection list to discard
< * outlyers. Construct candidate list in cluster order
< * determined by the sum of peer synchronization distance plus
< * scaled stratum. We must find at least one peer.
---
> * Clustering algorithm. Construct candidate list in order first
> * by stratum then by root distance. If we have more than
> * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
> * list to find falsetickers, who leave the island immediately.
> * If a falseticker is not configured, his association raft is
> * drowned as well. We must leave at least one peer to collect
> * the million bucks.
1420,1421c1711,1714
< if (nlist > 1 && (low >= peer->offset ||
< peer->offset >= high))
---
> if (nlist > 1 && (low >= peer->offset || peer->offset >=
> high)) {
> if (!(peer->flags & FLAG_CONFIG))
> unpeer(peer);
1423c1716,1717
< peer->status = CTL_PST_SEL_CORRECT;
---
> }
> peer->status = CTL_PST_SEL_DISTSYSPEER;
1434d1727
< synch[k] = synch[k - 1];
1435a1729,1730
> error[k] = error[k - 1];
> synch[k] = synch[k - 1];
1437a1733
> error[k] = peer->jitter;
1441a1738,1739
> for (i = 0; i < nlist; i++) {
> peer_list[i]->status = CTL_PST_SEL_SELCAND;
1444,1445c1742
< if (debug > 1)
< for (i = 0; i < nlist; i++)
---
> if (debug > 2)
1448a1746
> }
1451,1454c1749,1754
< * Now, prune outlyers by root dispersion. Continue as long as
< * there are more than NTP_MINCLOCK survivors and the minimum
< * select dispersion is greater than the maximum peer
< * dispersion. Stop if we are about to discard a prefer peer.
---
> * Now, vote outlyers off the island by select jitter weighted
> * by root dispersion. Continue voting as long as there are more
> * than NTP_MINCLOCK survivors and the minimum select jitter
> * squared is greater than the maximum peer jitter squared. Stop
> * if we are about to discard a prefer peer, who of course has
> * the immunity idol.
1456,1463d1755
< for (i = 0; i < nlist; i++) {
< peer = peer_list[i];
< error[i] = peer->variance;
< if (i < NTP_CANCLOCK)
< peer->status = CTL_PST_SEL_SELCAND;
< else
< peer->status = CTL_PST_SEL_DISTSYSPEER;
< }
1465,1468c1757,1760
< sys_maxd = 0;
< d = error[0];
< for (k = i = nlist - 1; i >= 0; i--) {
< double sdisp = 0;
---
> d = 1e9;
> e = -1e9;
> k = 0;
> for (i = 0; i < nlist; i++) {
1470,1473c1762,1769
< for (j = nlist - 1; j > 0; j--) {
< sdisp = NTP_SWEIGHT * (sdisp +
< DIFF(peer_list[i]->offset,
< peer_list[j]->offset));
---
> if (error[i] < d)
> d = error[i];
> f = 0;
> if (nlist > 1) {
> for (j = 0; j < nlist; j++)
> f += DIFF(peer_list[j]->offset,
> peer_list[i]->offset);
> f /= nlist - 1;
1475,1476c1771,1774
< if (sdisp > sys_maxd) {
< sys_maxd = sdisp;
---
> f = max(f, SQUARE(LOGTOD(sys_precision)));
> if (f * synch[i] > e) {
> sys_selerr = f;
> e = f * synch[i];
1479,1480d1776
< if (error[i] < d)
< d = error[i];
1484c1780
< if (debug > 1)
---
> if (debug > 2)
1487c1783
< nlist, SQRT(sys_maxd), SQRT(d));
---
> k, SQRT(sys_selerr), SQRT(d));
1489,1490c1785,1786
< if (nlist <= NTP_MINCLOCK || sys_maxd <= d ||
< peer_list[k]->flags & FLAG_PREFER)
---
> if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
> peer_list[k]->flags & FLAG_PREFER)
1491a1788,1789
> if (!(peer_list[k]->flags & FLAG_CONFIG))
> unpeer(peer_list[k]);
1497a1796,1811
>
> #ifdef AUTOKEY
> /*
> * In manycast client mode we may have spooked a sizeable number
> * of servers that we don't need. If there are at least
> * NTP_MINCLOCK of them, the manycast message will be turned
> * off. By the time we get here we nay be ready to prune some of
> * them back, but we want to make sure all the candicates have
> * had a chance. If they didn't pass the sanity and intersection
> * tests, they have already been voted off the island.
> */
> if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
> resetmanycast();
> #endif /* AUTOKEY */
> sys_survivors = nlist;
>
1499c1813
< if (debug > 1) {
---
> if (debug > 2) {
1503,1504c1817,1819
< ntoa(&peer_list[i]->srcadr), peer_list[i]->offset,
< synch[i], peer_list[i]->pollsw);
---
> ntoa(&peer_list[i]->srcadr),
> peer_list[i]->offset, synch[i],
> peer_list[i]->pollsw);
1522a1838,1843
> *
> * Note that we go no further, unless the number of survivors is
> * a majority of the suckers that have been found reachable and
> * no prior source is available. This avoids the transient when
> * one of a flock of sources is out to lunch and just happens
> * to be the first survivor.
1523a1845,1846
> if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
> return;
1526,1543c1849,1861
< peer_list[i]->status = CTL_PST_SEL_SYNCCAND;
< peer_list[i]->flags |= FLAG_SYSPEER;
< poll_update(peer_list[i], peer_list[i]->hpoll);
< if (peer_list[i]->stratum == peer_list[0]->stratum) {
< leap_consensus |= peer_list[i]->leap;
< if (peer_list[i]->refclktype == REFCLK_ATOM_PPS)
< typepps = peer_list[i];
< if (peer_list[i] == sys_peer)
< typesystem = peer_list[i];
< if (peer_list[i]->flags & FLAG_PREFER) {
< typeprefer = peer_list[i];
< if (fabs(typeprefer->offset) <
< clock_max)
< pps_update = 1;
< }
< } else {
< if (peer_list[i] == sys_peer)
< sys_peer = 0;
---
> peer = peer_list[i];
> peer->status = CTL_PST_SEL_SYNCCAND;
> peer->flags |= FLAG_SYSPEER;
> poll_update(peer, peer->hpoll);
> if (peer->stratum == peer_list[0]->stratum) {
> leap_consensus |= peer->leap;
> if (peer->refclktype == REFCLK_ATOM_PPS &&
> peer->stratum < STRATUM_UNSPEC)
> typepps = peer;
> if (peer == osys_peer)
> typesystem = peer;
> if (peer->flags & FLAG_PREFER)
> sys_prefer = peer;
1559,1563c1877,1884
< osys_peer = sys_peer;
< if (typeprefer && (typeprefer->refclktype == REFCLK_LOCALCLOCK
< || typeprefer->sstclktype == CTL_SST_TS_TELEPHONE ||
< !typepps)) {
< sys_peer = typeprefer;
---
> if (sys_prefer)
> sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
> sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
> !typepps;
> else
> sw = 0;
> if (sw) {
> sys_peer = sys_prefer;
1566c1887
< sys_epsil = sys_peer->variance;
---
> sys_syserr = sys_peer->jitter;
1572c1893
< } else if (typepps && pps_update) {
---
> } else if (typepps) {
1576c1897
< sys_epsil = sys_peer->variance;
---
> sys_syserr = sys_peer->jitter;
1578,1579c1899,1901
< NLOG(NLOG_SYSEVENT) /* conditional syslog */
< msyslog(LOG_INFO, "pps sync enabled");
---
> NLOG(NLOG_SYSEVENT)
> msyslog(LOG_INFO,
> "pps sync enabled");
1583c1905,1906
< printf("select: pps offset %.6f\n", sys_offset);
---
> printf("select: pps offset %.6f\n",
> sys_offset);
1586c1909,1911
< if (!typesystem)
---
> if (typesystem)
> sys_peer = osys_peer;
> else
1590c1915
< sys_epsil = sys_peer->variance + sys_maxd;
---
> sys_syserr = sys_peer->jitter + sys_selerr;
1630,1633c1955,1962
< return ((fabs(peer->delay) + peer->rootdelay) / 2 +
< peer->rootdispersion + peer->disp +
< SQRT(peer->variance) + CLOCK_PHI * (current_time -
< peer->update));
---
> /*
> * Careful squeak here. The value returned must be greater than
> * zero blamed on the peer jitter, which must be at least the
> * square of sys_precision.
> */
> return ((peer->rootdelay + peer->delay) / 2 +
> peer->rootdispersion + peer->disp + clock_phi *
> (current_time - peer->update) + SQRT(peer->jitter));
1644,1647c1973,1976
< struct pkt xpkt;
< int find_rtt = (peer->cast_flags & MDF_MCAST) &&
< peer->hmode != MODE_BROADCAST;
< int sendlen;
---
> struct pkt xpkt; /* transmit packet */
> int sendlen, authlen;
> keyid_t xkeyid; /* transmit key ID */
> l_fp xmt_tx;
1650c1979
< * Initialize protocol fields.
---
> * Initialize transmit packet header fields.
1652,1653c1981,1982
< xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
< peer->version, peer->hmode);
---
> xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
> peer->hmode);
1658,1659c1987
< xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion +
< LOGTOD(sys_precision)));
---
> xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
1666,1669c1994,2001
< * Authenticate the packet if enabled and either configured or
< * the previous packet was authenticated. If for some reason the
< * key associated with the key identifier is not in the key
< * cache, then honk key zero.
---
> * If the received packet contains a MAC, the transmitted packet
> * is authenticated and contains a MAC. If not, the transmitted
> * packet is not authenticated.
> *
> * In the current I/O semantics the default interface is set
> * until after receiving a packet and setting the right
> * interface. So, the first packet goes out unauthenticated.
> * That's why the really icky test next is here.
1672,1674c2004,2017
< if (peer->flags & FLAG_AUTHENABLE) {
< u_long xkeyid;
< l_fp xmt_tx;
---
> if (!(peer->flags & FLAG_AUTHENABLE)) {
> get_systime(&peer->xmt);
> HTONL_FP(&peer->xmt, &xpkt.xmt);
> sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
> sendlen);
> peer->sent++;
> #ifdef DEBUG
> if (debug)
> printf("transmit: at %ld %s->%s mode %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode);
> #endif
> return;
> }
1675a2019,2027
> /*
> * The received packet contains a MAC, so the transmitted packet
> * must be authenticated. If autokey is enabled, fuss with the
> * various modes; otherwise, private key cryptography is used.
> */
> #ifdef AUTOKEY
> if ((peer->flags & FLAG_SKEY)) {
> u_int cmmd;
>
1677,1678c2029,2048
< * Transmit encrypted packet compensated for the
< * encryption delay.
---
> * The Public Key Dance (PKD): Cryptographic credentials
> * are contained in extension fields, each including a
> * 4-octet length/code word followed by a 4-octet
> * association ID and optional additional data. Optional
> * data includes a 4-octet data length field followed by
> * the data itself. Request messages are sent from a
> * configured association; response messages can be sent
> * from a configured association or can take the fast
> * path without ever matching an association. Response
> * messages have the same code as the request, but have
> * a response bit and possibly an error bit set. In this
> * implementation, a message may contain no more than
> * one command and no more than one response.
> *
> * Cryptographic session keys include both a public and
> * a private componet. Request and response messages
> * using extension fields are always sent with the
> * private component set to zero. Packets without
> * extension fields indlude the private component when
> * the session key is generated.
1680,1682c2050,2051
< #ifdef MD5
< if (peer->flags & FLAG_SKEY) {
<
---
> while (1) {
>
1684,1692c2053,2070
< * In autokey mode, allocate and initialize a
< * key list if not already done. Then, use the
< * list in inverse order, discarding keys once
< * used. Keep the latest key around until the
< * next one, so clients can use client/server
< * packets to compute propagation delay. Note we
< * have to wait until the receive side of the
< * socket is bound and the server address
< * confirmed.
---
> * Allocate and initialize a keylist if not
> * already done. Then, use the list in inverse
> * order, discarding keys once used. Keep the
> * latest key around until the next one, so
> * clients can use client/server packets to
> * compute propagation delay.
> *
> * Note that once a key is used from the list,
> * it is retained in the key cache until the
> * next key is used. This is to allow a client
> * to retrieve the encrypted session key
> * identifier to verify authenticity.
> *
> * If for some reason a key is no longer in the
> * key cache, a birthday has happened and the
> * pseudo-random sequence is probably broken. In
> * that case, purge the keylist and regenerate
> * it.
1694,1716c2072,2080
< if (ntohl(peer->dstadr->sin.sin_addr.s_addr) ==
< 0 &&
< ntohl(peer->dstadr->bcast.sin_addr.s_addr) == 0)
< peer->keyid = 0;
< else {
< if (peer->keylist == 0) {
< make_keylist(peer);
< } else {
< authtrust(peer->keylist[peer->keynumber], 0);
< if (peer->keynumber == 0)
< make_keylist(peer);
< else {
< peer->keynumber--;
< xkeyid = peer->keylist[peer->keynumber];
< if (!authistrusted(xkeyid))
< make_keylist(peer);
< }
< }
< peer->keyid = peer->keylist[peer->keynumber];
< xpkt.keyid1 = htonl(2 * sizeof(u_int32));
< xpkt.keyid2 = htonl(sys_private);
< sendlen += 2 * sizeof(u_int32);
< }
---
> if (peer->keynumber == 0)
> make_keylist(peer, peer->dstadr);
> else
> peer->keynumber--;
> xkeyid = peer->keylist[peer->keynumber];
> if (authistrusted(xkeyid))
> break;
> else
> key_expire(peer);
1718,1729c2082,2083
< #endif /* MD5 */
< xkeyid = peer->keyid;
< get_systime(&peer->xmt);
< L_ADD(&peer->xmt, &sys_authdelay);
< HTONL_FP(&peer->xmt, &xpkt.xmt);
< sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt,
< sendlen);
< get_systime(&xmt_tx);
< sendpkt(&peer->srcadr, find_rtt ? any_interface :
< peer->dstadr, ((peer->cast_flags & MDF_MCAST) &&
< !find_rtt) ? ((peer->cast_flags & MDF_ACAST) ? -7 :
< peer->ttl) : -7, &xpkt, sendlen);
---
> peer->keyid = xkeyid;
> switch (peer->hmode) {
1732,1733c2086,2089
< * Calculate the encryption delay. Keep the minimum over
< * the latest two samples.
---
> * In broadcast mode the autokey values are required.
> * Send them when a new keylist is generated; otherwise,
> * send the association ID so the client can request
> * them at other times.
1735,1751c2091,2099
< L_SUB(&xmt_tx, &peer->xmt);
< L_ADD(&xmt_tx, &sys_authdelay);
< sys_authdly[1] = sys_authdly[0];
< sys_authdly[0] = xmt_tx.l_uf;
< if (sys_authdly[0] < sys_authdly[1])
< sys_authdelay.l_uf = sys_authdly[0];
< else
< sys_authdelay.l_uf = sys_authdly[1];
< peer->sent++;
< #ifdef DEBUG
< if (debug)
< printf(
< "transmit: at %ld to %s mode %d keyid %08lx index %d\n",
< current_time, ntoa(&peer->srcadr),
< peer->hmode, xkeyid, peer->keynumber);
< #endif
< } else {
---
> case MODE_BROADCAST:
> if (peer->flags & FLAG_ASSOC)
> cmmd = CRYPTO_AUTO | CRYPTO_RESP;
> else
> cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, cmmd, 0, peer->associd);
> break;
>
1753c2101,2119
< * Transmit non-authenticated packet.
---
> * In symmetric modes the public key, leapsecond table,
> * agreement parameters and autokey values are required.
> *
> * 1. If a response is pending, always send it first.
> *
> * 2. Don't send anything except a public-key request
> * until the public key has been stored.
> *
> * 3. Once the public key has been stored, don't send
> * anything except an agreement parameter request
> * until the agreement parameters have been stored.
> *
> * 4. Once the argeement parameters have been stored,
> * don't send anything except a public value request
> * until the agreed key has been stored.
> *
> * 5. When the agreed key has been stored and the key
> * list is regenerated, send the autokey values
> * gratis unless they have already been sent.
1755,1761c2121,2285
< get_systime(&(peer->xmt));
< HTONL_FP(&peer->xmt, &xpkt.xmt);
< sendpkt(&(peer->srcadr), find_rtt ? any_interface :
< peer->dstadr, ((peer->cast_flags & MDF_MCAST) &&
< !find_rtt) ? ((peer->cast_flags & MDF_ACAST) ? -7 :
< peer->ttl) : -8, &xpkt, sendlen);
< peer->sent++;
---
> case MODE_ACTIVE:
> case MODE_PASSIVE:
> #ifdef PUBKEY
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (!peer->crypto)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_ASSOC,
> peer->hcookie, peer->assoc);
> else if (!crypto_flags &&
> peer->pcookie.tstamp == 0 && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> else if (crypto_flags && peer->pubkey.ptr ==
> NULL)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_NAME, peer->hcookie,
> peer->assoc);
> else if (peer->crypto & CRYPTO_FLAG_CERT)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_CERT, peer->hcookie,
> peer->assoc);
> else if (crypto_flags && peer->crypto &
> CRYPTO_FLAG_DH && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_DHPAR,
> peer->hcookie, peer->assoc);
> else if (crypto_flags && peer->pcookie.tstamp ==
> 0 && sys_leap != LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_DH, peer->hcookie,
> peer->assoc);
> #else
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (peer->pcookie.tstamp == 0 && sys_leap !=
> LEAP_NOTINSYNC)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> else if (!(peer->flags & FLAG_AUTOKEY))
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO, peer->hcookie,
> peer->assoc);
> else if ((peer->flags & FLAG_ASSOC) &&
> (peer->cmmd >> 16) != CRYPTO_AUTO)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO | CRYPTO_RESP,
> peer->hcookie, peer->associd);
> #ifdef PUBKEY
> else if (peer->crypto & CRYPTO_FLAG_TAI)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_TAI, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> peer->cmmd = 0;
> break;
>
> /*
> * In client mode, the public key, host cookie and
> * autokey values are required. In broadcast client
> * mode, these values must be acquired during the
> * client/server exchange to avoid having to wait until
> * the next key list regeneration. Otherwise, the poor
> * dude may die a lingering death until becoming
> * unreachable and attempting rebirth. Note that we ask
> * for the cookie at each key list regeneration anyway.
> */
> case MODE_CLIENT:
> if (peer->cmmd != 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, (peer->cmmd >> 16) |
> CRYPTO_RESP, peer->hcookie,
> peer->associd);
> if (!peer->crypto)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_ASSOC,
> peer->hcookie, peer->assoc);
> #ifdef PUBKEY
> else if (crypto_flags && peer->pubkey.ptr ==
> NULL)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_NAME, peer->hcookie,
> peer->assoc);
> else if (peer->crypto & CRYPTO_FLAG_CERT)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_CERT, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> else if (peer->pcookie.tstamp == 0)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_PRIV, peer->hcookie,
> peer->assoc);
> else if (!(peer->flags & FLAG_AUTOKEY) &&
> (peer->cast_flags & MDF_BCLNT))
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_AUTO, peer->hcookie,
> peer->assoc);
> #ifdef PUBKEY
> else if (peer->crypto & CRYPTO_FLAG_TAI)
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, CRYPTO_TAI, peer->hcookie,
> peer->assoc);
> #endif /* PUBKEY */
> peer->cmmd = 0;
> break;
> }
>
> /*
> * If extension fields are present, we must use a
> * private value of zero and force min poll interval.
> * Most intricate.
> */
> if (sendlen > LEN_PKT_NOMAC)
> session_key(&peer->dstadr->sin, &peer->srcadr,
> xkeyid, 0, 2);
> }
> #endif /* AUTOKEY */
> xkeyid = peer->keyid;
> get_systime(&peer->xmt);
> L_ADD(&peer->xmt, &sys_authdelay);
> HTONL_FP(&peer->xmt, &xpkt.xmt);
> authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
> if (authlen == 0) {
> msyslog(LOG_NOTICE,
> "transmit: no encryption key found");
> peer->flash |= TEST4 | TEST5;
> return;
> }
> sendlen += authlen;
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY)
> authtrust(xkeyid, 0);
> #endif /* AUTOKEY */
> get_systime(&xmt_tx);
> if (sendlen > sizeof(xpkt)) {
> msyslog(LOG_ERR, "buffer overflow %u", sendlen);
> exit(-1);
> }
> sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
>
> /*
> * Calculate the encryption delay. Keep the minimum over
> * the latest two samples.
> */
> L_SUB(&xmt_tx, &peer->xmt);
> L_ADD(&xmt_tx, &sys_authdelay);
> sys_authdly[1] = sys_authdly[0];
> sys_authdly[0] = xmt_tx.l_uf;
> if (sys_authdly[0] < sys_authdly[1])
> sys_authdelay.l_uf = sys_authdly[0];
> else
> sys_authdelay.l_uf = sys_authdly[1];
> peer->sent++;
> #ifdef AUTOKEY
1763,1766c2287,2292
< if (debug)
< printf("transmit: at %ld to %s mode %d\n",
< current_time, ntoa(&peer->srcadr),
< peer->hmode);
---
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
> authlen, peer->keynumber);
1768c2294,2303
< }
---
> #else
> #ifdef DEBUG
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
> current_time, ntoa(&peer->dstadr->sin),
> ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
> authlen);
> #endif
> #endif /* AUTOKEY */
1770a2306
>
1772c2308,2309
< * fast_xmit - Send packet for nonpersistent association.
---
> * fast_xmit - Send packet for nonpersistent association. Note that
> * neither the source or destination can be a broadcast address.
1778c2315,2316
< u_long xkeyid /* transmit key ID */
---
> keyid_t xkeyid, /* transmit key ID */
> int mask /* restrict mask */
1781,1784c2319,2323
< struct pkt xpkt;
< struct pkt *rpkt;
< int sendlen;
< l_fp xmt_ts;
---
> struct pkt xpkt; /* transmit packet structure */
> struct pkt *rpkt; /* receive packet structure */
> l_fp xmt_ts; /* transmit timestamp */
> l_fp xmt_tx; /* transmit timestamp after authent */
> int sendlen, authlen;
1787,1788c2326,2329
< * Initialize transmit packet header fields in the receive
< * buffer provided. We leave some fields intact as received.
---
> * Initialize transmit packet header fields from the receive
> * buffer provided. We leave some fields intact as received. If
> * the gazinta was from a multicast address, the gazouta must go
> * out another way.
1791,1793c2332,2354
< xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
< PKT_VERSION(rpkt->li_vn_mode), xmode);
< xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
---
> if (rbufp->dstadr->flags & INT_MULTICAST)
> rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
>
> /*
> * If the caller is restricted, return a kiss-of-death packet;
> * otherwise, smooch politely.
> */
> if (mask & (RES_DONTSERVE | RES_LIMITED)) {
> if (!(mask & RES_DEMOBILIZE)) {
> return;
> } else {
> xpkt.li_vn_mode =
> PKT_LI_VN_MODE(LEAP_NOTINSYNC,
> PKT_VERSION(rpkt->li_vn_mode), xmode);
> xpkt.stratum = STRATUM_UNSPEC;
> memcpy(&xpkt.refid, "DENY", 4);
> }
> } else {
> xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
> PKT_VERSION(rpkt->li_vn_mode), xmode);
> xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
> xpkt.refid = sys_refid;
> }
1797,1799c2358,2359
< xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion +
< LOGTOD(sys_precision)));
< xpkt.refid = sys_refid;
---
> xpkt.rootdispersion =
> HTONS_FP(DTOUFP(sys_rootdispersion));
1803,1805d2362
< sendlen = LEN_PKT_NOMAC;
< if (rbufp->recv_length > sendlen) {
< l_fp xmt_tx;
1807,1815c2364,2370
< /*
< * Transmit encrypted packet compensated for the
< * encryption delay.
< */
< if (xkeyid > NTP_MAXKEY) {
< xpkt.keyid1 = htonl(2 * sizeof(u_int32));
< xpkt.keyid2 = htonl(sys_private);
< sendlen += 2 * sizeof(u_int32);
< }
---
> /*
> * If the received packet contains a MAC, the transmitted packet
> * is authenticated and contains a MAC. If not, the transmitted
> * packet is not authenticated.
> */
> sendlen = LEN_PKT_NOMAC;
> if (rbufp->recv_length == sendlen) {
1817d2371
< L_ADD(&xmt_ts, &sys_authdelay);
1819c2373
< sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt,
---
> sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
1821,1836d2374
< get_systime(&xmt_tx);
< sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, -9, &xpkt,
< sendlen);
<
< /*
< * Calculate the encryption delay. Keep the minimum over
< * the latest two samples.
< */
< L_SUB(&xmt_tx, &xmt_ts);
< L_ADD(&xmt_tx, &sys_authdelay);
< sys_authdly[1] = sys_authdly[0];
< sys_authdly[0] = xmt_tx.l_uf;
< if (sys_authdly[0] < sys_authdly[1])
< sys_authdelay.l_uf = sys_authdly[0];
< else
< sys_authdelay.l_uf = sys_authdly[1];
1839,1842c2377,2379
< printf(
< "transmit: at %ld to %s mode %d keyid %08lx\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< xmode, xkeyid);
---
> printf("transmit: at %ld %s->%s mode %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), xmode);
1844c2381,2382
< } else {
---
> return;
> }
1845a2384,2396
> /*
> * The received packet contains a MAC, so the transmitted packet
> * must be authenticated. For private-key cryptography, use the
> * predefined private keys to generate the cryptosum. For
> * autokey cryptography, use the server private value to
> * generate the cookie, which is unique for every source-
> * destination-key ID combination.
> */
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY) {
> keyid_t cookie;
> u_int code, associd;
>
1847c2398,2404
< * Transmit non-authenticated packet.
---
> * The only way to get here is a reply to a legitimate
> * client request message, so the mode must be
> * MODE_SERVER. If an extension field is present, there
> * can be only one and that must be a command. Do what
> * needs, but with private value of zero so the poor
> * jerk can decode it. If no extension field is present,
> * use the cookie to generate the session key.
1849,1852c2406,2449
< get_systime(&xmt_ts);
< HTONL_FP(&xmt_ts, &xpkt.xmt);
< sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, -10, &xpkt,
< sendlen);
---
> code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
> cookie = session_key(&rbufp->recv_srcadr,
> &rbufp->dstadr->sin, 0, sys_private, 0);
> associd = htonl(rpkt->exten[1]);
> if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
> sizeof(u_int32)) {
> session_key(&rbufp->dstadr->sin,
> &rbufp->recv_srcadr, xkeyid, 0, 2);
> sendlen += crypto_xmit((u_int32 *)&xpkt,
> sendlen, code, cookie, associd);
> } else {
> session_key(&rbufp->dstadr->sin,
> &rbufp->recv_srcadr, xkeyid, cookie, 2);
> }
> }
> #endif /* AUTOKEY */
> get_systime(&xmt_ts);
> L_ADD(&xmt_ts, &sys_authdelay);
> HTONL_FP(&xmt_ts, &xpkt.xmt);
> authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
> sendlen += authlen;
> #ifdef AUTOKEY
> if (xkeyid > NTP_MAXKEY)
> authtrust(xkeyid, 0);
> #endif /* AUTOKEY */
> get_systime(&xmt_tx);
> if (sendlen > sizeof(xpkt)) {
> msyslog(LOG_ERR, "buffer overflow %u", sendlen);
> exit(-1);
> }
> sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
>
> /*
> * Calculate the encryption delay. Keep the minimum over the
> * latest two samples.
> */
> L_SUB(&xmt_tx, &xmt_ts);
> L_ADD(&xmt_tx, &sys_authdelay);
> sys_authdly[1] = sys_authdly[0];
> sys_authdly[0] = xmt_tx.l_uf;
> if (sys_authdly[0] < sys_authdly[1])
> sys_authdelay.l_uf = sys_authdly[0];
> else
> sys_authdelay.l_uf = sys_authdly[1];
1854,1857c2451,2456
< if (debug)
< printf("transmit: at %ld to %s mode %d\n",
< current_time, ntoa(&rbufp->recv_srcadr),
< xmode);
---
> if (debug)
> printf(
> "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
> current_time, ntoa(&rbufp->dstadr->sin),
> ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
> authlen);
1859d2457
< }
1862c2460,2461
< #ifdef MD5
---
>
> #ifdef AUTOKEY
1864c2463
< * Compute key list
---
> * key_expire - purge the key list
1866,1868c2465,2467
< static void
< make_keylist(
< struct peer *peer
---
> void
> key_expire(
> struct peer *peer /* peer structure pointer */
1872,1873d2470
< u_long keyid;
< u_long ltemp;
1875,1892c2472,2476
< /*
< * Allocate the key list if necessary.
< */
< if (peer->keylist == 0)
< peer->keylist = (u_long *)emalloc(sizeof(u_long) *
< NTP_MAXSESSION);
<
< /*
< * Generate an initial key ID which is unique and greater than
< * NTP_MAXKEY.
< */
< while (1) {
< keyid = (u_long)RANDOM & 0xffffffff;
< if (keyid <= NTP_MAXKEY)
< continue;
< if (authhavekey(keyid))
< continue;
< break;
---
> if (peer->keylist != NULL) {
> for (i = 0; i <= peer->keynumber; i++)
> authtrust(peer->keylist[i], 0);
> free(peer->keylist);
> peer->keylist = NULL;
1894,1914c2478,2482
<
< /*
< * Generate up to NTP_MAXSESSION session keys. Stop if the
< * next one would not be unique or not a session key ID or if
< * it would expire before the next poll.
< */
< ltemp = sys_automax;
< for (i = 0; i < NTP_MAXSESSION; i++) {
< peer->keylist[i] = keyid;
< peer->keynumber = i;
< keyid = session_key(
< ntohl(peer->dstadr->sin.sin_addr.s_addr),
< (peer->hmode == MODE_BROADCAST || (peer->flags &
< FLAG_MCAST2)) ?
< ntohl(peer->dstadr->bcast.sin_addr.s_addr):
< ntohl(peer->srcadr.sin_addr.s_addr), keyid, ltemp);
< ltemp -= 1 << peer->hpoll;
< if (auth_havekey(keyid) || keyid <= NTP_MAXKEY ||
< ltemp <= (1 << (peer->hpoll + 1)))
< break;
< }
---
> peer->keynumber = peer->sndauto.seq = 0;
> #ifdef DEBUG
> if (debug)
> printf("key_expire: at %lu\n", current_time);
> #endif
1916c2484
< #endif /* MD5 */
---
> #endif /* AUTOKEY */
2035a2604
> sys_jitter = LOGTOD(sys_precision);
2040c2609,2610
< sys_peer = 0;
---
> sys_peer = NULL;
> sys_survivors = 0;
2044d2613
< #if defined(DES) || defined(MD5)
2046,2048d2614
< #else
< sys_authenticate = 0;
< #endif
2059a2626
> #ifdef AUTOKEY
2060a2628
> #endif /* AUTOKEY */
2069c2637
< msyslog(LOG_DEBUG, "kern_enable is %d", kern_enable);
---
> pps_enable = 0;
2073c2641,2642
< * Some system clocks should only be adjusted in 10ms increments.
---
> * Some system clocks should only be adjusted in 10ms
> * increments.
2178a2748,2765
> case PROTO_PPS:
>
> /*
> * Turn on/off PPS discipline
> */
> pps_enable = (int)value;
> break;
>
> #ifdef REFCLOCK
> case PROTO_CAL:
>
> /*
> * Turn on/off refclock calibrate
> */
> cal_enable = (int)value;
> break;
> #endif
>