Annotation of embedaddon/ntp/ntpd/ntp_proto.c, revision 1.1
1.1 ! misho 1: /*
! 2: * ntp_proto.c - NTP version 4 protocol machinery
! 3: *
! 4: * ATTENTION: Get approval from Dave Mills on all changes to this file!
! 5: *
! 6: */
! 7: #ifdef HAVE_CONFIG_H
! 8: #include <config.h>
! 9: #endif
! 10:
! 11: #include "ntpd.h"
! 12: #include "ntp_stdlib.h"
! 13: #include "ntp_unixtime.h"
! 14: #include "ntp_control.h"
! 15: #include "ntp_string.h"
! 16:
! 17: #include <stdio.h>
! 18: #ifdef HAVE_LIBSCF_H
! 19: #include <libscf.h>
! 20: #include <unistd.h>
! 21: #endif /* HAVE_LIBSCF_H */
! 22:
! 23:
! 24: #if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
! 25: #include "ntp_refclock.h"
! 26: #endif
! 27:
! 28: /*
! 29: * This macro defines the authentication state. If x is 1 authentication
! 30: * is required; othewise it is optional.
! 31: */
! 32: #define AUTH(x, y) ((x) ? (y) == AUTH_OK : (y) == AUTH_OK || \
! 33: (y) == AUTH_NONE)
! 34:
! 35: #define AUTH_NONE 0 /* authentication not required */
! 36: #define AUTH_OK 1 /* authentication OK */
! 37: #define AUTH_ERROR 2 /* authentication error */
! 38: #define AUTH_CRYPTO 3 /* crypto_NAK */
! 39:
! 40: /*
! 41: * traffic shaping parameters
! 42: */
! 43: #define NTP_IBURST 6 /* packets in iburst */
! 44: #define RESP_DELAY 1 /* refclock burst delay (s) */
! 45:
! 46: /*
! 47: * System variables are declared here. Unless specified otherwise, all
! 48: * times are in seconds.
! 49: */
! 50: u_char sys_leap; /* system leap indicator */
! 51: u_char sys_stratum; /* system stratum */
! 52: s_char sys_precision; /* local clock precision (log2 s) */
! 53: double sys_rootdelay; /* roundtrip delay to primary source */
! 54: double sys_rootdisp; /* dispersion to primary source */
! 55: u_int32 sys_refid; /* reference id (network byte order) */
! 56: l_fp sys_reftime; /* last update time */
! 57: struct peer *sys_peer; /* current peer */
! 58:
! 59: /*
! 60: * Rate controls. Leaky buckets are used to throttle the packet
! 61: * transmission rates in order to protect busy servers such as at NIST
! 62: * and USNO. There is a counter for each association and another for KoD
! 63: * packets. The association counter decrements each second, but not
! 64: * below zero. Each time a packet is sent the counter is incremented by
! 65: * a configurable value representing the average interval between
! 66: * packets. A packet is delayed as long as the counter is greater than
! 67: * zero. Note this does not affect the time value computations.
! 68: */
! 69: /*
! 70: * Nonspecified system state variables
! 71: */
! 72: int sys_bclient; /* broadcast client enable */
! 73: double sys_bdelay; /* broadcast client default delay */
! 74: int sys_authenticate; /* requre authentication for config */
! 75: l_fp sys_authdelay; /* authentication delay */
! 76: double sys_offset; /* current local clock offset */
! 77: double sys_mindisp = MINDISPERSE; /* minimum distance (s) */
! 78: double sys_maxdist = MAXDISTANCE; /* selection threshold */
! 79: double sys_jitter; /* system jitter */
! 80: u_long sys_epoch; /* last clock update time */
! 81: static double sys_clockhop; /* clockhop threshold */
! 82: int leap_tai; /* TAI at next next leap */
! 83: u_long leap_sec; /* next scheduled leap from file */
! 84: u_long leap_peers; /* next scheduled leap from peers */
! 85: u_long leap_expire; /* leap information expiration */
! 86: static int leap_vote; /* leap consensus */
! 87: keyid_t sys_private; /* private value for session seed */
! 88: int sys_manycastserver; /* respond to manycast client pkts */
! 89: int peer_ntpdate; /* active peers in ntpdate mode */
! 90: int sys_survivors; /* truest of the truechimers */
! 91:
! 92: /*
! 93: * TOS and multicast mapping stuff
! 94: */
! 95: int sys_floor = 0; /* cluster stratum floor */
! 96: int sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling */
! 97: int sys_minsane = 1; /* minimum candidates */
! 98: int sys_minclock = NTP_MINCLOCK; /* minimum candidates */
! 99: int sys_maxclock = NTP_MAXCLOCK; /* maximum candidates */
! 100: int sys_cohort = 0; /* cohort switch */
! 101: int sys_orphan = STRATUM_UNSPEC + 1; /* orphan stratum */
! 102: int sys_beacon = BEACON; /* manycast beacon interval */
! 103: int sys_ttlmax; /* max ttl mapping vector index */
! 104: u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
! 105:
! 106: /*
! 107: * Statistics counters - first the good, then the bad
! 108: */
! 109: u_long sys_stattime; /* elapsed time */
! 110: u_long sys_received; /* packets received */
! 111: u_long sys_processed; /* packets for this host */
! 112: u_long sys_newversion; /* current version */
! 113: u_long sys_oldversion; /* old version */
! 114: u_long sys_restricted; /* access denied */
! 115: u_long sys_badlength; /* bad length or format */
! 116: u_long sys_badauth; /* bad authentication */
! 117: u_long sys_declined; /* declined */
! 118: u_long sys_limitrejected; /* rate exceeded */
! 119: u_long sys_kodsent; /* KoD sent */
! 120:
! 121: static double root_distance (struct peer *);
! 122: static void clock_combine (struct peer **, int);
! 123: static void peer_xmit (struct peer *);
! 124: static void fast_xmit (struct recvbuf *, int, keyid_t,
! 125: int);
! 126: static void clock_update (struct peer *);
! 127: static int default_get_precision (void);
! 128: static int local_refid (struct peer *);
! 129: static int peer_unfit (struct peer *);
! 130:
! 131:
! 132: /*
! 133: * transmit - transmit procedure called by poll timeout
! 134: */
! 135: void
! 136: transmit(
! 137: struct peer *peer /* peer structure pointer */
! 138: )
! 139: {
! 140: int hpoll;
! 141:
! 142: /*
! 143: * The polling state machine. There are two kinds of machines,
! 144: * those that never expect a reply (broadcast and manycast
! 145: * server modes) and those that do (all other modes). The dance
! 146: * is intricate...
! 147: */
! 148: hpoll = peer->hpoll;
! 149:
! 150: /*
! 151: * In broadcast mode the poll interval is never changed from
! 152: * minpoll.
! 153: */
! 154: if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
! 155: peer->outdate = current_time;
! 156: if (sys_leap != LEAP_NOTINSYNC)
! 157: peer_xmit(peer);
! 158: poll_update(peer, hpoll);
! 159: return;
! 160: }
! 161:
! 162: /*
! 163: * In manycast mode we start with unity ttl. The ttl is
! 164: * increased by one for each poll until either sys_maxclock
! 165: * servers have been found or the maximum ttl is reached. When
! 166: * sys_maxclock servers are found we stop polling until one or
! 167: * more servers have timed out or until less than minpoll
! 168: * associations turn up. In this case additional better servers
! 169: * are dragged in and preempt the existing ones.
! 170: */
! 171: if (peer->cast_flags & MDF_ACAST) {
! 172: peer->outdate = current_time;
! 173: if (peer->unreach > sys_beacon) {
! 174: peer->unreach = 0;
! 175: peer->ttl = 0;
! 176: peer_xmit(peer);
! 177: } else if (sys_survivors < sys_minclock ||
! 178: peer_associations < sys_maxclock) {
! 179: if (peer->ttl < sys_ttlmax)
! 180: peer->ttl++;
! 181: peer_xmit(peer);
! 182: }
! 183: peer->unreach++;
! 184: poll_update(peer, hpoll);
! 185: return;
! 186: }
! 187:
! 188: /*
! 189: * In unicast modes the dance is much more intricate. It is
! 190: * desigmed to back off whenever possible to minimize network
! 191: * traffic.
! 192: */
! 193: if (peer->burst == 0) {
! 194: u_char oreach;
! 195:
! 196: /*
! 197: * Update the reachability status. If not heard for
! 198: * three consecutive polls, stuff infinity in the clock
! 199: * filter.
! 200: */
! 201: oreach = peer->reach;
! 202: peer->outdate = current_time;
! 203: peer->unreach++;
! 204: peer->reach <<= 1;
! 205: if (!(peer->reach & 0x0f))
! 206: clock_filter(peer, 0., 0., MAXDISPERSE);
! 207: if (!peer->reach) {
! 208:
! 209: /*
! 210: * Here the peer is unreachable. If it was
! 211: * previously reachable raise a trap. Send a
! 212: * burst if enabled.
! 213: */
! 214: if (oreach)
! 215: report_event(PEVNT_UNREACH, peer, NULL);
! 216: if ((peer->flags & FLAG_IBURST) &&
! 217: peer->retry == 0)
! 218: peer->retry = NTP_RETRY;
! 219: } else {
! 220:
! 221: /*
! 222: * Here the peer is reachable. Send a burst if
! 223: * enabled and the peer is fit.
! 224: */
! 225: hpoll = sys_poll;
! 226: if (!(peer->flags & FLAG_PREEMPT &&
! 227: peer->hmode == MODE_CLIENT))
! 228: peer->unreach = 0;
! 229: if ((peer->flags & FLAG_BURST) && peer->retry ==
! 230: 0 && !peer_unfit(peer))
! 231: peer->retry = NTP_RETRY;
! 232: }
! 233:
! 234: /*
! 235: * Watch for timeout. If preemptable, toss the rascal;
! 236: * otherwise, bump the poll interval. Note the
! 237: * poll_update() routine will clamp it to maxpoll.
! 238: */
! 239: if (peer->unreach >= NTP_UNREACH) {
! 240: hpoll++;
! 241: if (peer->flags & FLAG_PREEMPT) {
! 242: report_event(PEVNT_RESTART, peer,
! 243: "timeout");
! 244: if (peer->hmode != MODE_CLIENT) {
! 245: peer_clear(peer, "TIME");
! 246: unpeer(peer);
! 247: return;
! 248: }
! 249: if (peer_associations > sys_maxclock &&
! 250: score_all(peer)) {
! 251: peer_clear(peer, "TIME");
! 252: unpeer(peer);
! 253: return;
! 254: }
! 255: }
! 256: }
! 257: } else {
! 258: peer->burst--;
! 259: if (peer->burst == 0) {
! 260:
! 261: /*
! 262: * If ntpdate mode and the clock has not been
! 263: * set and all peers have completed the burst,
! 264: * we declare a successful failure.
! 265: */
! 266: if (mode_ntpdate) {
! 267: peer_ntpdate--;
! 268: if (peer_ntpdate == 0) {
! 269: msyslog(LOG_NOTICE,
! 270: "ntpd: no servers found");
! 271: printf(
! 272: "ntpd: no servers found\n");
! 273: exit (0);
! 274: }
! 275: }
! 276: }
! 277: }
! 278: if (peer->retry > 0)
! 279: peer->retry--;
! 280:
! 281: /*
! 282: * Do not transmit if in broadcast client mode.
! 283: */
! 284: if (peer->hmode != MODE_BCLIENT)
! 285: peer_xmit(peer);
! 286: poll_update(peer, hpoll);
! 287: }
! 288:
! 289:
! 290: /*
! 291: * receive - receive procedure called for each packet received
! 292: */
! 293: void
! 294: receive(
! 295: struct recvbuf *rbufp
! 296: )
! 297: {
! 298: register struct peer *peer; /* peer structure pointer */
! 299: register struct pkt *pkt; /* receive packet pointer */
! 300: int hisversion; /* packet version */
! 301: int hisleap; /* packet leap indicator */
! 302: int hismode; /* packet mode */
! 303: int hisstratum; /* packet stratum */
! 304: int restrict_mask; /* restrict bits */
! 305: int has_mac; /* length of MAC field */
! 306: int authlen; /* offset of MAC field */
! 307: int is_authentic = 0; /* cryptosum ok */
! 308: int retcode = AM_NOMATCH; /* match code */
! 309: keyid_t skeyid = 0; /* key IDs */
! 310: u_int32 opcode = 0; /* extension field opcode */
! 311: sockaddr_u *dstadr_sin; /* active runway */
! 312: struct peer *peer2; /* aux peer structure pointer */
! 313: endpt * match_ep; /* newpeer() local address */
! 314: l_fp p_org; /* origin timestamp */
! 315: l_fp p_rec; /* receive timestamp */
! 316: l_fp p_xmt; /* transmit timestamp */
! 317: #ifdef OPENSSL
! 318: struct autokey *ap; /* autokey structure pointer */
! 319: int rval; /* cookie snatcher */
! 320: keyid_t pkeyid = 0, tkeyid = 0; /* key IDs */
! 321: #endif /* OPENSSL */
! 322: #ifdef HAVE_NTP_SIGND
! 323: static unsigned char zero_key[16];
! 324: #endif /* HAVE_NTP_SIGND */
! 325:
! 326: /*
! 327: * Monitor the packet and get restrictions. Note that the packet
! 328: * length for control and private mode packets must be checked
! 329: * by the service routines. Some restrictions have to be handled
! 330: * later in order to generate a kiss-o'-death packet.
! 331: */
! 332: /*
! 333: * Bogus port check is before anything, since it probably
! 334: * reveals a clogging attack.
! 335: */
! 336: sys_received++;
! 337: if (SRCPORT(&rbufp->recv_srcadr) < NTP_PORT) {
! 338: sys_badlength++;
! 339: return; /* bogus port */
! 340: }
! 341: restrict_mask = restrictions(&rbufp->recv_srcadr);
! 342: #ifdef DEBUG
! 343: if (debug > 1)
! 344: printf("receive: at %ld %s<-%s flags %x restrict %03x\n",
! 345: current_time, stoa(&rbufp->dstadr->sin),
! 346: stoa(&rbufp->recv_srcadr),
! 347: rbufp->dstadr->flags, restrict_mask);
! 348: #endif
! 349: pkt = &rbufp->recv_pkt;
! 350: hisversion = PKT_VERSION(pkt->li_vn_mode);
! 351: hisleap = PKT_LEAP(pkt->li_vn_mode);
! 352: hismode = (int)PKT_MODE(pkt->li_vn_mode);
! 353: hisstratum = PKT_TO_STRATUM(pkt->stratum);
! 354: if (restrict_mask & RES_IGNORE) {
! 355: sys_restricted++;
! 356: return; /* ignore everything */
! 357: }
! 358: if (hismode == MODE_PRIVATE) {
! 359: if (restrict_mask & RES_NOQUERY) {
! 360: sys_restricted++;
! 361: return; /* no query private */
! 362: }
! 363: process_private(rbufp, ((restrict_mask &
! 364: RES_NOMODIFY) == 0));
! 365: return;
! 366: }
! 367: if (hismode == MODE_CONTROL) {
! 368: if (restrict_mask & RES_NOQUERY) {
! 369: sys_restricted++;
! 370: return; /* no query control */
! 371: }
! 372: process_control(rbufp, restrict_mask);
! 373: return;
! 374: }
! 375: if (restrict_mask & RES_DONTSERVE) {
! 376: sys_restricted++;
! 377: return; /* no time serve */
! 378: }
! 379:
! 380: /*
! 381: * This is for testing. If restricted drop ten percent of
! 382: * surviving packets.
! 383: */
! 384: if (restrict_mask & RES_TIMEOUT) {
! 385: if ((double)ntp_random() / 0x7fffffff < .1) {
! 386: sys_restricted++;
! 387: return; /* no flakeway */
! 388: }
! 389: }
! 390:
! 391: /*
! 392: * Version check must be after the query packets, since they
! 393: * intentionally use an early version.
! 394: */
! 395: if (hisversion == NTP_VERSION) {
! 396: sys_newversion++; /* new version */
! 397: } else if (!(restrict_mask & RES_VERSION) && hisversion >=
! 398: NTP_OLDVERSION) {
! 399: sys_oldversion++; /* previous version */
! 400: } else {
! 401: sys_badlength++;
! 402: return; /* old version */
! 403: }
! 404:
! 405: /*
! 406: * Figure out his mode and validate the packet. This has some
! 407: * legacy raunch that probably should be removed. In very early
! 408: * NTP versions mode 0 was equivalent to what later versions
! 409: * would interpret as client mode.
! 410: */
! 411: if (hismode == MODE_UNSPEC) {
! 412: if (hisversion == NTP_OLDVERSION) {
! 413: hismode = MODE_CLIENT;
! 414: } else {
! 415: sys_badlength++;
! 416: return; /* invalid mode */
! 417: }
! 418: }
! 419:
! 420: /*
! 421: * Parse the extension field if present. We figure out whether
! 422: * an extension field is present by measuring the MAC size. If
! 423: * the number of words following the packet header is 0, no MAC
! 424: * is present and the packet is not authenticated. If 1, the
! 425: * packet is a crypto-NAK; if 3, the packet is authenticated
! 426: * with DES; if 5, the packet is authenticated with MD5; if 6,
! 427: * the packet is authenticated with SHA. If 2 or * 4, the packet
! 428: * is a runt and discarded forthwith. If greater than 6, an
! 429: * extension field is present, so we subtract the length of the
! 430: * field and go around again.
! 431: */
! 432: authlen = LEN_PKT_NOMAC;
! 433: has_mac = rbufp->recv_length - authlen;
! 434: while (has_mac != 0) {
! 435: u_int32 len;
! 436:
! 437: if (has_mac % 4 != 0 || has_mac < MIN_MAC_LEN) {
! 438: sys_badlength++;
! 439: return; /* bad length */
! 440: }
! 441: if (has_mac <= MAX_MAC_LEN) {
! 442: skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
! 443: break;
! 444:
! 445: } else {
! 446: opcode = ntohl(((u_int32 *)pkt)[authlen / 4]);
! 447: len = opcode & 0xffff;
! 448: if (len % 4 != 0 || len < 4 || len + authlen >
! 449: rbufp->recv_length) {
! 450: sys_badlength++;
! 451: return; /* bad length */
! 452: }
! 453: authlen += len;
! 454: has_mac -= len;
! 455: }
! 456: }
! 457:
! 458: /*
! 459: * If authentication required, a MAC must be present.
! 460: */
! 461: if (restrict_mask & RES_DONTTRUST && has_mac == 0) {
! 462: sys_restricted++;
! 463: return; /* access denied */
! 464: }
! 465:
! 466: /*
! 467: * Update the MRU list and finger the cloggers. It can be a
! 468: * little expensive, so turn it off for production use.
! 469: */
! 470: restrict_mask = ntp_monitor(rbufp, restrict_mask);
! 471: if (restrict_mask & RES_LIMITED) {
! 472: sys_limitrejected++;
! 473: if (!(restrict_mask & RES_KOD) || MODE_BROADCAST ==
! 474: hismode || MODE_SERVER == hismode)
! 475: return; /* rate exceeded */
! 476:
! 477: if (hismode == MODE_CLIENT)
! 478: fast_xmit(rbufp, MODE_SERVER, skeyid,
! 479: restrict_mask);
! 480: else
! 481: fast_xmit(rbufp, MODE_ACTIVE, skeyid,
! 482: restrict_mask);
! 483: return; /* rate exceeded */
! 484: }
! 485: restrict_mask &= ~RES_KOD;
! 486:
! 487: /*
! 488: * We have tossed out as many buggy packets as possible early in
! 489: * the game to reduce the exposure to a clogging attack. now we
! 490: * have to burn some cycles to find the association and
! 491: * authenticate the packet if required. Note that we burn only
! 492: * MD5 cycles, again to reduce exposure. There may be no
! 493: * matching association and that's okay.
! 494: *
! 495: * More on the autokey mambo. Normally the local interface is
! 496: * found when the association was mobilized with respect to a
! 497: * designated remote address. We assume packets arriving from
! 498: * the remote address arrive via this interface and the local
! 499: * address used to construct the autokey is the unicast address
! 500: * of the interface. However, if the sender is a broadcaster,
! 501: * the interface broadcast address is used instead.
! 502: * Notwithstanding this technobabble, if the sender is a
! 503: * multicaster, the broadcast address is null, so we use the
! 504: * unicast address anyway. Don't ask.
! 505: */
! 506: peer = findpeer(rbufp, hismode, &retcode);
! 507: dstadr_sin = &rbufp->dstadr->sin;
! 508: NTOHL_FP(&pkt->org, &p_org);
! 509: NTOHL_FP(&pkt->rec, &p_rec);
! 510: NTOHL_FP(&pkt->xmt, &p_xmt);
! 511:
! 512: /*
! 513: * Authentication is conditioned by three switches:
! 514: *
! 515: * NOPEER (RES_NOPEER) do not mobilize an association unless
! 516: * authenticated
! 517: * NOTRUST (RES_DONTTRUST) do not allow access unless
! 518: * authenticated (implies NOPEER)
! 519: * enable (sys_authenticate) master NOPEER switch, by default
! 520: * on
! 521: *
! 522: * The NOPEER and NOTRUST can be specified on a per-client basis
! 523: * using the restrict command. The enable switch if on implies
! 524: * NOPEER for all clients. There are four outcomes:
! 525: *
! 526: * NONE The packet has no MAC.
! 527: * OK the packet has a MAC and authentication succeeds
! 528: * ERROR the packet has a MAC and authentication fails
! 529: * CRYPTO crypto-NAK. The MAC has four octets only.
! 530: *
! 531: * Note: The AUTH(x, y) macro is used to filter outcomes. If x
! 532: * is zero, acceptable outcomes of y are NONE and OK. If x is
! 533: * one, the only acceptable outcome of y is OK.
! 534: */
! 535:
! 536: if (has_mac == 0) {
! 537: restrict_mask &= ~RES_MSSNTP;
! 538: is_authentic = AUTH_NONE; /* not required */
! 539: #ifdef DEBUG
! 540: if (debug)
! 541: printf(
! 542: "receive: at %ld %s<-%s mode %d len %d\n",
! 543: current_time, stoa(dstadr_sin),
! 544: stoa(&rbufp->recv_srcadr), hismode,
! 545: authlen);
! 546: #endif
! 547: } else if (has_mac == 4) {
! 548: restrict_mask &= ~RES_MSSNTP;
! 549: is_authentic = AUTH_CRYPTO; /* crypto-NAK */
! 550: #ifdef DEBUG
! 551: if (debug)
! 552: printf(
! 553: "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
! 554: current_time, stoa(dstadr_sin),
! 555: stoa(&rbufp->recv_srcadr), hismode, skeyid,
! 556: authlen + has_mac, is_authentic);
! 557: #endif
! 558:
! 559: #ifdef HAVE_NTP_SIGND
! 560: /*
! 561: * If the signature is 20 bytes long, the last 16 of
! 562: * which are zero, then this is a Microsoft client
! 563: * wanting AD-style authentication of the server's
! 564: * reply.
! 565: *
! 566: * This is described in Microsoft's WSPP docs, in MS-SNTP:
! 567: * http://msdn.microsoft.com/en-us/library/cc212930.aspx
! 568: */
! 569: } else if (has_mac == MAX_MD5_LEN && (restrict_mask & RES_MSSNTP) &&
! 570: (retcode == AM_FXMIT || retcode == AM_NEWPASS) &&
! 571: (memcmp(zero_key, (char *)pkt + authlen + 4, MAX_MD5_LEN - 4) ==
! 572: 0)) {
! 573: is_authentic = AUTH_NONE;
! 574: #endif /* HAVE_NTP_SIGND */
! 575:
! 576: } else {
! 577: restrict_mask &= ~RES_MSSNTP;
! 578: #ifdef OPENSSL
! 579: /*
! 580: * For autokey modes, generate the session key
! 581: * and install in the key cache. Use the socket
! 582: * broadcast or unicast address as appropriate.
! 583: */
! 584: if (crypto_flags && skeyid > NTP_MAXKEY) {
! 585:
! 586: /*
! 587: * More on the autokey dance (AKD). A cookie is
! 588: * constructed from public and private values.
! 589: * For broadcast packets, the cookie is public
! 590: * (zero). For packets that match no
! 591: * association, the cookie is hashed from the
! 592: * addresses and private value. For server
! 593: * packets, the cookie was previously obtained
! 594: * from the server. For symmetric modes, the
! 595: * cookie was previously constructed using an
! 596: * agreement protocol; however, should PKI be
! 597: * unavailable, we construct a fake agreement as
! 598: * the EXOR of the peer and host cookies.
! 599: *
! 600: * hismode ephemeral persistent
! 601: * =======================================
! 602: * active 0 cookie#
! 603: * passive 0% cookie#
! 604: * client sys cookie 0%
! 605: * server 0% sys cookie
! 606: * broadcast 0 0
! 607: *
! 608: * # if unsync, 0
! 609: * % can't happen
! 610: */
! 611: if (has_mac < MAX_MD5_LEN) {
! 612: sys_badauth++;
! 613: return;
! 614: }
! 615: if (hismode == MODE_BROADCAST) {
! 616:
! 617: /*
! 618: * For broadcaster, use the interface
! 619: * broadcast address when available;
! 620: * otherwise, use the unicast address
! 621: * found when the association was
! 622: * mobilized. However, if this is from
! 623: * the wildcard interface, game over.
! 624: */
! 625: if (crypto_flags && rbufp->dstadr ==
! 626: any_interface) {
! 627: sys_restricted++;
! 628: return; /* no wildcard */
! 629: }
! 630: pkeyid = 0;
! 631: if (!SOCK_UNSPEC(&rbufp->dstadr->bcast))
! 632: dstadr_sin =
! 633: &rbufp->dstadr->bcast;
! 634: } else if (peer == NULL) {
! 635: pkeyid = session_key(
! 636: &rbufp->recv_srcadr, dstadr_sin, 0,
! 637: sys_private, 0);
! 638: } else {
! 639: pkeyid = peer->pcookie;
! 640: }
! 641:
! 642: /*
! 643: * The session key includes both the public
! 644: * values and cookie. In case of an extension
! 645: * field, the cookie used for authentication
! 646: * purposes is zero. Note the hash is saved for
! 647: * use later in the autokey mambo.
! 648: */
! 649: if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
! 650: session_key(&rbufp->recv_srcadr,
! 651: dstadr_sin, skeyid, 0, 2);
! 652: tkeyid = session_key(
! 653: &rbufp->recv_srcadr, dstadr_sin,
! 654: skeyid, pkeyid, 0);
! 655: } else {
! 656: tkeyid = session_key(
! 657: &rbufp->recv_srcadr, dstadr_sin,
! 658: skeyid, pkeyid, 2);
! 659: }
! 660:
! 661: }
! 662: #endif /* OPENSSL */
! 663:
! 664: /*
! 665: * Compute the cryptosum. Note a clogging attack may
! 666: * succeed in bloating the key cache. If an autokey,
! 667: * purge it immediately, since we won't be needing it
! 668: * again. If the packet is authentic, it can mobilize an
! 669: * association. Note that there is no key zero.
! 670: */
! 671: if (!authdecrypt(skeyid, (u_int32 *)pkt, authlen,
! 672: has_mac))
! 673: is_authentic = AUTH_ERROR;
! 674: else
! 675: is_authentic = AUTH_OK;
! 676: #ifdef OPENSSL
! 677: if (crypto_flags && skeyid > NTP_MAXKEY)
! 678: authtrust(skeyid, 0);
! 679: #endif /* OPENSSL */
! 680: #ifdef DEBUG
! 681: if (debug)
! 682: printf(
! 683: "receive: at %ld %s<-%s mode %d keyid %08x len %d auth %d\n",
! 684: current_time, stoa(dstadr_sin),
! 685: stoa(&rbufp->recv_srcadr), hismode, skeyid,
! 686: authlen + has_mac, is_authentic);
! 687: #endif
! 688: }
! 689:
! 690: /*
! 691: * The association matching rules are implemented by a set of
! 692: * routines and an association table. A packet matching an
! 693: * association is processed by the peer process for that
! 694: * association. If there are no errors, an ephemeral association
! 695: * is mobilized: a broadcast packet mobilizes a broadcast client
! 696: * aassociation; a manycast server packet mobilizes a manycast
! 697: * client association; a symmetric active packet mobilizes a
! 698: * symmetric passive association.
! 699: */
! 700: switch (retcode) {
! 701:
! 702: /*
! 703: * This is a client mode packet not matching any association. If
! 704: * an ordinary client, simply toss a server mode packet back
! 705: * over the fence. If a manycast client, we have to work a
! 706: * little harder.
! 707: */
! 708: case AM_FXMIT:
! 709:
! 710: /*
! 711: * If authentication OK, send a server reply; otherwise,
! 712: * send a crypto-NAK.
! 713: */
! 714: if (!(rbufp->dstadr->flags & INT_MCASTOPEN)) {
! 715: if (AUTH(restrict_mask & RES_DONTTRUST,
! 716: is_authentic)) {
! 717: fast_xmit(rbufp, MODE_SERVER, skeyid,
! 718: restrict_mask);
! 719: } else if (is_authentic == AUTH_ERROR) {
! 720: fast_xmit(rbufp, MODE_SERVER, 0,
! 721: restrict_mask);
! 722: sys_badauth++;
! 723: } else {
! 724: sys_restricted++;
! 725: }
! 726: return; /* hooray */
! 727: }
! 728:
! 729: /*
! 730: * This must be manycast. Do not respond if not
! 731: * configured as a manycast server.
! 732: */
! 733: if (!sys_manycastserver) {
! 734: sys_restricted++;
! 735: return; /* not enabled */
! 736: }
! 737:
! 738: /*
! 739: * Do not respond if we are not synchronized or our
! 740: * stratum is greater than the manycaster or the
! 741: * manycaster has already synchronized to us.
! 742: */
! 743: if (sys_leap == LEAP_NOTINSYNC || sys_stratum >=
! 744: hisstratum || (!sys_cohort && sys_stratum ==
! 745: hisstratum + 1) || rbufp->dstadr->addr_refid ==
! 746: pkt->refid) {
! 747: sys_declined++;
! 748: return; /* no help */
! 749: }
! 750:
! 751: /*
! 752: * Respond only if authentication succeeds. Don't do a
! 753: * crypto-NAK, as that would not be useful.
! 754: */
! 755: if (AUTH(restrict_mask & RES_DONTTRUST, is_authentic))
! 756: fast_xmit(rbufp, MODE_SERVER, skeyid,
! 757: restrict_mask);
! 758: return; /* hooray */
! 759:
! 760: /*
! 761: * This is a server mode packet returned in response to a client
! 762: * mode packet sent to a multicast group address. The origin
! 763: * timestamp is a good nonce to reliably associate the reply
! 764: * with what was sent. If there is no match, that's curious and
! 765: * could be an intruder attempting to clog, so we just ignore
! 766: * it.
! 767: *
! 768: * If the packet is authentic and the manycast association is
! 769: * found, we mobilize a client association and copy pertinent
! 770: * variables from the manycast association to the new client
! 771: * association. If not, just ignore the packet.
! 772: *
! 773: * There is an implosion hazard at the manycast client, since
! 774: * the manycast servers send the server packet immediately. If
! 775: * the guy is already here, don't fire up a duplicate.
! 776: */
! 777: case AM_MANYCAST:
! 778: if (!AUTH(sys_authenticate | (restrict_mask &
! 779: (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
! 780: sys_restricted++;
! 781: return; /* access denied */
! 782: }
! 783:
! 784: /*
! 785: * Do not respond if unsynchronized or stratum is below
! 786: * the floor or at or above the ceiling.
! 787: */
! 788: if (hisleap == LEAP_NOTINSYNC || hisstratum <
! 789: sys_floor || hisstratum >= sys_ceiling) {
! 790: sys_declined++;
! 791: return; /* no help */
! 792: }
! 793: if ((peer2 = findmanycastpeer(rbufp)) == NULL) {
! 794: sys_restricted++;
! 795: return; /* not enabled */
! 796: }
! 797: if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
! 798: MODE_CLIENT, hisversion, NTP_MINDPOLL, NTP_MAXDPOLL,
! 799: FLAG_PREEMPT, MDF_UCAST | MDF_ACLNT, 0, skeyid)) ==
! 800: NULL) {
! 801: sys_declined++;
! 802: return; /* ignore duplicate */
! 803: }
! 804:
! 805: /*
! 806: * We don't need these, but it warms the billboards.
! 807: */
! 808: if (peer2->flags & FLAG_IBURST)
! 809: peer->flags |= FLAG_IBURST;
! 810: peer->minpoll = peer2->minpoll;
! 811: peer->maxpoll = peer2->maxpoll;
! 812: break;
! 813:
! 814: /*
! 815: * This is the first packet received from a broadcast server. If
! 816: * the packet is authentic and we are enabled as broadcast
! 817: * client, mobilize a broadcast client association. We don't
! 818: * kiss any frogs here.
! 819: */
! 820: case AM_NEWBCL:
! 821: if (sys_bclient == 0) {
! 822: sys_restricted++;
! 823: return; /* not enabled */
! 824: }
! 825: if (!AUTH(sys_authenticate | (restrict_mask &
! 826: (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
! 827: sys_restricted++;
! 828: return; /* access denied */
! 829: }
! 830:
! 831: /*
! 832: * Do not respond if unsynchronized or stratum is below
! 833: * the floor or at or above the ceiling.
! 834: */
! 835: if (hisleap == LEAP_NOTINSYNC || hisstratum <
! 836: sys_floor || hisstratum >= sys_ceiling) {
! 837: sys_declined++;
! 838: return; /* no help */
! 839: }
! 840:
! 841: #ifdef OPENSSL
! 842: /*
! 843: * Do not respond if Autokey and the opcode is not a
! 844: * CRYPTO_ASSOC response with associationn ID.
! 845: */
! 846: if (crypto_flags && skeyid > NTP_MAXKEY && (opcode &
! 847: 0xffff0000) != (CRYPTO_ASSOC | CRYPTO_RESP)) {
! 848: sys_declined++;
! 849: return; /* protocol error */
! 850: }
! 851: #endif /* OPENSSL */
! 852:
! 853: /*
! 854: * Broadcasts received via a multicast address may
! 855: * arrive after a unicast volley has begun
! 856: * with the same remote address. newpeer() will not
! 857: * find duplicate associations on other local endpoints
! 858: * if a non-NULL endpoint is supplied. multicastclient
! 859: * ephemeral associations are unique across all local
! 860: * endpoints.
! 861: */
! 862: if (!(INT_MCASTOPEN & rbufp->dstadr->flags))
! 863: match_ep = rbufp->dstadr;
! 864: else
! 865: match_ep = NULL;
! 866:
! 867: /*
! 868: * Determine whether to execute the initial volley.
! 869: */
! 870: if (sys_bdelay != 0) {
! 871: #ifdef OPENSSL
! 872: /*
! 873: * If a two-way exchange is not possible,
! 874: * neither is Autokey.
! 875: */
! 876: if (crypto_flags && skeyid > NTP_MAXKEY) {
! 877: sys_restricted++;
! 878: return; /* no autokey */
! 879: }
! 880: #endif /* OPENSSL */
! 881:
! 882: /*
! 883: * Do not execute the volley. Start out in
! 884: * broadcast client mode.
! 885: */
! 886: peer = newpeer(&rbufp->recv_srcadr, match_ep,
! 887: MODE_BCLIENT, hisversion, pkt->ppoll,
! 888: pkt->ppoll, FLAG_PREEMPT, MDF_BCLNT, 0,
! 889: skeyid);
! 890: if (NULL == peer) {
! 891: sys_restricted++;
! 892: return; /* ignore duplicate */
! 893:
! 894: } else {
! 895: peer->delay = sys_bdelay;
! 896: peer->bias = -sys_bdelay / 2.;
! 897: }
! 898: break;
! 899: }
! 900:
! 901: /*
! 902: * Execute the initial volley in order to calibrate the
! 903: * propagation delay and run the Autokey protocol.
! 904: *
! 905: * Note that the minpoll is taken from the broadcast
! 906: * packet, normally 6 (64 s) and that the poll interval
! 907: * is fixed at this value.
! 908: */
! 909: peer = newpeer(&rbufp->recv_srcadr, match_ep,
! 910: MODE_CLIENT, hisversion, pkt->ppoll, pkt->ppoll,
! 911: FLAG_BC_VOL | FLAG_IBURST | FLAG_PREEMPT, MDF_BCLNT,
! 912: 0, skeyid);
! 913: if (NULL == peer) {
! 914: sys_restricted++;
! 915: return; /* ignore duplicate */
! 916: }
! 917: #ifdef OPENSSL
! 918: if (skeyid > NTP_MAXKEY)
! 919: crypto_recv(peer, rbufp);
! 920: #endif /* OPENSSL */
! 921:
! 922: return; /* hooray */
! 923:
! 924: /*
! 925: * This is the first packet received from a symmetric active
! 926: * peer. If the packet is authentic and the first he sent,
! 927: * mobilize a passive association. If not, kiss the frog.
! 928: */
! 929: case AM_NEWPASS:
! 930: if (!AUTH(sys_authenticate | (restrict_mask &
! 931: (RES_NOPEER | RES_DONTTRUST)), is_authentic)) {
! 932:
! 933: /*
! 934: * If authenticated but cannot mobilize an
! 935: * association, send a symmetric passive
! 936: * response without mobilizing an association.
! 937: * This is for drat broken Windows clients. See
! 938: * Microsoft KB 875424 for preferred workaround.
! 939: */
! 940: if (AUTH(restrict_mask & RES_DONTTRUST,
! 941: is_authentic)) {
! 942: fast_xmit(rbufp, MODE_PASSIVE, skeyid,
! 943: restrict_mask);
! 944: return; /* hooray */
! 945: }
! 946: if (is_authentic == AUTH_ERROR) {
! 947: fast_xmit(rbufp, MODE_ACTIVE, 0,
! 948: restrict_mask);
! 949: sys_restricted++;
! 950: }
! 951: }
! 952:
! 953: /*
! 954: * Do not respond if synchronized and stratum is either
! 955: * below the floor or at or above the ceiling. Note,
! 956: * this allows an unsynchronized peer to synchronize to
! 957: * us. It would be very strange if he did and then was
! 958: * nipped, but that could only happen if we were
! 959: * operating at the top end of the range.
! 960: */
! 961: if (hisleap != LEAP_NOTINSYNC && (hisstratum <
! 962: sys_floor || hisstratum >= sys_ceiling)) {
! 963: sys_declined++;
! 964: return; /* no help */
! 965: }
! 966:
! 967: /*
! 968: * The message is correctly authenticated and
! 969: * allowed. Mobiliae a symmetric passive association.
! 970: */
! 971: if ((peer = newpeer(&rbufp->recv_srcadr,
! 972: rbufp->dstadr, MODE_PASSIVE, hisversion, pkt->ppoll,
! 973: NTP_MAXDPOLL, FLAG_PREEMPT, MDF_UCAST, 0,
! 974: skeyid)) == NULL) {
! 975: sys_declined++;
! 976: return; /* ignore duplicate */
! 977: }
! 978: break;
! 979:
! 980:
! 981: /*
! 982: * Process regular packet. Nothing special.
! 983: */
! 984: case AM_PROCPKT:
! 985: break;
! 986:
! 987: /*
! 988: * A passive packet matches a passive association. This is
! 989: * usually the result of reconfiguring a client on the fly. As
! 990: * this association might be legitamate and this packet an
! 991: * attempt to deny service, just ignore it.
! 992: */
! 993: case AM_ERR:
! 994: sys_declined++;
! 995: return;
! 996:
! 997: /*
! 998: * For everything else there is the bit bucket.
! 999: */
! 1000: default:
! 1001: sys_declined++;
! 1002: return;
! 1003: }
! 1004:
! 1005: #ifdef OPENSSL
! 1006: /*
! 1007: * If the association is configured for Autokey, the packet must
! 1008: * have a public key ID; if not, the packet must have a
! 1009: * symmetric key ID.
! 1010: */
! 1011: if (is_authentic != AUTH_CRYPTO && (((peer->flags &
! 1012: FLAG_SKEY) && skeyid <= NTP_MAXKEY) || (!(peer->flags &
! 1013: FLAG_SKEY) && skeyid > NTP_MAXKEY))) {
! 1014: sys_badauth++;
! 1015: return;
! 1016: }
! 1017: #endif /* OPENSSL */
! 1018: peer->received++;
! 1019: peer->flash &= ~PKT_TEST_MASK;
! 1020: if (peer->flags & FLAG_XBOGUS) {
! 1021: peer->flags &= ~FLAG_XBOGUS;
! 1022: peer->flash |= TEST3;
! 1023: }
! 1024:
! 1025: /*
! 1026: * Next comes a rigorous schedule of timestamp checking. If the
! 1027: * transmit timestamp is zero, the server has not initialized in
! 1028: * interleaved modes or is horribly broken.
! 1029: */
! 1030: if (L_ISZERO(&p_xmt)) {
! 1031: peer->flash |= TEST3; /* unsynch */
! 1032:
! 1033: /*
! 1034: * If the transmit timestamp duplicates a previous one, the
! 1035: * packet is a replay. This prevents the bad guys from replaying
! 1036: * the most recent packet, authenticated or not.
! 1037: */
! 1038: } else if (L_ISEQU(&peer->xmt, &p_xmt)) {
! 1039: peer->flash |= TEST1; /* duplicate */
! 1040: peer->oldpkt++;
! 1041: return;
! 1042:
! 1043: /*
! 1044: * If this is a broadcast mode packet, skip further checking. If
! 1045: * an intial volley, bail out now and let the client do its
! 1046: * stuff. If the origin timestamp is nonzero, this is an
! 1047: * interleaved broadcast. so restart the protocol.
! 1048: */
! 1049: } else if (hismode == MODE_BROADCAST) {
! 1050: if (!L_ISZERO(&p_org) && !(peer->flags & FLAG_XB)) {
! 1051: peer->flags |= FLAG_XB;
! 1052: peer->aorg = p_xmt;
! 1053: peer->borg = rbufp->recv_time;
! 1054: report_event(PEVNT_XLEAVE, peer, NULL);
! 1055: return;
! 1056: }
! 1057:
! 1058: /*
! 1059: * Check for bogus packet in basic mode. If found, switch to
! 1060: * interleaved mode and resynchronize, but only after confirming
! 1061: * the packet is not bogus in symmetric interleaved mode.
! 1062: */
! 1063: } else if (peer->flip == 0) {
! 1064: if (!L_ISEQU(&p_org, &peer->aorg)) {
! 1065: peer->bogusorg++;
! 1066: peer->flash |= TEST2; /* bogus */
! 1067: if (!L_ISZERO(&peer->dst) && L_ISEQU(&p_org,
! 1068: &peer->dst)) {
! 1069: peer->flip = 1;
! 1070: report_event(PEVNT_XLEAVE, peer, NULL);
! 1071: }
! 1072: } else {
! 1073: L_CLR(&peer->aorg);
! 1074: }
! 1075:
! 1076: /*
! 1077: * Check for valid nonzero timestamp fields.
! 1078: */
! 1079: } else if (L_ISZERO(&p_org) || L_ISZERO(&p_rec) ||
! 1080: L_ISZERO(&peer->dst)) {
! 1081: peer->flash |= TEST3; /* unsynch */
! 1082:
! 1083: /*
! 1084: * Check for bogus packet in interleaved symmetric mode. This
! 1085: * can happen if a packet is lost, duplicat or crossed. If
! 1086: * found, flip and resynchronize.
! 1087: */
! 1088: } else if (!L_ISZERO(&peer->dst) && !L_ISEQU(&p_org,
! 1089: &peer->dst)) {
! 1090: peer->bogusorg++;
! 1091: peer->flags |= FLAG_XBOGUS;
! 1092: peer->flash |= TEST2; /* bogus */
! 1093: }
! 1094:
! 1095: /*
! 1096: * Update the state variables.
! 1097: */
! 1098: if (peer->flip == 0) {
! 1099: if (hismode != MODE_BROADCAST)
! 1100: peer->rec = p_xmt;
! 1101: peer->dst = rbufp->recv_time;
! 1102: }
! 1103: peer->xmt = p_xmt;
! 1104:
! 1105: /*
! 1106: * If this is a crypto_NAK, the server cannot authenticate a
! 1107: * client packet. The server might have just changed keys. Clear
! 1108: * the association and restart the protocol.
! 1109: */
! 1110: if (is_authentic == AUTH_CRYPTO) {
! 1111: report_event(PEVNT_AUTH, peer, "crypto_NAK");
! 1112: peer->flash |= TEST5; /* bad auth */
! 1113: peer->badauth++;
! 1114: if (peer->flags & FLAG_PREEMPT) {
! 1115: unpeer(peer);
! 1116: return;
! 1117: }
! 1118: #ifdef OPENSSL
! 1119: if (peer->crypto)
! 1120: peer_clear(peer, "AUTH");
! 1121: #endif /* OPENSSL */
! 1122: return;
! 1123:
! 1124: /*
! 1125: * If the digest fails, the client cannot authenticate a server
! 1126: * reply to a client packet previously sent. The loopback check
! 1127: * is designed to avoid a bait-and-switch attack, which was
! 1128: * possible in past versions. If symmetric modes, return a
! 1129: * crypto-NAK. The peer should restart the protocol.
! 1130: */
! 1131: } else if (!AUTH(has_mac || (restrict_mask & RES_DONTTRUST),
! 1132: is_authentic)) {
! 1133: report_event(PEVNT_AUTH, peer, "digest");
! 1134: peer->flash |= TEST5; /* bad auth */
! 1135: peer->badauth++;
! 1136: if (hismode == MODE_ACTIVE || hismode == MODE_PASSIVE)
! 1137: fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
! 1138: if (peer->flags & FLAG_PREEMPT) {
! 1139: unpeer(peer);
! 1140: return;
! 1141: }
! 1142: #ifdef OPENSSL
! 1143: if (peer->crypto)
! 1144: peer_clear(peer, "AUTH");
! 1145: #endif /* OPENSSL */
! 1146: return;
! 1147: }
! 1148:
! 1149: /*
! 1150: * Set the peer ppoll to the maximum of the packet ppoll and the
! 1151: * peer minpoll. If a kiss-o'-death, set the peer minpoll to
! 1152: * this maximumn and advance the headway to give the sender some
! 1153: * headroom. Very intricate.
! 1154: */
! 1155: peer->ppoll = max(peer->minpoll, pkt->ppoll);
! 1156: if (hismode == MODE_SERVER && hisleap == LEAP_NOTINSYNC &&
! 1157: hisstratum == STRATUM_UNSPEC && memcmp(&pkt->refid,
! 1158: "RATE", 4) == 0) {
! 1159: peer->selbroken++;
! 1160: report_event(PEVNT_RATE, peer, NULL);
! 1161: if (pkt->ppoll > peer->minpoll)
! 1162: peer->minpoll = peer->ppoll;
! 1163: peer->burst = peer->retry = 0;
! 1164: peer->throttle = (NTP_SHIFT + 1) * (1 << peer->minpoll);
! 1165: poll_update(peer, pkt->ppoll);
! 1166: return; /* kiss-o'-death */
! 1167: }
! 1168:
! 1169: /*
! 1170: * That was hard and I am sweaty, but the packet is squeaky
! 1171: * clean. Get on with real work.
! 1172: */
! 1173: peer->timereceived = current_time;
! 1174: if (is_authentic == AUTH_OK)
! 1175: peer->flags |= FLAG_AUTHENTIC;
! 1176: else
! 1177: peer->flags &= ~FLAG_AUTHENTIC;
! 1178:
! 1179: #ifdef OPENSSL
! 1180: /*
! 1181: * More autokey dance. The rules of the cha-cha are as follows:
! 1182: *
! 1183: * 1. If there is no key or the key is not auto, do nothing.
! 1184: *
! 1185: * 2. If this packet is in response to the one just previously
! 1186: * sent or from a broadcast server, do the extension fields.
! 1187: * Otherwise, assume bogosity and bail out.
! 1188: *
! 1189: * 3. If an extension field contains a verified signature, it is
! 1190: * self-authenticated and we sit the dance.
! 1191: *
! 1192: * 4. If this is a server reply, check only to see that the
! 1193: * transmitted key ID matches the received key ID.
! 1194: *
! 1195: * 5. Check to see that one or more hashes of the current key ID
! 1196: * matches the previous key ID or ultimate original key ID
! 1197: * obtained from the broadcaster or symmetric peer. If no
! 1198: * match, sit the dance and call for new autokey values.
! 1199: *
! 1200: * In case of crypto error, fire the orchestra, stop dancing and
! 1201: * restart the protocol.
! 1202: */
! 1203: if (peer->flags & FLAG_SKEY) {
! 1204: /*
! 1205: * Decrement remaining audokey hashes. This isn't
! 1206: * perfect if a packet is lost, but results in no harm.
! 1207: */
! 1208: ap = (struct autokey *)peer->recval.ptr;
! 1209: if (ap != NULL) {
! 1210: if (ap->seq > 0)
! 1211: ap->seq--;
! 1212: }
! 1213: peer->flash |= TEST8;
! 1214: rval = crypto_recv(peer, rbufp);
! 1215: if (rval == XEVNT_OK) {
! 1216: peer->unreach = 0;
! 1217: } else {
! 1218: if (rval == XEVNT_ERR) {
! 1219: report_event(PEVNT_RESTART, peer,
! 1220: "crypto error");
! 1221: peer_clear(peer, "CRYP");
! 1222: peer->flash |= TEST9; /* bad crypt */
! 1223: if (peer->flags & FLAG_PREEMPT)
! 1224: unpeer(peer);
! 1225: }
! 1226: return;
! 1227: }
! 1228:
! 1229: /*
! 1230: * If server mode, verify the receive key ID matches
! 1231: * the transmit key ID.
! 1232: */
! 1233: if (hismode == MODE_SERVER) {
! 1234: if (skeyid == peer->keyid)
! 1235: peer->flash &= ~TEST8;
! 1236:
! 1237: /*
! 1238: * If an extension field is present, verify only that it
! 1239: * has been correctly signed. We don't need a sequence
! 1240: * check here, but the sequence continues.
! 1241: */
! 1242: } else if (!(peer->flash & TEST8)) {
! 1243: peer->pkeyid = skeyid;
! 1244:
! 1245: /*
! 1246: * Now the fun part. Here, skeyid is the current ID in
! 1247: * the packet, pkeyid is the ID in the last packet and
! 1248: * tkeyid is the hash of skeyid. If the autokey values
! 1249: * have not been received, this is an automatic error.
! 1250: * If so, check that the tkeyid matches pkeyid. If not,
! 1251: * hash tkeyid and try again. If the number of hashes
! 1252: * exceeds the number remaining in the sequence, declare
! 1253: * a successful failure and refresh the autokey values.
! 1254: */
! 1255: } else if (ap != NULL) {
! 1256: int i;
! 1257:
! 1258: for (i = 0; ; i++) {
! 1259: if (tkeyid == peer->pkeyid ||
! 1260: tkeyid == ap->key) {
! 1261: peer->flash &= ~TEST8;
! 1262: peer->pkeyid = skeyid;
! 1263: ap->seq -= i;
! 1264: break;
! 1265: }
! 1266: if (i > ap->seq) {
! 1267: peer->crypto &=
! 1268: ~CRYPTO_FLAG_AUTO;
! 1269: break;
! 1270: }
! 1271: tkeyid = session_key(
! 1272: &rbufp->recv_srcadr, dstadr_sin,
! 1273: tkeyid, pkeyid, 0);
! 1274: }
! 1275: if (peer->flash & TEST8)
! 1276: report_event(PEVNT_AUTH, peer, "keylist");
! 1277: }
! 1278: if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 9 */
! 1279: peer->flash |= TEST8; /* bad autokey */
! 1280:
! 1281: /*
! 1282: * The maximum lifetime of the protocol is about one
! 1283: * week before restarting the Autokey protocol to
! 1284: * refreshed certificates and leapseconds values.
! 1285: */
! 1286: if (current_time > peer->refresh) {
! 1287: report_event(PEVNT_RESTART, peer,
! 1288: "crypto refresh");
! 1289: peer_clear(peer, "TIME");
! 1290: return;
! 1291: }
! 1292: }
! 1293: #endif /* OPENSSL */
! 1294:
! 1295: /*
! 1296: * The dance is complete and the flash bits have been lit. Toss
! 1297: * the packet over the fence for processing, which may light up
! 1298: * more flashers.
! 1299: */
! 1300: process_packet(peer, pkt, rbufp->recv_length);
! 1301:
! 1302: /*
! 1303: * In interleaved mode update the state variables. Also adjust the
! 1304: * transmit phase to avoid crossover.
! 1305: */
! 1306: if (peer->flip != 0) {
! 1307: peer->rec = p_rec;
! 1308: peer->dst = rbufp->recv_time;
! 1309: if (peer->nextdate - current_time < (1 << min(peer->ppoll,
! 1310: peer->hpoll)) / 2)
! 1311: peer->nextdate++;
! 1312: else
! 1313: peer->nextdate--;
! 1314: }
! 1315: }
! 1316:
! 1317:
! 1318: /*
! 1319: * process_packet - Packet Procedure, a la Section 3.4.4 of the
! 1320: * specification. Or almost, at least. If we're in here we have a
! 1321: * reasonable expectation that we will be having a long term
! 1322: * relationship with this host.
! 1323: */
! 1324: void
! 1325: process_packet(
! 1326: register struct peer *peer,
! 1327: register struct pkt *pkt,
! 1328: u_int len
! 1329: )
! 1330: {
! 1331: double t34, t21;
! 1332: double p_offset, p_del, p_disp;
! 1333: l_fp p_rec, p_xmt, p_org, p_reftime, ci;
! 1334: u_char pmode, pleap, pstratum;
! 1335: char statstr[NTP_MAXSTRLEN];
! 1336: #ifdef ASSYM
! 1337: int itemp;
! 1338: double etemp, ftemp, td;
! 1339: #endif /* ASSYM */
! 1340:
! 1341: sys_processed++;
! 1342: peer->processed++;
! 1343: p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
! 1344: p_offset = 0;
! 1345: p_disp = FPTOD(NTOHS_FP(pkt->rootdisp));
! 1346: NTOHL_FP(&pkt->reftime, &p_reftime);
! 1347: NTOHL_FP(&pkt->org, &p_org);
! 1348: NTOHL_FP(&pkt->rec, &p_rec);
! 1349: NTOHL_FP(&pkt->xmt, &p_xmt);
! 1350: pmode = PKT_MODE(pkt->li_vn_mode);
! 1351: pleap = PKT_LEAP(pkt->li_vn_mode);
! 1352: pstratum = PKT_TO_STRATUM(pkt->stratum);
! 1353:
! 1354: /*
! 1355: * Capture the header values in the client/peer association..
! 1356: */
! 1357: record_raw_stats(&peer->srcadr, peer->dstadr ?
! 1358: &peer->dstadr->sin : NULL, &p_org, &p_rec, &p_xmt,
! 1359: &peer->dst);
! 1360: peer->leap = pleap;
! 1361: peer->stratum = min(pstratum, STRATUM_UNSPEC);
! 1362: peer->pmode = pmode;
! 1363: peer->precision = pkt->precision;
! 1364: peer->rootdelay = p_del;
! 1365: peer->rootdisp = p_disp;
! 1366: peer->refid = pkt->refid; /* network byte order */
! 1367: peer->reftime = p_reftime;
! 1368:
! 1369: /*
! 1370: * First, if either burst mode is armed, enable the burst.
! 1371: * Compute the headway for the next packet and delay if
! 1372: * necessary to avoid exceeding the threshold.
! 1373: */
! 1374: if (peer->retry > 0) {
! 1375: peer->retry = 0;
! 1376: if (peer->reach)
! 1377: peer->burst = min(1 << (peer->hpoll -
! 1378: peer->minpoll), NTP_SHIFT) - 1;
! 1379: else
! 1380: peer->burst = NTP_IBURST - 1;
! 1381: if (peer->burst > 0)
! 1382: peer->nextdate = current_time;
! 1383: }
! 1384: poll_update(peer, peer->hpoll);
! 1385:
! 1386: /*
! 1387: * Verify the server is synchronized; that is, the leap bits,
! 1388: * stratum and root distance are valid.
! 1389: */
! 1390: if (pleap == LEAP_NOTINSYNC || /* test 6 */
! 1391: pstratum < sys_floor || pstratum >= sys_ceiling)
! 1392: peer->flash |= TEST6; /* bad synch or strat */
! 1393: if (p_del / 2 + p_disp >= MAXDISPERSE) /* test 7 */
! 1394: peer->flash |= TEST7; /* bad header */
! 1395:
! 1396: /*
! 1397: * If any tests fail at this point, the packet is discarded.
! 1398: * Note that some flashers may have already been set in the
! 1399: * receive() routine.
! 1400: */
! 1401: if (peer->flash & PKT_TEST_MASK) {
! 1402: peer->seldisptoolarge++;
! 1403: #ifdef DEBUG
! 1404: if (debug)
! 1405: printf("packet: flash header %04x\n",
! 1406: peer->flash);
! 1407: #endif
! 1408: return;
! 1409: }
! 1410:
! 1411: /*
! 1412: * If the peer was previously unreachable, raise a trap. In any
! 1413: * case, mark it reachable.
! 1414: */
! 1415: if (!peer->reach) {
! 1416: report_event(PEVNT_REACH, peer, NULL);
! 1417: peer->timereachable = current_time;
! 1418: }
! 1419: peer->reach |= 1;
! 1420:
! 1421: /*
! 1422: * For a client/server association, calculate the clock offset,
! 1423: * roundtrip delay and dispersion. The equations are reordered
! 1424: * from the spec for more efficient use of temporaries. For a
! 1425: * broadcast association, offset the last measurement by the
! 1426: * computed delay during the client/server volley. Note the
! 1427: * computation of dispersion includes the system precision plus
! 1428: * that due to the frequency error since the origin time.
! 1429: *
! 1430: * It is very important to respect the hazards of overflow. The
! 1431: * only permitted operation on raw timestamps is subtraction,
! 1432: * where the result is a signed quantity spanning from 68 years
! 1433: * in the past to 68 years in the future. To avoid loss of
! 1434: * precision, these calculations are done using 64-bit integer
! 1435: * arithmetic. However, the offset and delay calculations are
! 1436: * sums and differences of these first-order differences, which
! 1437: * if done using 64-bit integer arithmetic, would be valid over
! 1438: * only half that span. Since the typical first-order
! 1439: * differences are usually very small, they are converted to 64-
! 1440: * bit doubles and all remaining calculations done in floating-
! 1441: * double arithmetic. This preserves the accuracy while
! 1442: * retaining the 68-year span.
! 1443: *
! 1444: * There are three interleaving schemes, basic, interleaved
! 1445: * symmetric and interleaved broadcast. The timestamps are
! 1446: * idioscyncratically different. See the onwire briefing/white
! 1447: * paper at www.eecis.udel.edu/~mills for details.
! 1448: *
! 1449: * Interleaved symmetric mode
! 1450: * t1 = peer->aorg/borg, t2 = peer->rec, t3 = p_xmt,
! 1451: * t4 = peer->dst
! 1452: */
! 1453: if (peer->flip != 0) {
! 1454: ci = p_xmt; /* t3 - t4 */
! 1455: L_SUB(&ci, &peer->dst);
! 1456: LFPTOD(&ci, t34);
! 1457: ci = p_rec; /* t2 - t1 */
! 1458: if (peer->flip > 0)
! 1459: L_SUB(&ci, &peer->borg);
! 1460: else
! 1461: L_SUB(&ci, &peer->aorg);
! 1462: LFPTOD(&ci, t21);
! 1463: p_del = t21 - t34;
! 1464: p_offset = (t21 + t34) / 2.;
! 1465: if (p_del < 0 || p_del > 1.) {
! 1466: sprintf(statstr, "t21 %.6f t34 %.6f", t21, t34);
! 1467: report_event(PEVNT_XERR, peer, statstr);
! 1468: return;
! 1469: }
! 1470:
! 1471: /*
! 1472: * Broadcast modes
! 1473: */
! 1474: } else if (peer->pmode == MODE_BROADCAST) {
! 1475:
! 1476: /*
! 1477: * Interleaved broadcast mode. Use interleaved timestamps.
! 1478: * t1 = peer->borg, t2 = p_org, t3 = p_org, t4 = aorg
! 1479: */
! 1480: if (peer->flags & FLAG_XB) {
! 1481: ci = p_org; /* delay */
! 1482: L_SUB(&ci, &peer->aorg);
! 1483: LFPTOD(&ci, t34);
! 1484: ci = p_org; /* t2 - t1 */
! 1485: L_SUB(&ci, &peer->borg);
! 1486: LFPTOD(&ci, t21);
! 1487: peer->aorg = p_xmt;
! 1488: peer->borg = peer->dst;
! 1489: if (t34 < 0 || t34 > 1.) {
! 1490: sprintf(statstr,
! 1491: "offset %.6f delay %.6f", t21, t34);
! 1492: report_event(PEVNT_XERR, peer, statstr);
! 1493: return;
! 1494: }
! 1495: p_offset = t21;
! 1496: peer->xleave = t34;
! 1497:
! 1498: /*
! 1499: * Basic broadcast - use direct timestamps.
! 1500: * t3 = p_xmt, t4 = peer->dst
! 1501: */
! 1502: } else {
! 1503: ci = p_xmt; /* t3 - t4 */
! 1504: L_SUB(&ci, &peer->dst);
! 1505: LFPTOD(&ci, t34);
! 1506: p_offset = t34;
! 1507: }
! 1508:
! 1509: /*
! 1510: * When calibration is complete and the clock is
! 1511: * synchronized, the bias is calculated as the difference
! 1512: * between the unicast timestamp and the broadcast
! 1513: * timestamp. This works for both basic and interleaved
! 1514: * modes.
! 1515: */
! 1516: if (FLAG_BC_VOL & peer->flags) {
! 1517: peer->flags &= ~FLAG_BC_VOL;
! 1518: peer->delay = (peer->offset - p_offset) * 2;
! 1519: }
! 1520: p_del = peer->delay;
! 1521: p_offset += p_del / 2;
! 1522:
! 1523:
! 1524: /*
! 1525: * Basic mode, otherwise known as the old fashioned way.
! 1526: *
! 1527: * t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->dst
! 1528: */
! 1529: } else {
! 1530: ci = p_xmt; /* t3 - t4 */
! 1531: L_SUB(&ci, &peer->dst);
! 1532: LFPTOD(&ci, t34);
! 1533: ci = p_rec; /* t2 - t1 */
! 1534: L_SUB(&ci, &p_org);
! 1535: LFPTOD(&ci, t21);
! 1536: p_del = fabs(t21 - t34);
! 1537: p_offset = (t21 + t34) / 2.;
! 1538: }
! 1539: p_offset += peer->bias;
! 1540: p_disp = LOGTOD(sys_precision) + LOGTOD(peer->precision) +
! 1541: clock_phi * p_del;
! 1542:
! 1543: #if ASSYM
! 1544: /*
! 1545: * This code calculates the outbound and inbound data rates by
! 1546: * measuring the differences between timestamps at different
! 1547: * packet lengths. This is helpful in cases of large asymmetric
! 1548: * delays commonly experienced on deep space communication
! 1549: * links.
! 1550: */
! 1551: if (peer->t21_last > 0 && peer->t34_bytes > 0) {
! 1552: itemp = peer->t21_bytes - peer->t21_last;
! 1553: if (itemp > 25) {
! 1554: etemp = t21 - peer->t21;
! 1555: if (fabs(etemp) > 1e-6) {
! 1556: ftemp = itemp / etemp;
! 1557: if (ftemp > 1000.)
! 1558: peer->r21 = ftemp;
! 1559: }
! 1560: }
! 1561: itemp = len - peer->t34_bytes;
! 1562: if (itemp > 25) {
! 1563: etemp = -t34 - peer->t34;
! 1564: if (fabs(etemp) > 1e-6) {
! 1565: ftemp = itemp / etemp;
! 1566: if (ftemp > 1000.)
! 1567: peer->r34 = ftemp;
! 1568: }
! 1569: }
! 1570: }
! 1571:
! 1572: /*
! 1573: * The following section compensates for different data rates on
! 1574: * the outbound (d21) and inbound (t34) directions. To do this,
! 1575: * it finds t such that r21 * t - r34 * (d - t) = 0, where d is
! 1576: * the roundtrip delay. Then it calculates the correction as a
! 1577: * fraction of d.
! 1578: */
! 1579: peer->t21 = t21;
! 1580: peer->t21_last = peer->t21_bytes;
! 1581: peer->t34 = -t34;
! 1582: peer->t34_bytes = len;
! 1583: #ifdef DEBUG
! 1584: if (debug > 1)
! 1585: printf("packet: t21 %.9lf %d t34 %.9lf %d\n", peer->t21,
! 1586: peer->t21_bytes, peer->t34, peer->t34_bytes);
! 1587: #endif
! 1588: if (peer->r21 > 0 && peer->r34 > 0 && p_del > 0) {
! 1589: if (peer->pmode != MODE_BROADCAST)
! 1590: td = (peer->r34 / (peer->r21 + peer->r34) -
! 1591: .5) * p_del;
! 1592: else
! 1593: td = 0;
! 1594:
! 1595: /*
! 1596: * Unfortunately, in many cases the errors are
! 1597: * unacceptable, so for the present the rates are not
! 1598: * used. In future, we might find conditions where the
! 1599: * calculations are useful, so this should be considered
! 1600: * a work in progress.
! 1601: */
! 1602: t21 -= td;
! 1603: t34 -= td;
! 1604: #ifdef DEBUG
! 1605: if (debug > 1)
! 1606: printf("packet: del %.6lf r21 %.1lf r34 %.1lf %.6lf\n",
! 1607: p_del, peer->r21 / 1e3, peer->r34 / 1e3,
! 1608: td);
! 1609: #endif
! 1610: }
! 1611: #endif /* ASSYM */
! 1612:
! 1613: /*
! 1614: * That was awesome. Now hand off to the clock filter.
! 1615: */
! 1616: clock_filter(peer, p_offset, p_del, p_disp);
! 1617:
! 1618: /*
! 1619: * If we are in broadcast calibrate mode, return to broadcast
! 1620: * client mode when the client is fit and the autokey dance is
! 1621: * complete.
! 1622: */
! 1623: if ((FLAG_BC_VOL & peer->flags) && MODE_CLIENT == peer->hmode &&
! 1624: !(TEST11 & peer_unfit(peer))) { /* distance exceeded */
! 1625: #ifdef OPENSSL
! 1626: if (peer->flags & FLAG_SKEY) {
! 1627: if (!(~peer->crypto & CRYPTO_FLAG_ALL))
! 1628: peer->hmode = MODE_BCLIENT;
! 1629: } else {
! 1630: peer->hmode = MODE_BCLIENT;
! 1631: }
! 1632: #else /* OPENSSL */
! 1633: peer->hmode = MODE_BCLIENT;
! 1634: #endif /* OPENSSL */
! 1635: }
! 1636: }
! 1637:
! 1638:
! 1639: /*
! 1640: * clock_update - Called at system process update intervals.
! 1641: */
! 1642: static void
! 1643: clock_update(
! 1644: struct peer *peer /* peer structure pointer */
! 1645: )
! 1646: {
! 1647: double dtemp;
! 1648: l_fp now;
! 1649: #ifdef HAVE_LIBSCF_H
! 1650: char *fmri;
! 1651: #endif /* HAVE_LIBSCF_H */
! 1652:
! 1653: /*
! 1654: * Update the system state variables. We do this very carefully,
! 1655: * as the poll interval might need to be clamped differently.
! 1656: */
! 1657: sys_peer = peer;
! 1658: sys_epoch = peer->epoch;
! 1659: if (sys_poll < peer->minpoll)
! 1660: sys_poll = peer->minpoll;
! 1661: if (sys_poll > peer->maxpoll)
! 1662: sys_poll = peer->maxpoll;
! 1663: poll_update(peer, sys_poll);
! 1664: sys_stratum = min(peer->stratum + 1, STRATUM_UNSPEC);
! 1665: if (peer->stratum == STRATUM_REFCLOCK ||
! 1666: peer->stratum == STRATUM_UNSPEC)
! 1667: sys_refid = peer->refid;
! 1668: else
! 1669: sys_refid = addr2refid(&peer->srcadr);
! 1670: dtemp = sys_jitter + fabs(sys_offset) + peer->disp +
! 1671: (peer->delay + peer->rootdelay) / 2 + clock_phi *
! 1672: (current_time - peer->update);
! 1673: sys_rootdisp = dtemp + peer->rootdisp;
! 1674: sys_rootdelay = peer->delay + peer->rootdelay;
! 1675: sys_reftime = peer->dst;
! 1676:
! 1677: #ifdef DEBUG
! 1678: if (debug)
! 1679: printf(
! 1680: "clock_update: at %lu sample %lu associd %d\n",
! 1681: current_time, peer->epoch, peer->associd);
! 1682: #endif
! 1683:
! 1684: /*
! 1685: * Comes now the moment of truth. Crank the clock discipline and
! 1686: * see what comes out.
! 1687: */
! 1688: switch (local_clock(peer, sys_offset)) {
! 1689:
! 1690: /*
! 1691: * Clock exceeds panic threshold. Life as we know it ends.
! 1692: */
! 1693: case -1:
! 1694: #ifdef HAVE_LIBSCF_H
! 1695: /*
! 1696: * For Solaris enter the maintenance mode.
! 1697: */
! 1698: if ((fmri = getenv("SMF_FMRI")) != NULL) {
! 1699: if (smf_maintain_instance(fmri, 0) < 0) {
! 1700: printf("smf_maintain_instance: %s\n",
! 1701: scf_strerror(scf_error()));
! 1702: exit(1);
! 1703: }
! 1704: /*
! 1705: * Sleep until SMF kills us.
! 1706: */
! 1707: for (;;)
! 1708: pause();
! 1709: }
! 1710: #endif /* HAVE_LIBSCF_H */
! 1711: exit (-1);
! 1712: /* not reached */
! 1713:
! 1714: /*
! 1715: * Clock was stepped. Flush all time values of all peers.
! 1716: */
! 1717: case 2:
! 1718: clear_all();
! 1719: sys_leap = LEAP_NOTINSYNC;
! 1720: sys_stratum = STRATUM_UNSPEC;
! 1721: memcpy(&sys_refid, "STEP", 4);
! 1722: sys_rootdelay = 0;
! 1723: sys_rootdisp = 0;
! 1724: L_CLR(&sys_reftime);
! 1725: sys_jitter = LOGTOD(sys_precision);
! 1726: leapsec = 0;
! 1727: break;
! 1728:
! 1729: /*
! 1730: * Clock was slewed. Handle the leapsecond stuff.
! 1731: */
! 1732: case 1:
! 1733:
! 1734: /*
! 1735: * If this is the first time the clock is set, reset the
! 1736: * leap bits. If crypto, the timer will goose the setup
! 1737: * process.
! 1738: */
! 1739: if (sys_leap == LEAP_NOTINSYNC) {
! 1740: sys_leap = LEAP_NOWARNING;
! 1741: #ifdef OPENSSL
! 1742: if (crypto_flags)
! 1743: crypto_update();
! 1744: #endif /* OPENSSL */
! 1745: }
! 1746:
! 1747: /*
! 1748: * If the leapseconds values are from file or network
! 1749: * and the leap is in the future, schedule a leap at the
! 1750: * given epoch. Otherwise, if the number of survivor
! 1751: * leap bits is greater than half the number of
! 1752: * survivors, schedule a leap for the end of the current
! 1753: * month.
! 1754: */
! 1755: get_systime(&now);
! 1756: if (leap_sec > 0) {
! 1757: if (leap_sec > now.l_ui) {
! 1758: sys_tai = leap_tai - 1;
! 1759: if (leapsec == 0)
! 1760: report_event(EVNT_ARMED, NULL,
! 1761: NULL);
! 1762: leapsec = leap_sec - now.l_ui;
! 1763: } else {
! 1764: sys_tai = leap_tai;
! 1765: }
! 1766: break;
! 1767:
! 1768: } else if (leap_vote > sys_survivors / 2) {
! 1769: leap_peers = now.l_ui + leap_month(now.l_ui);
! 1770: if (leap_peers > now.l_ui) {
! 1771: if (leapsec == 0)
! 1772: report_event(PEVNT_ARMED, peer,
! 1773: NULL);
! 1774: leapsec = leap_peers - now.l_ui;
! 1775: }
! 1776: } else if (leapsec > 0) {
! 1777: report_event(EVNT_DISARMED, NULL, NULL);
! 1778: leapsec = 0;
! 1779: }
! 1780: break;
! 1781:
! 1782: /*
! 1783: * Popcorn spike or step threshold exceeded. Pretend it never
! 1784: * happened.
! 1785: */
! 1786: default:
! 1787: break;
! 1788: }
! 1789: }
! 1790:
! 1791:
! 1792: /*
! 1793: * poll_update - update peer poll interval
! 1794: */
! 1795: void
! 1796: poll_update(
! 1797: struct peer *peer, /* peer structure pointer */
! 1798: int mpoll
! 1799: )
! 1800: {
! 1801: int hpoll, minpkt;
! 1802: u_long next, utemp;
! 1803:
! 1804: /*
! 1805: * This routine figures out when the next poll should be sent.
! 1806: * That turns out to be wickedly complicated. One problem is
! 1807: * that sometimes the time for the next poll is in the past when
! 1808: * the poll interval is reduced. We watch out for races here
! 1809: * between the receive process and the poll process.
! 1810: *
! 1811: * First, bracket the poll interval according to the type of
! 1812: * association and options. If a fixed interval is configured,
! 1813: * use minpoll. This primarily is for reference clocks, but
! 1814: * works for any association. Otherwise, clamp the poll interval
! 1815: * between minpoll and maxpoll.
! 1816: */
! 1817: if (peer->cast_flags & MDF_BCLNT)
! 1818: hpoll = peer->minpoll;
! 1819: else
! 1820: hpoll = max(min(peer->maxpoll, mpoll), peer->minpoll);
! 1821:
! 1822: #ifdef OPENSSL
! 1823: /*
! 1824: * If during the crypto protocol the poll interval has changed,
! 1825: * the lifetimes in the key list are probably bogus. Purge the
! 1826: * the key list and regenerate it later.
! 1827: */
! 1828: if ((peer->flags & FLAG_SKEY) && hpoll != peer->hpoll)
! 1829: key_expire(peer);
! 1830: #endif /* OPENSSL */
! 1831: peer->hpoll = hpoll;
! 1832:
! 1833: /*
! 1834: * There are three variables important for poll scheduling, the
! 1835: * current time (current_time), next scheduled time (nextdate)
! 1836: * and the earliest time (utemp). The earliest time is 2 s
! 1837: * seconds, but could be more due to rate management. When
! 1838: * sending in a burst, use the earliest time. When not in a
! 1839: * burst but with a reply pending, send at the earliest time
! 1840: * unless the next scheduled time has not advanced. This can
! 1841: * only happen if multiple replies are peinding in the same
! 1842: * response interval. Otherwise, send at the later of the next
! 1843: * scheduled time and the earliest time.
! 1844: *
! 1845: * Now we figure out if there is an override. If a burst is in
! 1846: * progress and we get called from the receive process, just
! 1847: * slink away. If called from the poll process, delay 1 s for a
! 1848: * reference clock, otherwise 2 s.
! 1849: */
! 1850: minpkt = 1 << ntp_minpkt;
! 1851: utemp = current_time + max(peer->throttle - (NTP_SHIFT - 1) *
! 1852: (1 << peer->minpoll), minpkt);
! 1853: if (peer->burst > 0) {
! 1854: if (peer->nextdate > current_time)
! 1855: return;
! 1856: #ifdef REFCLOCK
! 1857: else if (peer->flags & FLAG_REFCLOCK)
! 1858: peer->nextdate = current_time + RESP_DELAY;
! 1859: #endif /* REFCLOCK */
! 1860: else
! 1861: peer->nextdate = utemp;
! 1862:
! 1863: #ifdef OPENSSL
! 1864: /*
! 1865: * If a burst is not in progress and a crypto response message
! 1866: * is pending, delay 2 s, but only if this is a new interval.
! 1867: */
! 1868: } else if (peer->cmmd != NULL) {
! 1869: if (peer->nextdate > current_time) {
! 1870: if (peer->nextdate + minpkt != utemp)
! 1871: peer->nextdate = utemp;
! 1872: } else {
! 1873: peer->nextdate = utemp;
! 1874: }
! 1875: #endif /* OPENSSL */
! 1876:
! 1877: /*
! 1878: * The ordinary case. If a retry, use minpoll; if unreachable,
! 1879: * use host poll; otherwise, use the minimum of host and peer
! 1880: * polls; In other words, oversampling is okay but
! 1881: * understampling is evil. Use the maximum of this value and the
! 1882: * headway. If the average headway is greater than the headway
! 1883: * threshold, increase the headway by the minimum interval.
! 1884: */
! 1885: } else {
! 1886: if (peer->retry > 0)
! 1887: hpoll = peer->minpoll;
! 1888: else if (!(peer->reach))
! 1889: hpoll = peer->hpoll;
! 1890: else
! 1891: hpoll = min(peer->ppoll, peer->hpoll);
! 1892: #ifdef REFCLOCK
! 1893: if (peer->flags & FLAG_REFCLOCK)
! 1894: next = 1 << hpoll;
! 1895: else
! 1896: next = ((0x1000UL | (ntp_random() & 0x0ff)) <<
! 1897: hpoll) >> 12;
! 1898: #else /* REFCLOCK */
! 1899: next = ((0x1000UL | (ntp_random() & 0x0ff)) << hpoll) >>
! 1900: 12;
! 1901: #endif /* REFCLOCK */
! 1902: next += peer->outdate;
! 1903: if (next > utemp)
! 1904: peer->nextdate = next;
! 1905: else
! 1906: peer->nextdate = utemp;
! 1907: hpoll = peer->throttle - (1 << peer->minpoll);
! 1908: if (hpoll > 0)
! 1909: peer->nextdate += minpkt;
! 1910: }
! 1911: #ifdef DEBUG
! 1912: if (debug > 1)
! 1913: printf("poll_update: at %lu %s poll %d burst %d retry %d head %d early %lu next %lu\n",
! 1914: current_time, ntoa(&peer->srcadr), peer->hpoll,
! 1915: peer->burst, peer->retry, peer->throttle,
! 1916: utemp - current_time, peer->nextdate -
! 1917: current_time);
! 1918: #endif
! 1919: }
! 1920:
! 1921:
! 1922: /*
! 1923: * peer_clear - clear peer filter registers. See Section 3.4.8 of the
! 1924: * spec.
! 1925: */
! 1926: void
! 1927: peer_clear(
! 1928: struct peer *peer, /* peer structure */
! 1929: char *ident /* tally lights */
! 1930: )
! 1931: {
! 1932: int i;
! 1933:
! 1934: #ifdef OPENSSL
! 1935: /*
! 1936: * If cryptographic credentials have been acquired, toss them to
! 1937: * Valhalla. Note that autokeys are ephemeral, in that they are
! 1938: * tossed immediately upon use. Therefore, the keylist can be
! 1939: * purged anytime without needing to preserve random keys. Note
! 1940: * that, if the peer is purged, the cryptographic variables are
! 1941: * purged, too. This makes it much harder to sneak in some
! 1942: * unauthenticated data in the clock filter.
! 1943: */
! 1944: key_expire(peer);
! 1945: if (peer->iffval != NULL)
! 1946: BN_free(peer->iffval);
! 1947: value_free(&peer->cookval);
! 1948: value_free(&peer->recval);
! 1949: value_free(&peer->encrypt);
! 1950: value_free(&peer->sndval);
! 1951: if (peer->cmmd != NULL)
! 1952: free(peer->cmmd);
! 1953: if (peer->subject != NULL)
! 1954: free(peer->subject);
! 1955: if (peer->issuer != NULL)
! 1956: free(peer->issuer);
! 1957: #endif /* OPENSSL */
! 1958:
! 1959: /*
! 1960: * Clear all values, including the optional crypto values above.
! 1961: */
! 1962: memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
! 1963: peer->ppoll = peer->maxpoll;
! 1964: peer->hpoll = peer->minpoll;
! 1965: peer->disp = MAXDISPERSE;
! 1966: peer->flash = peer_unfit(peer);
! 1967: peer->jitter = LOGTOD(sys_precision);
! 1968:
! 1969: /*
! 1970: * If interleave mode, initialize the alternate origin switch.
! 1971: */
! 1972: if (peer->flags & FLAG_XLEAVE)
! 1973: peer->flip = 1;
! 1974: for (i = 0; i < NTP_SHIFT; i++) {
! 1975: peer->filter_order[i] = i;
! 1976: peer->filter_disp[i] = MAXDISPERSE;
! 1977: }
! 1978: #ifdef REFCLOCK
! 1979: if (!(peer->flags & FLAG_REFCLOCK)) {
! 1980: peer->leap = LEAP_NOTINSYNC;
! 1981: peer->stratum = STRATUM_UNSPEC;
! 1982: memcpy(&peer->refid, ident, 4);
! 1983: }
! 1984: #else
! 1985: peer->leap = LEAP_NOTINSYNC;
! 1986: peer->stratum = STRATUM_UNSPEC;
! 1987: memcpy(&peer->refid, ident, 4);
! 1988: #endif /* REFCLOCK */
! 1989:
! 1990: /*
! 1991: * During initialization use the association count to spread out
! 1992: * the polls at one-second intervals. Otherwise, randomize over
! 1993: * the minimum poll interval in order to avoid broadcast
! 1994: * implosion.
! 1995: */
! 1996: peer->nextdate = peer->update = peer->outdate = current_time;
! 1997: if (initializing) {
! 1998: peer->nextdate += peer_associations;
! 1999: } else if (peer->hmode == MODE_PASSIVE) {
! 2000: peer->nextdate += 1 << ntp_minpkt;
! 2001: } else {
! 2002: peer->nextdate += ntp_random() % peer_associations;
! 2003: }
! 2004: #ifdef OPENSSL
! 2005: peer->refresh = current_time + (1 << NTP_REFRESH);
! 2006: #endif /* OPENSSL */
! 2007: #ifdef DEBUG
! 2008: if (debug)
! 2009: printf(
! 2010: "peer_clear: at %ld next %ld associd %d refid %s\n",
! 2011: current_time, peer->nextdate, peer->associd,
! 2012: ident);
! 2013: #endif
! 2014: }
! 2015:
! 2016:
! 2017: /*
! 2018: * clock_filter - add incoming clock sample to filter register and run
! 2019: * the filter procedure to find the best sample.
! 2020: */
! 2021: void
! 2022: clock_filter(
! 2023: struct peer *peer, /* peer structure pointer */
! 2024: double sample_offset, /* clock offset */
! 2025: double sample_delay, /* roundtrip delay */
! 2026: double sample_disp /* dispersion */
! 2027: )
! 2028: {
! 2029: double dst[NTP_SHIFT]; /* distance vector */
! 2030: int ord[NTP_SHIFT]; /* index vector */
! 2031: int i, j, k, m;
! 2032: double dtemp, etemp;
! 2033: char tbuf[80];
! 2034:
! 2035: /*
! 2036: * A sample consists of the offset, delay, dispersion and epoch
! 2037: * of arrival. The offset and delay are determined by the on-
! 2038: * wire protocol. The dispersion grows from the last outbound
! 2039: * packet to the arrival of this one increased by the sum of the
! 2040: * peer precision and the system precision as required by the
! 2041: * error budget. First, shift the new arrival into the shift
! 2042: * register discarding the oldest one.
! 2043: */
! 2044: j = peer->filter_nextpt;
! 2045: peer->filter_offset[j] = sample_offset;
! 2046: peer->filter_delay[j] = sample_delay;
! 2047: peer->filter_disp[j] = sample_disp;
! 2048: peer->filter_epoch[j] = current_time;
! 2049: j = (j + 1) % NTP_SHIFT;
! 2050: peer->filter_nextpt = j;
! 2051:
! 2052: /*
! 2053: * Update dispersions since the last update and at the same
! 2054: * time initialize the distance and index lists. Since samples
! 2055: * become increasingly uncorrelated beyond the Allan intercept,
! 2056: * only under exceptional cases will an older sample be used.
! 2057: * Therefore, the distance list uses a compound metric. If the
! 2058: * dispersion is greater than the maximum dispersion, clamp the
! 2059: * distance at that value. If the time since the last update is
! 2060: * less than the Allan intercept use the delay; otherwise, use
! 2061: * the sum of the delay and dispersion.
! 2062: */
! 2063: dtemp = clock_phi * (current_time - peer->update);
! 2064: peer->update = current_time;
! 2065: for (i = NTP_SHIFT - 1; i >= 0; i--) {
! 2066: if (i != 0)
! 2067: peer->filter_disp[j] += dtemp;
! 2068: if (peer->filter_disp[j] >= MAXDISPERSE) {
! 2069: peer->filter_disp[j] = MAXDISPERSE;
! 2070: dst[i] = MAXDISPERSE;
! 2071: } else if (peer->update - peer->filter_epoch[j] >
! 2072: ULOGTOD(allan_xpt)) {
! 2073: dst[i] = peer->filter_delay[j] +
! 2074: peer->filter_disp[j];
! 2075: } else {
! 2076: dst[i] = peer->filter_delay[j];
! 2077: }
! 2078: ord[i] = j;
! 2079: j = (j + 1) % NTP_SHIFT;
! 2080: }
! 2081:
! 2082: /*
! 2083: * If the clock discipline has stabilized, sort the samples by
! 2084: * distance.
! 2085: */
! 2086: if (sys_leap != LEAP_NOTINSYNC) {
! 2087: for (i = 1; i < NTP_SHIFT; i++) {
! 2088: for (j = 0; j < i; j++) {
! 2089: if (dst[j] > dst[i]) {
! 2090: k = ord[j];
! 2091: ord[j] = ord[i];
! 2092: ord[i] = k;
! 2093: etemp = dst[j];
! 2094: dst[j] = dst[i];
! 2095: dst[i] = etemp;
! 2096: }
! 2097: }
! 2098: }
! 2099: }
! 2100:
! 2101: /*
! 2102: * Copy the index list to the association structure so ntpq
! 2103: * can see it later. Prune the distance list to leave only
! 2104: * samples less than the maximum dispersion, which disfavors
! 2105: * uncorrelated samples older than the Allan intercept. To
! 2106: * further improve the jitter estimate, of the remainder leave
! 2107: * only samples less than the maximum distance, but keep at
! 2108: * least two samples for jitter calculation.
! 2109: */
! 2110: m = 0;
! 2111: for (i = 0; i < NTP_SHIFT; i++) {
! 2112: peer->filter_order[i] = (u_char) ord[i];
! 2113: if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
! 2114: sys_maxdist))
! 2115: continue;
! 2116: m++;
! 2117: }
! 2118:
! 2119: /*
! 2120: * Compute the dispersion and jitter. The dispersion is weighted
! 2121: * exponentially by NTP_FWEIGHT (0.5) so it is normalized close
! 2122: * to 1.0. The jitter is the RMS differences relative to the
! 2123: * lowest delay sample.
! 2124: */
! 2125: peer->disp = peer->jitter = 0;
! 2126: k = ord[0];
! 2127: for (i = NTP_SHIFT - 1; i >= 0; i--) {
! 2128: j = ord[i];
! 2129: peer->disp = NTP_FWEIGHT * (peer->disp +
! 2130: peer->filter_disp[j]);
! 2131: if (i < m)
! 2132: peer->jitter += DIFF(peer->filter_offset[j],
! 2133: peer->filter_offset[k]);
! 2134: }
! 2135:
! 2136: /*
! 2137: * If no acceptable samples remain in the shift register,
! 2138: * quietly tiptoe home leaving only the dispersion. Otherwise,
! 2139: * save the offset, delay and jitter. Note the jitter must not
! 2140: * be less than the precision.
! 2141: */
! 2142: if (m == 0) {
! 2143: clock_select();
! 2144: return;
! 2145: }
! 2146:
! 2147: etemp = fabs(peer->offset - peer->filter_offset[k]);
! 2148: peer->offset = peer->filter_offset[k];
! 2149: peer->delay = peer->filter_delay[k];
! 2150: if (m > 1)
! 2151: peer->jitter /= m - 1;
! 2152: peer->jitter = max(SQRT(peer->jitter), LOGTOD(sys_precision));
! 2153:
! 2154: /*
! 2155: * If the the new sample and the current sample are both valid
! 2156: * and the difference between their offsets exceeds CLOCK_SGATE
! 2157: * (3) times the jitter and the interval between them is less
! 2158: * than twice the host poll interval, consider the new sample
! 2159: * a popcorn spike and ignore it.
! 2160: */
! 2161: if (peer->disp < sys_maxdist && peer->filter_disp[k] <
! 2162: sys_maxdist && etemp > CLOCK_SGATE * peer->jitter &&
! 2163: peer->filter_epoch[k] - peer->epoch < 2. *
! 2164: ULOGTOD(peer->hpoll)) {
! 2165: snprintf(tbuf, sizeof(tbuf), "%.6f s", etemp);
! 2166: report_event(PEVNT_POPCORN, peer, tbuf);
! 2167: return;
! 2168: }
! 2169:
! 2170: /*
! 2171: * A new minimum sample is useful only if it is later than the
! 2172: * last one used. In this design the maximum lifetime of any
! 2173: * sample is not greater than eight times the poll interval, so
! 2174: * the maximum interval between minimum samples is eight
! 2175: * packets.
! 2176: */
! 2177: if (peer->filter_epoch[k] <= peer->epoch) {
! 2178: #if DEBUG
! 2179: if (debug)
! 2180: printf("clock_filter: old sample %lu\n", current_time -
! 2181: peer->filter_epoch[k]);
! 2182: #endif
! 2183: return;
! 2184: }
! 2185: peer->epoch = peer->filter_epoch[k];
! 2186:
! 2187: /*
! 2188: * The mitigated sample statistics are saved for later
! 2189: * processing. If not synchronized or not in a burst, tickle the
! 2190: * clock select algorithm.
! 2191: */
! 2192: record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
! 2193: peer->offset, peer->delay, peer->disp, peer->jitter);
! 2194: #ifdef DEBUG
! 2195: if (debug)
! 2196: printf(
! 2197: "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f\n",
! 2198: m, peer->offset, peer->delay, peer->disp,
! 2199: peer->jitter);
! 2200: #endif
! 2201: if (peer->burst == 0 || sys_leap == LEAP_NOTINSYNC)
! 2202: clock_select();
! 2203: }
! 2204:
! 2205:
! 2206: /*
! 2207: * clock_select - find the pick-of-the-litter clock
! 2208: *
! 2209: * LOCKCLOCK: (1) If the local clock is the prefer peer, it will always
! 2210: * be enabled, even if declared falseticker, (2) only the prefer peer
! 2211: * caN Be selected as the system peer, (3) if the external source is
! 2212: * down, the system leap bits are set to 11 and the stratum set to
! 2213: * infinity.
! 2214: */
! 2215: void
! 2216: clock_select(void)
! 2217: {
! 2218: struct peer *peer;
! 2219: int i, j, k, n;
! 2220: int nlist, nl3;
! 2221: int allow, osurv;
! 2222: double d, e, f, g;
! 2223: double high, low;
! 2224: double seljitter;
! 2225: double synch[NTP_MAXASSOC], error[NTP_MAXASSOC];
! 2226: double orphmet = 2.0 * U_INT32_MAX; /* 2x is greater than */
! 2227: struct peer *osys_peer = NULL;
! 2228: struct peer *sys_prefer = NULL; /* prefer peer */
! 2229: struct peer *typesystem = NULL;
! 2230: struct peer *typeorphan = NULL;
! 2231: #ifdef REFCLOCK
! 2232: struct peer *typeacts = NULL;
! 2233: struct peer *typelocal = NULL;
! 2234: struct peer *typepps = NULL;
! 2235: #endif /* REFCLOCK */
! 2236:
! 2237: static int list_alloc = 0;
! 2238: static struct endpoint *endpoint = NULL;
! 2239: static int *indx = NULL;
! 2240: static struct peer **peer_list = NULL;
! 2241: static u_int endpoint_size = 0;
! 2242: static u_int indx_size = 0;
! 2243: static u_int peer_list_size = 0;
! 2244:
! 2245: /*
! 2246: * Initialize and create endpoint, index and peer lists big
! 2247: * enough to handle all associations.
! 2248: */
! 2249: osys_peer = sys_peer;
! 2250: osurv = sys_survivors;
! 2251: sys_survivors = 0;
! 2252: #ifdef LOCKCLOCK
! 2253: sys_leap = LEAP_NOTINSYNC;
! 2254: sys_stratum = STRATUM_UNSPEC;
! 2255: memcpy(&sys_refid, "DOWN", 4);
! 2256: #endif /* LOCKCLOCK */
! 2257: nlist = 0;
! 2258: for (n = 0; n < NTP_HASH_SIZE; n++)
! 2259: nlist += peer_hash_count[n];
! 2260: if (nlist > list_alloc) {
! 2261: if (list_alloc > 0) {
! 2262: free(endpoint);
! 2263: free(indx);
! 2264: free(peer_list);
! 2265: }
! 2266: while (list_alloc < nlist) {
! 2267: list_alloc += 5;
! 2268: endpoint_size += 5 * 3 * sizeof(*endpoint);
! 2269: indx_size += 5 * 3 * sizeof(*indx);
! 2270: peer_list_size += 5 * sizeof(*peer_list);
! 2271: }
! 2272: endpoint = (struct endpoint *)emalloc(endpoint_size);
! 2273: indx = (int *)emalloc(indx_size);
! 2274: peer_list = (struct peer **)emalloc(peer_list_size);
! 2275: }
! 2276:
! 2277: /*
! 2278: * Initially, we populate the island with all the rifraff peers
! 2279: * that happen to be lying around. Those with seriously
! 2280: * defective clocks are immediately booted off the island. Then,
! 2281: * the falsetickers are culled and put to sea. The truechimers
! 2282: * remaining are subject to repeated rounds where the most
! 2283: * unpopular at each round is kicked off. When the population
! 2284: * has dwindled to sys_minclock, the survivors split a million
! 2285: * bucks and collectively crank the chimes.
! 2286: */
! 2287: nlist = nl3 = 0; /* none yet */
! 2288: for (n = 0; n < NTP_HASH_SIZE; n++) {
! 2289: for (peer = peer_hash[n]; peer != NULL; peer =
! 2290: peer->next) {
! 2291: peer->new_status = CTL_PST_SEL_REJECT;
! 2292:
! 2293: /*
! 2294: * Leave the island immediately if the peer is
! 2295: * unfit to synchronize.
! 2296: */
! 2297: if (peer_unfit(peer))
! 2298: continue;
! 2299:
! 2300: /*
! 2301: * If this peer is an orphan parent, elect the
! 2302: * one with the lowest metric defined as the
! 2303: * IPv4 address or the first 64 bits of the
! 2304: * hashed IPv6 address. To ensure convergence
! 2305: * on the same selected orphan, consider as
! 2306: * well that this system may have the lowest
! 2307: * metric and be the orphan parent. If this
! 2308: * system wins, sys_peer will be NULL to trigger
! 2309: * orphan mode in timer().
! 2310: */
! 2311: if (peer->stratum == sys_orphan) {
! 2312: u_int32 localmet;
! 2313: u_int32 peermet;
! 2314:
! 2315: if (peer->dstadr != NULL)
! 2316: localmet = ntohl(peer->dstadr->addr_refid);
! 2317: else
! 2318: localmet = U_INT32_MAX;
! 2319: peermet = ntohl(addr2refid(&peer->srcadr));
! 2320: if (peermet < localmet &&
! 2321: peermet < orphmet) {
! 2322: typeorphan = peer;
! 2323: orphmet = peermet;
! 2324: }
! 2325: continue;
! 2326: }
! 2327:
! 2328: /*
! 2329: * If this peer could have the orphan parent
! 2330: * as a synchronization ancestor, exclude it
! 2331: * from selection to avoid forming a
! 2332: * synchronization loop within the orphan mesh,
! 2333: * triggering stratum climb to infinity
! 2334: * instability. Peers at stratum higher than
! 2335: * the orphan stratum could have the orphan
! 2336: * parent in ancestry so are excluded.
! 2337: * See http://bugs.ntp.org/2050
! 2338: */
! 2339: if (peer->stratum > sys_orphan)
! 2340: continue;
! 2341: #ifdef REFCLOCK
! 2342: /*
! 2343: * The following are special cases. We deal
! 2344: * with them later.
! 2345: */
! 2346: if (!(peer->flags & FLAG_PREFER)) {
! 2347: switch (peer->refclktype) {
! 2348: case REFCLK_LOCALCLOCK:
! 2349: if (typelocal == NULL)
! 2350: typelocal = peer;
! 2351: continue;
! 2352:
! 2353: case REFCLK_ACTS:
! 2354: if (typeacts == NULL)
! 2355: typeacts = peer;
! 2356: continue;
! 2357: }
! 2358: }
! 2359: #endif /* REFCLOCK */
! 2360:
! 2361: /*
! 2362: * If we get this far, the peer can stay on the
! 2363: * island, but does not yet have the immunity
! 2364: * idol.
! 2365: */
! 2366: peer->new_status = CTL_PST_SEL_SANE;
! 2367: peer_list[nlist++] = peer;
! 2368:
! 2369: /*
! 2370: * Insert each interval endpoint on the sorted
! 2371: * list.
! 2372: */
! 2373: e = peer->offset; /* Upper end */
! 2374: f = root_distance(peer);
! 2375: e = e + f;
! 2376: for (i = nl3 - 1; i >= 0; i--) {
! 2377: if (e >= endpoint[indx[i]].val)
! 2378: break;
! 2379:
! 2380: indx[i + 3] = indx[i];
! 2381: }
! 2382: indx[i + 3] = nl3;
! 2383: endpoint[nl3].type = 1;
! 2384: endpoint[nl3++].val = e;
! 2385:
! 2386: e = e - f; /* Center point */
! 2387: for (; i >= 0; i--) {
! 2388: if (e >= endpoint[indx[i]].val)
! 2389: break;
! 2390:
! 2391: indx[i + 2] = indx[i];
! 2392: }
! 2393: indx[i + 2] = nl3;
! 2394: endpoint[nl3].type = 0;
! 2395: endpoint[nl3++].val = e;
! 2396:
! 2397: e = e - f; /* Lower end */
! 2398: for (; i >= 0; i--) {
! 2399: if (e >= endpoint[indx[i]].val)
! 2400: break;
! 2401:
! 2402: indx[i + 1] = indx[i];
! 2403: }
! 2404: indx[i + 1] = nl3;
! 2405: endpoint[nl3].type = -1;
! 2406: endpoint[nl3++].val = e;
! 2407: }
! 2408: }
! 2409: #ifdef DEBUG
! 2410: if (debug > 2)
! 2411: for (i = 0; i < nl3; i++)
! 2412: printf("select: endpoint %2d %.6f\n",
! 2413: endpoint[indx[i]].type,
! 2414: endpoint[indx[i]].val);
! 2415: #endif
! 2416: /*
! 2417: * This is the actual algorithm that cleaves the truechimers
! 2418: * from the falsetickers. The original algorithm was described
! 2419: * in Keith Marzullo's dissertation, but has been modified for
! 2420: * better accuracy.
! 2421: *
! 2422: * Briefly put, we first assume there are no falsetickers, then
! 2423: * scan the candidate list first from the low end upwards and
! 2424: * then from the high end downwards. The scans stop when the
! 2425: * number of intersections equals the number of candidates less
! 2426: * the number of falsetickers. If this doesn't happen for a
! 2427: * given number of falsetickers, we bump the number of
! 2428: * falsetickers and try again. If the number of falsetickers
! 2429: * becomes equal to or greater than half the number of
! 2430: * candidates, the Albanians have won the Byzantine wars and
! 2431: * correct synchronization is not possible.
! 2432: *
! 2433: * Here, nlist is the number of candidates and allow is the
! 2434: * number of falsetickers. Upon exit, the truechimers are the
! 2435: * survivors with offsets not less than low and not greater than
! 2436: * high. There may be none of them.
! 2437: */
! 2438: low = 1e9;
! 2439: high = -1e9;
! 2440: for (allow = 0; 2 * allow < nlist; allow++) {
! 2441: int found;
! 2442:
! 2443: /*
! 2444: * Bound the interval (low, high) as the largest
! 2445: * interval containing points from presumed truechimers.
! 2446: */
! 2447: found = 0;
! 2448: n = 0;
! 2449: for (i = 0; i < nl3; i++) {
! 2450: low = endpoint[indx[i]].val;
! 2451: n -= endpoint[indx[i]].type;
! 2452: if (n >= nlist - allow)
! 2453: break;
! 2454: if (endpoint[indx[i]].type == 0)
! 2455: found++;
! 2456: }
! 2457: n = 0;
! 2458: for (j = nl3 - 1; j >= 0; j--) {
! 2459: high = endpoint[indx[j]].val;
! 2460: n += endpoint[indx[j]].type;
! 2461: if (n >= nlist - allow)
! 2462: break;
! 2463: if (endpoint[indx[j]].type == 0)
! 2464: found++;
! 2465: }
! 2466:
! 2467: /*
! 2468: * If the number of candidates found outside the
! 2469: * interval is greater than the number of falsetickers,
! 2470: * then at least one truechimer is outside the interval,
! 2471: * so go around again. This is what makes this algorithm
! 2472: * different than Marzullo's.
! 2473: */
! 2474: if (found > allow)
! 2475: continue;
! 2476:
! 2477: /*
! 2478: * If an interval containing truechimers is found, stop.
! 2479: * If not, increase the number of falsetickers and go
! 2480: * around again.
! 2481: */
! 2482: if (high > low)
! 2483: break;
! 2484: }
! 2485:
! 2486: /*
! 2487: * Clustering algorithm. Construct candidate list in order first
! 2488: * by stratum then by root distance, but keep only the best
! 2489: * NTP_MAXASSOC of them. Scan the list to find falsetickers, who
! 2490: * leave the island immediately. The TRUE peer is always a
! 2491: * truechimer. We must leave at least one peer to collect the
! 2492: * million bucks.
! 2493: */
! 2494: j = 0;
! 2495: for (i = 0; i < nlist; i++) {
! 2496: peer = peer_list[i];
! 2497: if (nlist > 1 && (peer->offset <= low || peer->offset >=
! 2498: high) && !(peer->flags & FLAG_TRUE))
! 2499: continue;
! 2500:
! 2501: #ifdef REFCLOCK
! 2502: /*
! 2503: * Eligible PPS peers must survive the intersection
! 2504: * algorithm. Use the first one found, but don't
! 2505: * include any of them in the cluster population.
! 2506: */
! 2507: if (peer->flags & FLAG_PPS) {
! 2508: if (typepps == NULL)
! 2509: typepps = peer;
! 2510: continue;
! 2511: }
! 2512: #endif /* REFCLOCK */
! 2513:
! 2514: /*
! 2515: * The metric is the scaled root distance at the next
! 2516: * poll interval plus the peer stratum.
! 2517: */
! 2518: d = (root_distance(peer) + clock_phi * (peer->nextdate -
! 2519: current_time)) / sys_maxdist + peer->stratum;
! 2520: if (j >= NTP_MAXASSOC) {
! 2521: if (d >= synch[j - 1])
! 2522: continue;
! 2523: else
! 2524: j--;
! 2525: }
! 2526: for (k = j; k > 0; k--) {
! 2527: if (d >= synch[k - 1])
! 2528: break;
! 2529:
! 2530: peer_list[k] = peer_list[k - 1];
! 2531: error[k] = error[k - 1];
! 2532: synch[k] = synch[k - 1];
! 2533: }
! 2534: peer_list[k] = peer;
! 2535: error[k] = peer->jitter;
! 2536: synch[k] = d;
! 2537: j++;
! 2538: }
! 2539: nlist = j;
! 2540:
! 2541: /*
! 2542: * If no survivors remain at this point, check if the modem
! 2543: * driver, local driver or orphan parent in that order. If so,
! 2544: * nominate the first one found as the only survivor.
! 2545: * Otherwise, give up and leave the island to the rats.
! 2546: */
! 2547: if (nlist == 0) {
! 2548: error[0] = 0;
! 2549: synch[0] = 0;
! 2550: #ifdef REFCLOCK
! 2551: if (typeacts != NULL) {
! 2552: peer_list[0] = typeacts;
! 2553: nlist = 1;
! 2554: } else if (typelocal != NULL) {
! 2555: peer_list[0] = typelocal;
! 2556: nlist = 1;
! 2557: } else
! 2558: #endif /* REFCLOCK */
! 2559: if (typeorphan != NULL) {
! 2560: peer_list[0] = typeorphan;
! 2561: nlist = 1;
! 2562: }
! 2563: }
! 2564:
! 2565: /*
! 2566: * Mark the candidates at this point as truechimers.
! 2567: */
! 2568: for (i = 0; i < nlist; i++) {
! 2569: peer_list[i]->new_status = CTL_PST_SEL_SELCAND;
! 2570: #ifdef DEBUG
! 2571: if (debug > 1)
! 2572: printf("select: survivor %s %f\n",
! 2573: stoa(&peer_list[i]->srcadr), synch[i]);
! 2574: #endif
! 2575: }
! 2576:
! 2577: /*
! 2578: * Now, vote outlyers off the island by select jitter weighted
! 2579: * by root distance. Continue voting as long as there are more
! 2580: * than sys_minclock survivors and the minimum select jitter is
! 2581: * greater than the maximum peer jitter. Stop if we are about to
! 2582: * discard a TRUE or PREFER peer, who of course has the
! 2583: * immunity idol.
! 2584: */
! 2585: seljitter = 0;
! 2586: while (1) {
! 2587: d = 1e9;
! 2588: e = -1e9;
! 2589: f = g = 0;
! 2590: k = 0;
! 2591: for (i = 0; i < nlist; i++) {
! 2592: if (error[i] < d)
! 2593: d = error[i];
! 2594: f = 0;
! 2595: if (nlist > 1) {
! 2596: for (j = 0; j < nlist; j++)
! 2597: f += DIFF(peer_list[j]->offset,
! 2598: peer_list[i]->offset);
! 2599: f = SQRT(f / (nlist - 1));
! 2600: }
! 2601: if (f * synch[i] > e) {
! 2602: g = f;
! 2603: e = f * synch[i];
! 2604: k = i;
! 2605: }
! 2606: }
! 2607: f = max(f, LOGTOD(sys_precision));
! 2608: if (nlist <= sys_minsane || nlist <= sys_minclock) {
! 2609: break;
! 2610:
! 2611: } else if (f <= d || peer_list[k]->flags &
! 2612: (FLAG_TRUE | FLAG_PREFER)) {
! 2613: seljitter = f;
! 2614: break;
! 2615: }
! 2616: #ifdef DEBUG
! 2617: if (debug > 2)
! 2618: printf(
! 2619: "select: drop %s seljit %.6f jit %.6f\n",
! 2620: ntoa(&peer_list[k]->srcadr), g, d);
! 2621: #endif
! 2622: if (nlist > sys_maxclock)
! 2623: peer_list[k]->new_status = CTL_PST_SEL_EXCESS;
! 2624: for (j = k + 1; j < nlist; j++) {
! 2625: peer_list[j - 1] = peer_list[j];
! 2626: synch[j - 1] = synch[j];
! 2627: error[j - 1] = error[j];
! 2628: }
! 2629: nlist--;
! 2630: }
! 2631:
! 2632: /*
! 2633: * What remains is a list usually not greater than sys_minclock
! 2634: * peers. Note that the head of the list is the system peer at
! 2635: * the lowest stratum and that unsynchronized peers cannot
! 2636: * survive this far.
! 2637: *
! 2638: * While at it, count the number of leap warning bits found.
! 2639: * This will be used later to vote the system leap warning bit.
! 2640: * If a leap warning bit is found on a reference clock, the vote
! 2641: * is always won.
! 2642: */
! 2643: leap_vote = 0;
! 2644: for (i = 0; i < nlist; i++) {
! 2645: peer = peer_list[i];
! 2646: peer->unreach = 0;
! 2647: peer->new_status = CTL_PST_SEL_SYNCCAND;
! 2648: sys_survivors++;
! 2649: if (peer->leap == LEAP_ADDSECOND) {
! 2650: if (peer->flags & FLAG_REFCLOCK)
! 2651: leap_vote = nlist;
! 2652: else
! 2653: leap_vote++;
! 2654: }
! 2655: if (peer->flags & FLAG_PREFER)
! 2656: sys_prefer = peer;
! 2657: }
! 2658:
! 2659: /*
! 2660: * Unless there are at least sys_misane survivors, leave the
! 2661: * building dark. Otherwise, do a clockhop dance. Ordinarily,
! 2662: * use the first survivor on the survivor list. However, if the
! 2663: * last selection is not first on the list, use it as long as
! 2664: * it doesn't get too old or too ugly.
! 2665: */
! 2666: if (nlist > 0 && nlist >= sys_minsane) {
! 2667: double x;
! 2668:
! 2669: typesystem = peer_list[0];
! 2670: if (osys_peer == NULL || osys_peer == typesystem) {
! 2671: sys_clockhop = 0;
! 2672: } else if ((x = fabs(typesystem->offset -
! 2673: osys_peer->offset)) < sys_mindisp) {
! 2674: if (sys_clockhop == 0)
! 2675: sys_clockhop = sys_mindisp;
! 2676: else
! 2677: sys_clockhop *= .5;
! 2678: #ifdef DEBUG
! 2679: if (debug)
! 2680: printf("select: clockhop %d %.6f %.6f\n",
! 2681: j, x, sys_clockhop);
! 2682: #endif
! 2683: if (fabs(x) < sys_clockhop)
! 2684: typesystem = osys_peer;
! 2685: else
! 2686: sys_clockhop = 0;
! 2687: } else {
! 2688: sys_clockhop = 0;
! 2689: }
! 2690: }
! 2691:
! 2692: /*
! 2693: * Mitigation rules of the game. We have the pick of the
! 2694: * litter in typesystem if any survivors are left. If
! 2695: * there is a prefer peer, use its offset and jitter.
! 2696: * Otherwise, use the combined offset and jitter of all kitters.
! 2697: */
! 2698: if (typesystem != NULL) {
! 2699: if (sys_prefer == NULL) {
! 2700: typesystem->new_status = CTL_PST_SEL_SYSPEER;
! 2701: clock_combine(peer_list, sys_survivors);
! 2702: sys_jitter = SQRT(SQUARE(sys_jitter) +
! 2703: SQUARE(seljitter));
! 2704: } else {
! 2705: typesystem = sys_prefer;
! 2706: sys_clockhop = 0;
! 2707: typesystem->new_status = CTL_PST_SEL_SYSPEER;
! 2708: sys_offset = typesystem->offset;
! 2709: sys_jitter = typesystem->jitter;
! 2710: }
! 2711: #ifdef DEBUG
! 2712: if (debug)
! 2713: printf("select: combine offset %.9f jitter %.9f\n",
! 2714: sys_offset, sys_jitter);
! 2715: #endif
! 2716: }
! 2717: #ifdef REFCLOCK
! 2718: /*
! 2719: * If a PPS driver is lit and the combined offset is less than
! 2720: * 0.4 s, select the driver as the PPS peer and use its offset
! 2721: * and jitter. However, if this is the atom driver, use it only
! 2722: * if there is a prefer peer or there are no survivors and none
! 2723: * are required.
! 2724: */
! 2725: if (typepps != NULL && fabs(sys_offset) < 0.4 &&
! 2726: (typepps->refclktype != REFCLK_ATOM_PPS ||
! 2727: (typepps->refclktype == REFCLK_ATOM_PPS && (sys_prefer !=
! 2728: NULL || (typesystem == NULL && sys_minsane == 0))))) {
! 2729: typesystem = typepps;
! 2730: sys_clockhop = 0;
! 2731: typesystem->new_status = CTL_PST_SEL_PPS;
! 2732: sys_offset = typesystem->offset;
! 2733: sys_jitter = typesystem->jitter;
! 2734: #ifdef DEBUG
! 2735: if (debug)
! 2736: printf("select: pps offset %.9f jitter %.9f\n",
! 2737: sys_offset, sys_jitter);
! 2738: #endif
! 2739: }
! 2740: #endif /* REFCLOCK */
! 2741:
! 2742: /*
! 2743: * If there are no survivors at this point, there is no
! 2744: * system peer. If so and this is an old update, keep the
! 2745: * current statistics, but do not update the clock.
! 2746: */
! 2747: if (typesystem == NULL) {
! 2748: if (osys_peer != NULL)
! 2749: report_event(EVNT_NOPEER, NULL, NULL);
! 2750: sys_peer = NULL;
! 2751: for (n = 0; n < NTP_HASH_SIZE; n++)
! 2752: for (peer = peer_hash[n]; peer != NULL; peer =
! 2753: peer->next)
! 2754: peer->status = peer->new_status;
! 2755: return;
! 2756: }
! 2757:
! 2758: /*
! 2759: * Do not use old data, as this may mess up the clock discipline
! 2760: * stability.
! 2761: */
! 2762: if (typesystem->epoch <= sys_epoch)
! 2763: return;
! 2764:
! 2765: /*
! 2766: * We have found the alpha male. Wind the clock.
! 2767: */
! 2768: if (osys_peer != typesystem)
! 2769: report_event(PEVNT_NEWPEER, typesystem, NULL);
! 2770: for (n = 0; n < NTP_HASH_SIZE; n++)
! 2771: for (peer = peer_hash[n]; peer != NULL; peer =
! 2772: peer->next)
! 2773: peer->status = peer->new_status;
! 2774: clock_update(typesystem);
! 2775: }
! 2776:
! 2777:
! 2778: /*
! 2779: * clock_combine - compute system offset and jitter from selected peers
! 2780: */
! 2781: static void
! 2782: clock_combine(
! 2783: struct peer **peers, /* survivor list */
! 2784: int npeers /* number of survivors */
! 2785: )
! 2786: {
! 2787: int i;
! 2788: double x, y, z, w;
! 2789:
! 2790: y = z = w = 0;
! 2791: for (i = 0; i < npeers; i++) {
! 2792: x = root_distance(peers[i]);
! 2793: y += 1. / x;
! 2794: z += peers[i]->offset / x;
! 2795: w += SQUARE(peers[i]->offset - peers[0]->offset) / x;
! 2796: }
! 2797: sys_offset = z / y;
! 2798: sys_jitter = SQRT(w / y);
! 2799: }
! 2800:
! 2801:
! 2802: /*
! 2803: * root_distance - compute synchronization distance from peer to root
! 2804: */
! 2805: static double
! 2806: root_distance(
! 2807: struct peer *peer /* peer structure pointer */
! 2808: )
! 2809: {
! 2810: double dtemp;
! 2811:
! 2812: /*
! 2813: * Careful squeak here. The value returned must be greater than
! 2814: * the minimum root dispersion in order to avoid clockhop with
! 2815: * highly precise reference clocks. Note that the root distance
! 2816: * cannot exceed the sys_maxdist, as this is the cutoff by the
! 2817: * selection algorithm.
! 2818: */
! 2819: dtemp = (peer->delay + peer->rootdelay) / 2 + peer->disp +
! 2820: peer->rootdisp + clock_phi * (current_time - peer->update) +
! 2821: peer->jitter;
! 2822: if (dtemp < sys_mindisp)
! 2823: dtemp = sys_mindisp;
! 2824: return (dtemp);
! 2825: }
! 2826:
! 2827:
! 2828: /*
! 2829: * peer_xmit - send packet for persistent association.
! 2830: */
! 2831: static void
! 2832: peer_xmit(
! 2833: struct peer *peer /* peer structure pointer */
! 2834: )
! 2835: {
! 2836: struct pkt xpkt; /* transmit packet */
! 2837: int sendlen, authlen;
! 2838: keyid_t xkeyid = 0; /* transmit key ID */
! 2839: l_fp xmt_tx, xmt_ty;
! 2840:
! 2841: if (!peer->dstadr) /* drop peers without interface */
! 2842: return;
! 2843:
! 2844: xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
! 2845: peer->hmode);
! 2846: xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
! 2847: xpkt.ppoll = peer->hpoll;
! 2848: xpkt.precision = sys_precision;
! 2849: xpkt.refid = sys_refid;
! 2850: xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
! 2851: xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
! 2852: HTONL_FP(&sys_reftime, &xpkt.reftime);
! 2853: HTONL_FP(&peer->rec, &xpkt.org);
! 2854: HTONL_FP(&peer->dst, &xpkt.rec);
! 2855:
! 2856: /*
! 2857: * If the received packet contains a MAC, the transmitted packet
! 2858: * is authenticated and contains a MAC. If not, the transmitted
! 2859: * packet is not authenticated.
! 2860: *
! 2861: * It is most important when autokey is in use that the local
! 2862: * interface IP address be known before the first packet is
! 2863: * sent. Otherwise, it is not possible to compute a correct MAC
! 2864: * the recipient will accept. Thus, the I/O semantics have to do
! 2865: * a little more work. In particular, the wildcard interface
! 2866: * might not be usable.
! 2867: */
! 2868: sendlen = LEN_PKT_NOMAC;
! 2869: #ifdef OPENSSL
! 2870: if (!(peer->flags & FLAG_SKEY) && peer->keyid == 0) {
! 2871: #else
! 2872: if (peer->keyid == 0) {
! 2873: #endif /* OPENSSL */
! 2874:
! 2875: /*
! 2876: * Transmit a-priori timestamps
! 2877: */
! 2878: get_systime(&xmt_tx);
! 2879: if (peer->flip == 0) { /* basic mode */
! 2880: peer->aorg = xmt_tx;
! 2881: HTONL_FP(&xmt_tx, &xpkt.xmt);
! 2882: } else { /* interleaved modes */
! 2883: if (peer->hmode == MODE_BROADCAST) { /* bcst */
! 2884: HTONL_FP(&xmt_tx, &xpkt.xmt);
! 2885: if (peer->flip > 0)
! 2886: HTONL_FP(&peer->borg,
! 2887: &xpkt.org);
! 2888: else
! 2889: HTONL_FP(&peer->aorg,
! 2890: &xpkt.org);
! 2891: } else { /* symmetric */
! 2892: if (peer->flip > 0)
! 2893: HTONL_FP(&peer->borg,
! 2894: &xpkt.xmt);
! 2895: else
! 2896: HTONL_FP(&peer->aorg,
! 2897: &xpkt.xmt);
! 2898: }
! 2899: }
! 2900: peer->t21_bytes = sendlen;
! 2901: sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
! 2902: &xpkt, sendlen);
! 2903: peer->sent++;
! 2904: peer->throttle += (1 << peer->minpoll) - 2;
! 2905:
! 2906: /*
! 2907: * Capture a-posteriori timestamps
! 2908: */
! 2909: get_systime(&xmt_ty);
! 2910: if (peer->flip != 0) { /* interleaved modes */
! 2911: if (peer->flip > 0)
! 2912: peer->aorg = xmt_ty;
! 2913: else
! 2914: peer->borg = xmt_ty;
! 2915: peer->flip = -peer->flip;
! 2916: }
! 2917: L_SUB(&xmt_ty, &xmt_tx);
! 2918: LFPTOD(&xmt_ty, peer->xleave);
! 2919: #ifdef DEBUG
! 2920: if (debug)
! 2921: printf("transmit: at %ld %s->%s mode %d len %d\n",
! 2922: current_time, peer->dstadr ?
! 2923: stoa(&peer->dstadr->sin) : "-",
! 2924: stoa(&peer->srcadr), peer->hmode, sendlen);
! 2925: #endif
! 2926: return;
! 2927: }
! 2928:
! 2929: /*
! 2930: * Authentication is enabled, so the transmitted packet must be
! 2931: * authenticated. If autokey is enabled, fuss with the various
! 2932: * modes; otherwise, symmetric key cryptography is used.
! 2933: */
! 2934: #ifdef OPENSSL
! 2935: if (peer->flags & FLAG_SKEY) {
! 2936: struct exten *exten; /* extension field */
! 2937:
! 2938: /*
! 2939: * The Public Key Dance (PKD): Cryptographic credentials
! 2940: * are contained in extension fields, each including a
! 2941: * 4-octet length/code word followed by a 4-octet
! 2942: * association ID and optional additional data. Optional
! 2943: * data includes a 4-octet data length field followed by
! 2944: * the data itself. Request messages are sent from a
! 2945: * configured association; response messages can be sent
! 2946: * from a configured association or can take the fast
! 2947: * path without ever matching an association. Response
! 2948: * messages have the same code as the request, but have
! 2949: * a response bit and possibly an error bit set. In this
! 2950: * implementation, a message may contain no more than
! 2951: * one command and one or more responses.
! 2952: *
! 2953: * Cryptographic session keys include both a public and
! 2954: * a private componet. Request and response messages
! 2955: * using extension fields are always sent with the
! 2956: * private component set to zero. Packets without
! 2957: * extension fields indlude the private component when
! 2958: * the session key is generated.
! 2959: */
! 2960: while (1) {
! 2961:
! 2962: /*
! 2963: * Allocate and initialize a keylist if not
! 2964: * already done. Then, use the list in inverse
! 2965: * order, discarding keys once used. Keep the
! 2966: * latest key around until the next one, so
! 2967: * clients can use client/server packets to
! 2968: * compute propagation delay.
! 2969: *
! 2970: * Note that once a key is used from the list,
! 2971: * it is retained in the key cache until the
! 2972: * next key is used. This is to allow a client
! 2973: * to retrieve the encrypted session key
! 2974: * identifier to verify authenticity.
! 2975: *
! 2976: * If for some reason a key is no longer in the
! 2977: * key cache, a birthday has happened or the key
! 2978: * has expired, so the pseudo-random sequence is
! 2979: * broken. In that case, purge the keylist and
! 2980: * regenerate it.
! 2981: */
! 2982: if (peer->keynumber == 0)
! 2983: make_keylist(peer, peer->dstadr);
! 2984: else
! 2985: peer->keynumber--;
! 2986: xkeyid = peer->keylist[peer->keynumber];
! 2987: if (authistrusted(xkeyid))
! 2988: break;
! 2989: else
! 2990: key_expire(peer);
! 2991: }
! 2992: peer->keyid = xkeyid;
! 2993: exten = NULL;
! 2994: switch (peer->hmode) {
! 2995:
! 2996: /*
! 2997: * In broadcast server mode the autokey values are
! 2998: * required by the broadcast clients. Push them when a
! 2999: * new keylist is generated; otherwise, push the
! 3000: * association message so the client can request them at
! 3001: * other times.
! 3002: */
! 3003: case MODE_BROADCAST:
! 3004: if (peer->flags & FLAG_ASSOC)
! 3005: exten = crypto_args(peer, CRYPTO_AUTO |
! 3006: CRYPTO_RESP, peer->associd, NULL);
! 3007: else
! 3008: exten = crypto_args(peer, CRYPTO_ASSOC |
! 3009: CRYPTO_RESP, peer->associd, NULL);
! 3010: break;
! 3011:
! 3012: /*
! 3013: * In symmetric modes the parameter, certificate,
! 3014: * identity, cookie and autokey exchanges are
! 3015: * required. The leapsecond exchange is optional. But, a
! 3016: * peer will not believe the other peer until the other
! 3017: * peer has synchronized, so the certificate exchange
! 3018: * might loop until then. If a peer finds a broken
! 3019: * autokey sequence, it uses the autokey exchange to
! 3020: * retrieve the autokey values. In any case, if a new
! 3021: * keylist is generated, the autokey values are pushed.
! 3022: */
! 3023: case MODE_ACTIVE:
! 3024: case MODE_PASSIVE:
! 3025:
! 3026: /*
! 3027: * Parameter, certificate and identity.
! 3028: */
! 3029: if (!peer->crypto)
! 3030: exten = crypto_args(peer, CRYPTO_ASSOC,
! 3031: peer->associd, sys_hostname);
! 3032: else if (!(peer->crypto & CRYPTO_FLAG_CERT))
! 3033: exten = crypto_args(peer, CRYPTO_CERT,
! 3034: peer->associd, peer->issuer);
! 3035: else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
! 3036: exten = crypto_args(peer,
! 3037: crypto_ident(peer), peer->associd,
! 3038: NULL);
! 3039:
! 3040: /*
! 3041: * Cookie and autokey. We request the cookie
! 3042: * only when the this peer and the other peer
! 3043: * are synchronized. But, this peer needs the
! 3044: * autokey values when the cookie is zero. Any
! 3045: * time we regenerate the key list, we offer the
! 3046: * autokey values without being asked. If for
! 3047: * some reason either peer finds a broken
! 3048: * autokey sequence, the autokey exchange is
! 3049: * used to retrieve the autokey values.
! 3050: */
! 3051: else if (sys_leap != LEAP_NOTINSYNC &&
! 3052: peer->leap != LEAP_NOTINSYNC &&
! 3053: !(peer->crypto & CRYPTO_FLAG_COOK))
! 3054: exten = crypto_args(peer, CRYPTO_COOK,
! 3055: peer->associd, NULL);
! 3056: else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
! 3057: exten = crypto_args(peer, CRYPTO_AUTO,
! 3058: peer->associd, NULL);
! 3059: else if (peer->flags & FLAG_ASSOC &&
! 3060: peer->crypto & CRYPTO_FLAG_SIGN)
! 3061: exten = crypto_args(peer, CRYPTO_AUTO |
! 3062: CRYPTO_RESP, peer->assoc, NULL);
! 3063:
! 3064: /*
! 3065: * Wait for clock sync, then sign the
! 3066: * certificate and retrieve the leapsecond
! 3067: * values.
! 3068: */
! 3069: else if (sys_leap == LEAP_NOTINSYNC)
! 3070: break;
! 3071:
! 3072: else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
! 3073: exten = crypto_args(peer, CRYPTO_SIGN,
! 3074: peer->associd, sys_hostname);
! 3075: else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
! 3076: exten = crypto_args(peer, CRYPTO_LEAP,
! 3077: peer->associd, NULL);
! 3078: break;
! 3079:
! 3080: /*
! 3081: * In client mode the parameter, certificate, identity,
! 3082: * cookie and sign exchanges are required. The
! 3083: * leapsecond exchange is optional. If broadcast client
! 3084: * mode the same exchanges are required, except that the
! 3085: * autokey exchange is substitutes for the cookie
! 3086: * exchange, since the cookie is always zero. If the
! 3087: * broadcast client finds a broken autokey sequence, it
! 3088: * uses the autokey exchange to retrieve the autokey
! 3089: * values.
! 3090: */
! 3091: case MODE_CLIENT:
! 3092:
! 3093: /*
! 3094: * Parameter, certificate and identity.
! 3095: */
! 3096: if (!peer->crypto)
! 3097: exten = crypto_args(peer, CRYPTO_ASSOC,
! 3098: peer->associd, sys_hostname);
! 3099: else if (!(peer->crypto & CRYPTO_FLAG_CERT))
! 3100: exten = crypto_args(peer, CRYPTO_CERT,
! 3101: peer->associd, peer->issuer);
! 3102: else if (!(peer->crypto & CRYPTO_FLAG_VRFY))
! 3103: exten = crypto_args(peer,
! 3104: crypto_ident(peer), peer->associd,
! 3105: NULL);
! 3106:
! 3107: /*
! 3108: * Cookie and autokey. These are requests, but
! 3109: * we use the peer association ID with autokey
! 3110: * rather than our own.
! 3111: */
! 3112: else if (!(peer->crypto & CRYPTO_FLAG_COOK))
! 3113: exten = crypto_args(peer, CRYPTO_COOK,
! 3114: peer->associd, NULL);
! 3115: else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
! 3116: exten = crypto_args(peer, CRYPTO_AUTO,
! 3117: peer->assoc, NULL);
! 3118:
! 3119: /*
! 3120: * Wait for clock sync, then sign the
! 3121: * certificate and retrieve the leapsecond
! 3122: * values.
! 3123: */
! 3124: else if (sys_leap == LEAP_NOTINSYNC)
! 3125: break;
! 3126:
! 3127: else if (!(peer->crypto & CRYPTO_FLAG_SIGN))
! 3128: exten = crypto_args(peer, CRYPTO_SIGN,
! 3129: peer->associd, sys_hostname);
! 3130: else if (!(peer->crypto & CRYPTO_FLAG_LEAP))
! 3131: exten = crypto_args(peer, CRYPTO_LEAP,
! 3132: peer->associd, NULL);
! 3133: break;
! 3134: }
! 3135:
! 3136: /*
! 3137: * Add a queued extension field if present. This is
! 3138: * always a request message, so the reply ID is already
! 3139: * in the message. If an error occurs, the error bit is
! 3140: * lit in the response.
! 3141: */
! 3142: if (peer->cmmd != NULL) {
! 3143: u_int32 temp32;
! 3144:
! 3145: temp32 = CRYPTO_RESP;
! 3146: peer->cmmd->opcode |= htonl(temp32);
! 3147: sendlen += crypto_xmit(peer, &xpkt, NULL,
! 3148: sendlen, peer->cmmd, 0);
! 3149: free(peer->cmmd);
! 3150: peer->cmmd = NULL;
! 3151: }
! 3152:
! 3153: /*
! 3154: * Add an extension field created above. All but the
! 3155: * autokey response message are request messages.
! 3156: */
! 3157: if (exten != NULL) {
! 3158: if (exten->opcode != 0)
! 3159: sendlen += crypto_xmit(peer, &xpkt,
! 3160: NULL, sendlen, exten, 0);
! 3161: free(exten);
! 3162: }
! 3163:
! 3164: /*
! 3165: * Calculate the next session key. Since extension
! 3166: * fields are present, the cookie value is zero.
! 3167: */
! 3168: if (sendlen > LEN_PKT_NOMAC) {
! 3169: session_key(&peer->dstadr->sin, &peer->srcadr,
! 3170: xkeyid, 0, 2);
! 3171: }
! 3172: }
! 3173: #endif /* OPENSSL */
! 3174:
! 3175: /*
! 3176: * Transmit a-priori timestamps
! 3177: */
! 3178: get_systime(&xmt_tx);
! 3179: if (peer->flip == 0) { /* basic mode */
! 3180: peer->aorg = xmt_tx;
! 3181: HTONL_FP(&xmt_tx, &xpkt.xmt);
! 3182: } else { /* interleaved modes */
! 3183: if (peer->hmode == MODE_BROADCAST) { /* bcst */
! 3184: HTONL_FP(&xmt_tx, &xpkt.xmt);
! 3185: if (peer->flip > 0)
! 3186: HTONL_FP(&peer->borg, &xpkt.org);
! 3187: else
! 3188: HTONL_FP(&peer->aorg, &xpkt.org);
! 3189: } else { /* symmetric */
! 3190: if (peer->flip > 0)
! 3191: HTONL_FP(&peer->borg, &xpkt.xmt);
! 3192: else
! 3193: HTONL_FP(&peer->aorg, &xpkt.xmt);
! 3194: }
! 3195: }
! 3196: xkeyid = peer->keyid;
! 3197: authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
! 3198: if (authlen == 0) {
! 3199: report_event(PEVNT_AUTH, peer, "no key");
! 3200: peer->flash |= TEST5; /* auth error */
! 3201: peer->badauth++;
! 3202: return;
! 3203: }
! 3204: sendlen += authlen;
! 3205: #ifdef OPENSSL
! 3206: if (xkeyid > NTP_MAXKEY)
! 3207: authtrust(xkeyid, 0);
! 3208: #endif /* OPENSSL */
! 3209: if (sendlen > sizeof(xpkt)) {
! 3210: msyslog(LOG_ERR, "proto: buffer overflow %u", sendlen);
! 3211: exit (-1);
! 3212: }
! 3213: peer->t21_bytes = sendlen;
! 3214: sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
! 3215: sendlen);
! 3216: peer->sent++;
! 3217: peer->throttle += (1 << peer->minpoll) - 2;
! 3218:
! 3219: /*
! 3220: * Capture a-posteriori timestamps
! 3221: */
! 3222: get_systime(&xmt_ty);
! 3223: if (peer->flip != 0) { /* interleaved modes */
! 3224: if (peer->flip > 0)
! 3225: peer->aorg = xmt_ty;
! 3226: else
! 3227: peer->borg = xmt_ty;
! 3228: peer->flip = -peer->flip;
! 3229: }
! 3230: L_SUB(&xmt_ty, &xmt_tx);
! 3231: LFPTOD(&xmt_ty, peer->xleave);
! 3232: #ifdef OPENSSL
! 3233: #ifdef DEBUG
! 3234: if (debug)
! 3235: printf("transmit: at %ld %s->%s mode %d keyid %08x len %d index %d\n",
! 3236: current_time, peer->dstadr ?
! 3237: ntoa(&peer->dstadr->sin) : "-",
! 3238: ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
! 3239: peer->keynumber);
! 3240: #endif
! 3241: #else /* OPENSSL */
! 3242: #ifdef DEBUG
! 3243: if (debug)
! 3244: printf("transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
! 3245: current_time, peer->dstadr ?
! 3246: ntoa(&peer->dstadr->sin) : "-",
! 3247: ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen);
! 3248: #endif
! 3249: #endif /* OPENSSL */
! 3250: }
! 3251:
! 3252:
! 3253: /*
! 3254: * fast_xmit - Send packet for nonpersistent association. Note that
! 3255: * neither the source or destination can be a broadcast address.
! 3256: */
! 3257: static void
! 3258: fast_xmit(
! 3259: struct recvbuf *rbufp, /* receive packet pointer */
! 3260: int xmode, /* receive mode */
! 3261: keyid_t xkeyid, /* transmit key ID */
! 3262: int flags /* restrict mask */
! 3263: )
! 3264: {
! 3265: struct pkt xpkt; /* transmit packet structure */
! 3266: struct pkt *rpkt; /* receive packet structure */
! 3267: l_fp xmt_tx, xmt_ty;
! 3268: int sendlen;
! 3269: #ifdef OPENSSL
! 3270: u_int32 temp32;
! 3271: #endif
! 3272:
! 3273: /*
! 3274: * Initialize transmit packet header fields from the receive
! 3275: * buffer provided. We leave the fields intact as received, but
! 3276: * set the peer poll at the maximum of the receive peer poll and
! 3277: * the system minimum poll (ntp_minpoll). This is for KoD rate
! 3278: * control and not strictly specification compliant, but doesn't
! 3279: * break anything.
! 3280: *
! 3281: * If the gazinta was from a multicast address, the gazoutta
! 3282: * must go out another way.
! 3283: */
! 3284: rpkt = &rbufp->recv_pkt;
! 3285: if (rbufp->dstadr->flags & INT_MCASTOPEN)
! 3286: rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
! 3287:
! 3288: /*
! 3289: * If this is a kiss-o'-death (KoD) packet, show leap
! 3290: * unsynchronized, stratum zero, reference ID the four-character
! 3291: * kiss code and system root delay. Note we don't reveal the
! 3292: * local time, so these packets can't be used for
! 3293: * synchronization.
! 3294: */
! 3295: if (flags & RES_KOD) {
! 3296: sys_kodsent++;
! 3297: xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
! 3298: PKT_VERSION(rpkt->li_vn_mode), xmode);
! 3299: xpkt.stratum = STRATUM_PKT_UNSPEC;
! 3300: xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
! 3301: memcpy(&xpkt.refid, "RATE", 4);
! 3302: xpkt.org = rpkt->xmt;
! 3303: xpkt.rec = rpkt->xmt;
! 3304: xpkt.xmt = rpkt->xmt;
! 3305:
! 3306: /*
! 3307: * This is a normal packet. Use the system variables.
! 3308: */
! 3309: } else {
! 3310: xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
! 3311: PKT_VERSION(rpkt->li_vn_mode), xmode);
! 3312: xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
! 3313: xpkt.ppoll = max(rpkt->ppoll, ntp_minpoll);
! 3314: xpkt.precision = sys_precision;
! 3315: xpkt.refid = sys_refid;
! 3316: xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
! 3317: xpkt.rootdisp = HTONS_FP(DTOUFP(sys_rootdisp));
! 3318: HTONL_FP(&sys_reftime, &xpkt.reftime);
! 3319: xpkt.org = rpkt->xmt;
! 3320: HTONL_FP(&rbufp->recv_time, &xpkt.rec);
! 3321: get_systime(&xmt_tx);
! 3322: HTONL_FP(&xmt_tx, &xpkt.xmt);
! 3323: }
! 3324:
! 3325: #ifdef HAVE_NTP_SIGND
! 3326: if (flags & RES_MSSNTP) {
! 3327: send_via_ntp_signd(rbufp, xmode, xkeyid, flags, &xpkt);
! 3328: return;
! 3329: }
! 3330: #endif /* HAVE_NTP_SIGND */
! 3331:
! 3332: /*
! 3333: * If the received packet contains a MAC, the transmitted packet
! 3334: * is authenticated and contains a MAC. If not, the transmitted
! 3335: * packet is not authenticated.
! 3336: */
! 3337: sendlen = LEN_PKT_NOMAC;
! 3338: if (rbufp->recv_length == sendlen) {
! 3339: sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
! 3340: sendlen);
! 3341: #ifdef DEBUG
! 3342: if (debug)
! 3343: printf(
! 3344: "transmit: at %ld %s->%s mode %d len %d\n",
! 3345: current_time, stoa(&rbufp->dstadr->sin),
! 3346: stoa(&rbufp->recv_srcadr), xmode, sendlen);
! 3347: #endif
! 3348: return;
! 3349: }
! 3350:
! 3351: /*
! 3352: * The received packet contains a MAC, so the transmitted packet
! 3353: * must be authenticated. For symmetric key cryptography, use
! 3354: * the predefined and trusted symmetric keys to generate the
! 3355: * cryptosum. For autokey cryptography, use the server private
! 3356: * value to generate the cookie, which is unique for every
! 3357: * source-destination-key ID combination.
! 3358: */
! 3359: #ifdef OPENSSL
! 3360: if (xkeyid > NTP_MAXKEY) {
! 3361: keyid_t cookie;
! 3362:
! 3363: /*
! 3364: * The only way to get here is a reply to a legitimate
! 3365: * client request message, so the mode must be
! 3366: * MODE_SERVER. If an extension field is present, there
! 3367: * can be only one and that must be a command. Do what
! 3368: * needs, but with private value of zero so the poor
! 3369: * jerk can decode it. If no extension field is present,
! 3370: * use the cookie to generate the session key.
! 3371: */
! 3372: cookie = session_key(&rbufp->recv_srcadr,
! 3373: &rbufp->dstadr->sin, 0, sys_private, 0);
! 3374: if (rbufp->recv_length > sendlen + MAX_MAC_LEN) {
! 3375: session_key(&rbufp->dstadr->sin,
! 3376: &rbufp->recv_srcadr, xkeyid, 0, 2);
! 3377: temp32 = CRYPTO_RESP;
! 3378: rpkt->exten[0] |= htonl(temp32);
! 3379: sendlen += crypto_xmit(NULL, &xpkt, rbufp,
! 3380: sendlen, (struct exten *)rpkt->exten,
! 3381: cookie);
! 3382: } else {
! 3383: session_key(&rbufp->dstadr->sin,
! 3384: &rbufp->recv_srcadr, xkeyid, cookie, 2);
! 3385: }
! 3386: }
! 3387: #endif /* OPENSSL */
! 3388: get_systime(&xmt_tx);
! 3389: sendlen += authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
! 3390: #ifdef OPENSSL
! 3391: if (xkeyid > NTP_MAXKEY)
! 3392: authtrust(xkeyid, 0);
! 3393: #endif /* OPENSSL */
! 3394: sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
! 3395: get_systime(&xmt_ty);
! 3396: L_SUB(&xmt_ty, &xmt_tx);
! 3397: sys_authdelay = xmt_ty;
! 3398: #ifdef DEBUG
! 3399: if (debug)
! 3400: printf(
! 3401: "transmit: at %ld %s->%s mode %d keyid %08x len %d\n",
! 3402: current_time, ntoa(&rbufp->dstadr->sin),
! 3403: ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen);
! 3404: #endif
! 3405: }
! 3406:
! 3407:
! 3408: #ifdef OPENSSL
! 3409: /*
! 3410: * key_expire - purge the key list
! 3411: */
! 3412: void
! 3413: key_expire(
! 3414: struct peer *peer /* peer structure pointer */
! 3415: )
! 3416: {
! 3417: int i;
! 3418:
! 3419: if (peer->keylist != NULL) {
! 3420: for (i = 0; i <= peer->keynumber; i++)
! 3421: authtrust(peer->keylist[i], 0);
! 3422: free(peer->keylist);
! 3423: peer->keylist = NULL;
! 3424: }
! 3425: value_free(&peer->sndval);
! 3426: peer->keynumber = 0;
! 3427: peer->flags &= ~FLAG_ASSOC;
! 3428: #ifdef DEBUG
! 3429: if (debug)
! 3430: printf("key_expire: at %lu associd %d\n", current_time,
! 3431: peer->associd);
! 3432: #endif
! 3433: }
! 3434: #endif /* OPENSSL */
! 3435:
! 3436:
! 3437: /*
! 3438: * local_refid(peer) - check peer refid to avoid selecting peers
! 3439: * currently synced to this ntpd.
! 3440: */
! 3441: static int
! 3442: local_refid(
! 3443: struct peer * p
! 3444: )
! 3445: {
! 3446: endpt * unicast_ep;
! 3447:
! 3448: if (p->dstadr != NULL && !(INT_MCASTIF & p->dstadr->flags))
! 3449: unicast_ep = p->dstadr;
! 3450: else
! 3451: unicast_ep = findinterface(&p->srcadr);
! 3452:
! 3453: if (unicast_ep != NULL && p->refid == unicast_ep->addr_refid)
! 3454: return TRUE;
! 3455: else
! 3456: return FALSE;
! 3457: }
! 3458:
! 3459:
! 3460: /*
! 3461: * Determine if the peer is unfit for synchronization
! 3462: *
! 3463: * A peer is unfit for synchronization if
! 3464: * > TEST10 bad leap or stratum below floor or at or above ceiling
! 3465: * > TEST11 root distance exceeded for remote peer
! 3466: * > TEST12 a direct or indirect synchronization loop would form
! 3467: * > TEST13 unreachable or noselect
! 3468: */
! 3469: int /* FALSE if fit, TRUE if unfit */
! 3470: peer_unfit(
! 3471: struct peer *peer /* peer structure pointer */
! 3472: )
! 3473: {
! 3474: int rval = 0;
! 3475:
! 3476: /*
! 3477: * A stratum error occurs if (1) the server has never been
! 3478: * synchronized, (2) the server stratum is below the floor or
! 3479: * greater than or equal to the ceiling.
! 3480: */
! 3481: if (peer->leap == LEAP_NOTINSYNC || peer->stratum < sys_floor ||
! 3482: peer->stratum >= sys_ceiling)
! 3483: rval |= TEST10; /* bad synch or stratum */
! 3484:
! 3485: /*
! 3486: * A distance error for a remote peer occurs if the root
! 3487: * distance is greater than or equal to the distance threshold
! 3488: * plus the increment due to one host poll interval.
! 3489: */
! 3490: if (!(peer->flags & FLAG_REFCLOCK) && root_distance(peer) >=
! 3491: sys_maxdist + clock_phi * ULOGTOD(peer->hpoll))
! 3492: rval |= TEST11; /* distance exceeded */
! 3493:
! 3494: /*
! 3495: * A loop error occurs if the remote peer is synchronized to the
! 3496: * local peer or if the remote peer is synchronized to the same
! 3497: * server as the local peer but only if the remote peer is
! 3498: * neither a reference clock nor an orphan.
! 3499: */
! 3500: if (peer->stratum > 1 && local_refid(peer))
! 3501: rval |= TEST12; /* synchronization loop */
! 3502:
! 3503: /*
! 3504: * An unreachable error occurs if the server is unreachable or
! 3505: * the noselect bit is set.
! 3506: */
! 3507: if (!peer->reach || (peer->flags & FLAG_NOSELECT))
! 3508: rval |= TEST13; /* unreachable */
! 3509:
! 3510: peer->flash &= ~PEER_TEST_MASK;
! 3511: peer->flash |= rval;
! 3512: return (rval);
! 3513: }
! 3514:
! 3515:
! 3516: /*
! 3517: * Find the precision of this particular machine
! 3518: */
! 3519: #define MINSTEP 100e-9 /* minimum clock increment (s) */
! 3520: #define MAXSTEP 20e-3 /* maximum clock increment (s) */
! 3521: #define MINLOOPS 5 /* minimum number of step samples */
! 3522:
! 3523: /*
! 3524: * This routine measures the system precision defined as the minimum of
! 3525: * a sequence of differences between successive readings of the system
! 3526: * clock. However, if a difference is less than MINSTEP, the clock has
! 3527: * been read more than once during a clock tick and the difference is
! 3528: * ignored. We set MINSTEP greater than zero in case something happens
! 3529: * like a cache miss.
! 3530: */
! 3531: int
! 3532: default_get_precision(void)
! 3533: {
! 3534: l_fp val; /* current seconds fraction */
! 3535: l_fp last; /* last seconds fraction */
! 3536: l_fp diff; /* difference */
! 3537: double tick; /* computed tick value */
! 3538: double dtemp; /* scratch */
! 3539: int i; /* log2 precision */
! 3540:
! 3541: /*
! 3542: * Loop to find precision value in seconds.
! 3543: */
! 3544: tick = MAXSTEP;
! 3545: i = 0;
! 3546: get_systime(&last);
! 3547: while (1) {
! 3548: get_systime(&val);
! 3549: diff = val;
! 3550: L_SUB(&diff, &last);
! 3551: last = val;
! 3552: LFPTOD(&diff, dtemp);
! 3553: if (dtemp < MINSTEP)
! 3554: continue;
! 3555:
! 3556: if (dtemp < tick)
! 3557: tick = dtemp;
! 3558: if (++i >= MINLOOPS)
! 3559: break;
! 3560: }
! 3561: sys_tick = tick;
! 3562:
! 3563: /*
! 3564: * Find the nearest power of two.
! 3565: */
! 3566: msyslog(LOG_NOTICE, "proto: precision = %.3f usec", tick * 1e6);
! 3567: for (i = 0; tick <= 1; i++)
! 3568: tick *= 2;
! 3569: if (tick - 1 > 1 - tick / 2)
! 3570: i--;
! 3571: return (-i);
! 3572: }
! 3573:
! 3574:
! 3575: /*
! 3576: * init_proto - initialize the protocol module's data
! 3577: */
! 3578: void
! 3579: init_proto(void)
! 3580: {
! 3581: l_fp dummy;
! 3582: int i;
! 3583:
! 3584: /*
! 3585: * Fill in the sys_* stuff. Default is don't listen to
! 3586: * broadcasting, require authentication.
! 3587: */
! 3588: sys_leap = LEAP_NOTINSYNC;
! 3589: sys_stratum = STRATUM_UNSPEC;
! 3590: memcpy(&sys_refid, "INIT", 4);
! 3591: sys_peer = NULL;
! 3592: sys_rootdelay = 0;
! 3593: sys_rootdisp = 0;
! 3594: L_CLR(&sys_reftime);
! 3595: sys_jitter = 0;
! 3596: sys_precision = (s_char)default_get_precision();
! 3597: get_systime(&dummy);
! 3598: sys_survivors = 0;
! 3599: sys_manycastserver = 0;
! 3600: sys_bclient = 0;
! 3601: sys_bdelay = 0;
! 3602: sys_authenticate = 1;
! 3603: sys_stattime = current_time;
! 3604: proto_clr_stats();
! 3605: for (i = 0; i < MAX_TTL; i++) {
! 3606: sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
! 3607: sys_ttlmax = i;
! 3608: }
! 3609: pps_enable = 0;
! 3610: stats_control = 1;
! 3611: }
! 3612:
! 3613:
! 3614: /*
! 3615: * proto_config - configure the protocol module
! 3616: */
! 3617: void
! 3618: proto_config(
! 3619: int item,
! 3620: u_long value,
! 3621: double dvalue,
! 3622: sockaddr_u *svalue
! 3623: )
! 3624: {
! 3625: /*
! 3626: * Figure out what he wants to change, then do it
! 3627: */
! 3628: DPRINTF(2, ("proto_config: code %d value %lu dvalue %lf\n",
! 3629: item, value, dvalue));
! 3630:
! 3631: switch (item) {
! 3632:
! 3633: /*
! 3634: * enable and disable commands - arguments are Boolean.
! 3635: */
! 3636: case PROTO_AUTHENTICATE: /* authentication (auth) */
! 3637: sys_authenticate = value;
! 3638: break;
! 3639:
! 3640: case PROTO_BROADCLIENT: /* broadcast client (bclient) */
! 3641: sys_bclient = (int)value;
! 3642: if (sys_bclient == 0)
! 3643: io_unsetbclient();
! 3644: else
! 3645: io_setbclient();
! 3646: break;
! 3647:
! 3648: #ifdef REFCLOCK
! 3649: case PROTO_CAL: /* refclock calibrate (calibrate) */
! 3650: cal_enable = value;
! 3651: break;
! 3652: #endif /* REFCLOCK */
! 3653:
! 3654: case PROTO_KERNEL: /* kernel discipline (kernel) */
! 3655: kern_enable = value;
! 3656: break;
! 3657:
! 3658: case PROTO_MONITOR: /* monitoring (monitor) */
! 3659: if (value)
! 3660: mon_start(MON_ON);
! 3661: else
! 3662: mon_stop(MON_ON);
! 3663: break;
! 3664:
! 3665: case PROTO_NTP: /* NTP discipline (ntp) */
! 3666: ntp_enable = value;
! 3667: break;
! 3668:
! 3669: case PROTO_PPS: /* PPS discipline (pps) */
! 3670: pps_enable = value;
! 3671: break;
! 3672:
! 3673: case PROTO_FILEGEN: /* statistics (stats) */
! 3674: stats_control = value;
! 3675: break;
! 3676:
! 3677: /*
! 3678: * tos command - arguments are double, sometimes cast to int
! 3679: */
! 3680: case PROTO_BEACON: /* manycast beacon (beacon) */
! 3681: sys_beacon = (int)dvalue;
! 3682: break;
! 3683:
! 3684: case PROTO_BROADDELAY: /* default broadcast delay (bdelay) */
! 3685: sys_bdelay = dvalue;
! 3686: break;
! 3687:
! 3688: case PROTO_CEILING: /* stratum ceiling (ceiling) */
! 3689: sys_ceiling = (int)dvalue;
! 3690: break;
! 3691:
! 3692: case PROTO_COHORT: /* cohort switch (cohort) */
! 3693: sys_cohort = (int)dvalue;
! 3694: break;
! 3695:
! 3696: case PROTO_FLOOR: /* stratum floor (floor) */
! 3697: sys_floor = (int)dvalue;
! 3698: break;
! 3699:
! 3700: case PROTO_MAXCLOCK: /* maximum candidates (maxclock) */
! 3701: sys_maxclock = (int)dvalue;
! 3702: break;
! 3703:
! 3704: case PROTO_MAXDIST: /* select threshold (maxdist) */
! 3705: sys_maxdist = dvalue;
! 3706: break;
! 3707:
! 3708: case PROTO_CALLDELAY: /* modem call delay (mdelay) */
! 3709: break; /* NOT USED */
! 3710:
! 3711: case PROTO_MINCLOCK: /* minimum candidates (minclock) */
! 3712: sys_minclock = (int)dvalue;
! 3713: break;
! 3714:
! 3715: case PROTO_MINDISP: /* minimum distance (mindist) */
! 3716: sys_mindisp = dvalue;
! 3717: break;
! 3718:
! 3719: case PROTO_MINSANE: /* minimum survivors (minsane) */
! 3720: sys_minsane = (int)dvalue;
! 3721: break;
! 3722:
! 3723: case PROTO_ORPHAN: /* orphan stratum (orphan) */
! 3724: sys_orphan = (int)dvalue;
! 3725: break;
! 3726:
! 3727: case PROTO_ADJ: /* tick increment (tick) */
! 3728: sys_tick = dvalue;
! 3729: break;
! 3730:
! 3731: /*
! 3732: * Miscellaneous commands
! 3733: */
! 3734: case PROTO_MULTICAST_ADD: /* add group address */
! 3735: if (svalue != NULL)
! 3736: io_multicast_add(svalue);
! 3737: sys_bclient = 1;
! 3738: break;
! 3739:
! 3740: case PROTO_MULTICAST_DEL: /* delete group address */
! 3741: if (svalue != NULL)
! 3742: io_multicast_del(svalue);
! 3743: break;
! 3744:
! 3745: default:
! 3746: msyslog(LOG_NOTICE,
! 3747: "proto: unsupported option %d", item);
! 3748: }
! 3749: }
! 3750:
! 3751:
! 3752: /*
! 3753: * proto_clr_stats - clear protocol stat counters
! 3754: */
! 3755: void
! 3756: proto_clr_stats(void)
! 3757: {
! 3758: sys_stattime = current_time;
! 3759: sys_received = 0;
! 3760: sys_processed = 0;
! 3761: sys_newversion = 0;
! 3762: sys_oldversion = 0;
! 3763: sys_declined = 0;
! 3764: sys_restricted = 0;
! 3765: sys_badlength = 0;
! 3766: sys_badauth = 0;
! 3767: sys_limitrejected = 0;
! 3768: }
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>