home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-385-Vol-1of3.iso / x / xntp3.zip / xntpd / ntp_proto.c < prev    next >
C/C++ Source or Header  |  1992-08-15  |  52KB  |  2,141 lines

  1. /*
  2.  * ntp_proto.c - NTP version 3 protocol machinery
  3.  */
  4. #include <stdio.h>
  5. #include <sys/types.h>
  6. #include <sys/socket.h>
  7. #include <netinet/in.h>
  8.  
  9. #include "ntp_syslog.h"
  10. #include "ntp_fp.h"
  11. #include "ntp.h"
  12.  
  13. /*
  14.  * System variables are declared here.  See Section 3.2 of
  15.  * the specification.
  16.  */
  17. u_char sys_leap;        /* system leap indicator */
  18. u_char sys_stratum;        /* stratum of system */
  19. s_char sys_precision;        /* local clock precision */
  20. s_fp sys_rootdelay;        /* distance to current sync source */
  21. u_fp sys_rootdispersion;    /* dispersion of system clock */
  22. u_long sys_refid;        /* reference source for local clock */
  23. l_fp sys_offset;        /* combined offset from clock_select */
  24. u_fp sys_maxd;            /* dispersion of selected peer */
  25. l_fp sys_reftime;        /* time we were last updated */
  26. l_fp sys_refskew;        /* accumulated skew since last update */
  27. struct peer *sys_peer;        /* our current peer */
  28. int sys_poll;            /* log2 of desired system poll interval */
  29. long sys_clock;            /* second part of current time */
  30. long sys_lastselect;        /* sys_clock at last synch-dist update */
  31.  
  32. /*
  33.  * Non-specified system state variables.
  34.  */
  35. int sys_bclient;        /* we set our time to broadcasts */
  36. u_long sys_bdelay;        /* default delay to use for broadcasting */
  37. int sys_authenticate;        /* authenticate time used for syncing */
  38.  
  39. u_long sys_authdelay;        /* ts fraction, time it takes for encrypt() */
  40.  
  41. /*
  42.  * Statistics counters
  43.  */
  44. u_long sys_stattime;        /* time when we started recording */
  45. u_long sys_badstratum;        /* packets with invalid incoming stratum */
  46. u_long sys_oldversionpkt;    /* old version packets received */
  47. u_long sys_newversionpkt;    /* new version packets received */
  48. u_long sys_unknownversion;    /* don't know version packets */
  49. u_long sys_badlength;        /* packets with bad length */
  50. u_long sys_processed;        /* packets processed */
  51. u_long sys_badauth;        /* packets dropped because of authorization */
  52. u_long sys_wanderhold;        /* sys_peer held to prevent wandering */
  53.  
  54. /*
  55.  * Imported from ntp_timer.c
  56.  */
  57. extern u_long current_time;
  58. extern struct event timerqueue[];
  59.  
  60. /*
  61.  * Imported from ntp_io.c
  62.  */
  63. extern struct interface *any_interface;
  64.  
  65. /*
  66.  * Imported from ntp_loopfilter.c
  67.  */
  68. extern int pps_control;
  69. extern u_long pps_update;
  70.  
  71. /*
  72.  * The peer hash table.  Imported from ntp_peer.c
  73.  */
  74. extern struct peer *peer_hash[];
  75. extern int peer_hash_count[];
  76.  
  77. /*
  78.  * debug flag
  79.  */
  80. extern int debug;
  81.  
  82.  
  83. /*
  84.  * transmit - Transmit Procedure.  See Section 3.4.1 of the specification.
  85.  */
  86. void
  87. transmit(peer)
  88.     register struct peer *peer;
  89. {
  90.     struct pkt xpkt;    /* packet to send */
  91.     u_long peer_timer;
  92.     extern void unpeer();
  93.     void clock_select();
  94.     void clock_filter();
  95.     void clear();
  96.     extern void sendpkt();
  97.     extern void get_systime();
  98.     extern void auth1crypt();
  99.     extern int auth2crypt();
  100.     extern int authhavekey();
  101.     extern char *ntoa();
  102.  
  103.     if (peer->hmode != MODE_BCLIENT) {
  104.         u_long xkeyid;
  105.  
  106.         /*
  107.          * Figure out which keyid to include in the packet
  108.          */
  109.         if ((peer->flags & FLAG_AUTHENABLE)
  110.             && (peer->flags & (FLAG_CONFIG|FLAG_AUTHENTIC))
  111.             && authhavekey(peer->keyid)) {
  112.             xkeyid = peer->keyid;
  113.         } else {
  114.             xkeyid = 0;
  115.         }
  116.  
  117.         /*
  118.          * Make up a packet to send.
  119.          */
  120.         xpkt.li_vn_mode
  121.             = PKT_LI_VN_MODE(sys_leap, peer->version, peer->hmode);
  122.         xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
  123.         if (peer->reach == 0)
  124.             xpkt.ppoll = NTP_MINPOLL;
  125.         else
  126.             xpkt.ppoll = peer->hpoll;
  127.         xpkt.precision = sys_precision;
  128.         xpkt.rootdelay = HTONS_FP(sys_rootdelay);
  129.         xpkt.rootdispersion =
  130.             HTONS_FP(sys_rootdispersion +
  131.                  (FP_SECOND >> (-(int)sys_precision)) +
  132.                  LFPTOFP(&sys_refskew));
  133.         xpkt.refid = sys_refid;
  134.         HTONL_FP(&sys_reftime, &xpkt.reftime);
  135.         HTONL_FP(&peer->org, &xpkt.org);
  136.         HTONL_FP(&peer->rec, &xpkt.rec);
  137.  
  138.         /*
  139.          * Decide whether to authenticate or not.  If so, call encrypt()
  140.          * to fill in the rest of the frame.  If not, just add in the
  141.          * xmt timestamp and send it quick.
  142.          */
  143.         if (peer->flags & FLAG_AUTHENABLE) {
  144.                 int sendlen;
  145.  
  146.             xpkt.keyid = htonl(xkeyid);
  147.             auth1crypt(xkeyid, (u_long *)&xpkt, LEN_PKT_NOMAC);
  148.             get_systime(&peer->xmt);
  149.             L_ADDUF(&peer->xmt, sys_authdelay);
  150.             HTONL_FP(&peer->xmt, &xpkt.xmt);
  151.             sendlen = auth2crypt(xkeyid, (u_long *)&xpkt,
  152.                          LEN_PKT_NOMAC);
  153.             sendpkt(&(peer->srcadr), peer->dstadr, &xpkt,
  154.                 sendlen + LEN_PKT_NOMAC);
  155. #ifdef DEBUG
  156.             if (debug > 1)
  157.                 printf("transmit auth to %s\n",
  158.                     ntoa(&(peer->srcadr)));
  159. #endif
  160.             peer->sent++;
  161.         } else {
  162.             /*
  163.              * Get xmt timestamp, then send it without mac field
  164.              */
  165.             get_systime(&(peer->xmt));
  166.             HTONL_FP(&peer->xmt, &xpkt.xmt);
  167.             sendpkt(&(peer->srcadr), peer->dstadr, &xpkt,
  168.                 LEN_PKT_NOMAC);
  169. #ifdef DEBUG
  170.             if (debug > 1)
  171.                 printf("transmit to %s\n", ntoa(&(peer->srcadr)));
  172. #endif
  173.             peer->sent++;
  174.         }
  175.     }
  176.  
  177.     if (peer->hmode != MODE_BROADCAST) {
  178.         u_char opeer_reach;
  179.         /*
  180.          * Determine reachability and diddle things if we
  181.          * haven't heard from the host for a while.
  182.          */
  183.         opeer_reach = peer->reach;
  184.         peer->reach <<= 1;
  185.         if (peer->reach == 0) {
  186.             if (opeer_reach != 0)
  187.                 report_event(EVNT_UNREACH, peer);
  188.             /*
  189.              * Clear this guy out.  No need to redo clock
  190.              * selection since by now this guy won't be a player
  191.              */
  192.             if (peer->flags & FLAG_CONFIG) {
  193.                 if (opeer_reach != 0) {
  194.                     clear(peer);
  195.                     peer->timereachable = current_time;
  196.                 }
  197.             } else {
  198.                 unpeer(peer);
  199.                 return;
  200.             }
  201.  
  202.             /*
  203.              * While we have a chance, if our system peer
  204.              * is zero or his stratum is greater than the
  205.              * last known stratum of this guy, make sure
  206.              * peer->hpoll is clamped to the minimum before
  207.              * resetting the timer.
  208.              * If the peer has been unreachable for a while
  209.              * and we have a system peer who is at least his
  210.              * equal, we may want to ramp his polling interval
  211.              * up to avoid the useless traffic.
  212.              */
  213.             if (sys_peer == 0
  214.                 || sys_peer->stratum > peer->stratum) {
  215.                 peer->hpoll = NTP_MINPOLL;
  216.                 peer->unreach = 0;
  217.             } else {
  218.                 if (peer->unreach < 16) {
  219.                     peer->unreach++;
  220.                     peer->hpoll = NTP_MINPOLL;
  221.                 } else if (peer->hpoll < NTP_MAXPOLL) {
  222.                     peer->hpoll++;
  223.                     peer->ppoll = peer->hpoll;
  224.                 }
  225.             }
  226.  
  227.         /*
  228.          * Update reachability and poll variables
  229.          */
  230.         } else if ((opeer_reach & 3) == 0) {
  231.  
  232.             l_fp off;
  233.  
  234.             if (peer->valid > 0)
  235.                 peer->valid--;
  236.             if (peer->hpoll > NTP_MINPOLL)
  237.                 peer->hpoll--;
  238.             off.l_ui = off.l_uf = 0;
  239.             clock_filter(peer, &off, 0, NTP_MAXDISPERSE);
  240.             if (peer->flags & FLAG_SYSPEER)
  241.                 clock_select(peer);
  242.         } else {
  243.             if (peer->valid < NTP_SHIFT) {
  244.                 peer->valid++;
  245.             } else {
  246.                 if (peer->hpoll < NTP_MAXPOLL)
  247.                     peer->hpoll++;
  248.             }
  249.         }
  250.     }
  251.  
  252.     /*
  253.      * Finally, update the host-poll variable.
  254.      */
  255.     if ((peer->flags & FLAG_SYSPEER) && peer->hpoll > sys_poll) {
  256.         /* clamp it */
  257.         peer->hpoll = sys_poll;
  258.     }
  259.     if ((peer->flags & FLAG_MINPOLL)
  260.         || peer->hmode == MODE_BROADCAST || peer->hmode == MODE_BCLIENT) {
  261.         /* clamp it */
  262.         peer->hpoll = NTP_MINPOLL;
  263.     }
  264.  
  265.     /*
  266.      * Arrange for our next time out.  hpoll will be less than
  267.      * NTP_MAXPOLL for sure.
  268.      */
  269.     if (peer->event_timer.next != 0)
  270.         /*
  271.          * Oops, someone did already.
  272.          */
  273.         TIMER_DEQUEUE(&peer->event_timer);
  274.     peer_timer = 1 << max(min(peer->ppoll, peer->hpoll), NTP_MINPOLL);
  275.     peer->event_timer.event_time = current_time + peer_timer;
  276.     TIMER_ENQUEUE(timerqueue, &peer->event_timer);
  277. }
  278.  
  279. #if 0
  280. static void
  281. ct_die(after)
  282. {
  283.     syslog(LOG_ERR, "timers garbled (%s)", after?"after":"before");
  284.     abort();
  285. }
  286.  
  287. void
  288. check_timers(after)
  289. {
  290.         register int i;
  291.     register struct event *p, *q;
  292.  
  293.     for (i = 0; i < TIMER_NSLOTS; i++) {
  294.         p = &timerqueue[i];
  295.         if (p->event_time != 0)
  296.             ct_die(after);
  297.         do {
  298.             q = p;
  299.             if ((p = p->next) == 0)
  300.                 ct_die(after);
  301.             if (p->prev != q)
  302.                 ct_die(after);
  303.         } while (p->event_time != 0);
  304.         if (p != &timerqueue[i])
  305.             ct_die(after);
  306.     }
  307. }
  308. #endif        
  309.  
  310. /*
  311.  * receive - Receive Procedure.  See section 3.4.2 in the specification.
  312.  */
  313. void
  314. receive(rbufp)
  315.     struct recvbuf *rbufp;
  316. {
  317.     register struct peer *peer;
  318.     register struct pkt *pkt;
  319.     register u_char hismode;
  320.     int restrict;
  321.     int has_mac;
  322.     int trustable;
  323.     int is_authentic;
  324.     u_long hiskeyid;
  325.     struct peer *peer2;
  326.     int process_packet();
  327.     void fast_xmit();
  328.     void clock_select();
  329.     void clear();
  330.     extern void unpeer();
  331.     extern void monitor();
  332.     extern int restrictions();
  333.     extern int authdecrypt();
  334.     extern int authistrusted();
  335.     extern struct peer *findpeer();
  336.     extern struct peer *newpeer();
  337.     extern char *ntoa();
  338.  
  339. #ifdef DEBUG
  340.     if (debug > 1)
  341.         printf("receive from %s\n", ntoa(&rbufp->recv_srcadr));
  342. #endif
  343.  
  344.     /*
  345.      * Let the monitoring software take a look at this first.
  346.      */
  347.     monitor(rbufp);
  348.  
  349.     /*
  350.      * Get the restrictions on this guy.  If we're to ignore him,
  351.      * go no further.
  352.      */
  353.     restrict = restrictions(&rbufp->recv_srcadr);
  354.     if (restrict & RES_IGNORE)
  355.         return;
  356.  
  357.     /*
  358.      * Get a pointer to the packet.
  359.      */
  360.     pkt = &rbufp->recv_pkt;
  361.  
  362.     /*
  363.      * Catch packets whose version number we can't deal with
  364.      */
  365.     if (PKT_VERSION(pkt->li_vn_mode) >= NTP_VERSION) {
  366.         sys_newversionpkt++;
  367.     } else if (PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
  368.         sys_oldversionpkt++;
  369.     } else {
  370.         sys_unknownversion++;
  371.         return;
  372.     }
  373.  
  374.     /*
  375.      * Catch private mode packets.  Dump it if queries not allowed.
  376.      */
  377.     if (PKT_MODE(pkt->li_vn_mode) == MODE_PRIVATE) {
  378.         if (restrict & RES_NOQUERY)
  379.             return;
  380.         process_private(rbufp, ((restrict&RES_NOMODIFY) == 0));
  381.         return;
  382.     }
  383.  
  384.     /*
  385.      * Same with control mode packets.
  386.      */
  387.     if (PKT_MODE(pkt->li_vn_mode) == MODE_CONTROL) {
  388.         if (restrict & RES_NOQUERY)
  389.             return;
  390.         process_control(rbufp, restrict);
  391.         return;
  392.     }
  393.  
  394.     /*
  395.      * See if we're allowed to serve this guy time.  If not, ignore
  396.      * him.
  397.      */
  398.     if (restrict & RES_DONTSERVE)
  399.         return;
  400.  
  401.     /*
  402.      * Dump anything with a putrid stratum.  These will most likely
  403.      * come from someone trying to poll us with ntpdc.
  404.      */
  405.     if (pkt->stratum > NTP_MAXSTRATUM) {
  406.         sys_badstratum++;
  407.         return;
  408.     }
  409.  
  410.     /*
  411.      * Find the peer.  This will return a null if this guy
  412.      * isn't in the database.
  413.      */
  414.     peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr);
  415.  
  416.     /*
  417.      * Check the length for validity, drop the packet if it is
  418.      * not as expected.
  419.      *
  420.      * If this is a client mode poll, go no further.  Send back
  421.      * his time and drop it.
  422.      *
  423.      * The scheme we use for authentication is this.  If we are
  424.      * running in non-authenticated mode, we accept both frames
  425.      * which are authenticated and frames which aren't, but don't
  426.      * authenticate.  We do record whether the frame had a mac field
  427.      * or not so we know what to do on output.
  428.      *
  429.      * If we are running in authenticated mode, we only trust frames
  430.      * which have authentication attached, which are validated and
  431.      * which are using one of our trusted keys.  We respond to all
  432.      * other pollers without saving any state.  If a host we are
  433.      * passively peering with changes his key from a trusted one to
  434.      * an untrusted one, we immediately unpeer with him, reselect
  435.      * the clock and treat him as an unmemorable client (this is
  436.      * a small denial-of-service hole I'll have to think about).
  437.      * If a similar event occurs with a configured peer we drop the
  438.      * frame and hope he'll revert to our key again.  If we get a
  439.      * frame which can't be authenticated with the given key, we
  440.      * drop it.  Either we disagree on the keys or someone is trying
  441.      * some funny stuff.
  442.      */
  443.  
  444.     /*
  445.      * here we assume that any packet with an authenticator is at
  446.      * least LEN_PKT_MAC bytes long, which means at least 96 bits
  447.      */
  448.     if (rbufp->recv_length >= LEN_PKT_MAC) {
  449.         has_mac = rbufp->recv_length - LEN_PKT_NOMAC;
  450.         hiskeyid = ntohl(pkt->keyid);
  451. #ifdef    DEBUG
  452.         if (debug > 3)
  453.             printf("receive: pkt is %d octets, mac %d octets long, keyid %d\n",
  454.                rbufp->recv_length, has_mac, hiskeyid);
  455. #endif
  456.     } else if (rbufp->recv_length == LEN_PKT_NOMAC) {
  457.         hiskeyid = 0;
  458.         has_mac = 0;
  459.     } else {
  460. #ifdef DEBUG
  461.         if (debug > 2)
  462.             printf("receive: bad length %d (not > %d or == %d)\n",
  463.                    rbufp->recv_length, LEN_PKT_MAC, LEN_PKT_NOMAC);
  464. #endif
  465.         sys_badlength++;
  466.         return;
  467.     }
  468.  
  469.  
  470.  
  471.     /*
  472.      * Figure out his mode and validate it.
  473.      */
  474.     hismode = PKT_MODE(pkt->li_vn_mode);
  475. #ifdef DEBUG
  476.     if (debug > 2)
  477.         printf("receive: his mode %d\n", hismode);
  478. #endif
  479.     if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION && hismode == 0) {
  480.         /*
  481.          * Easy.  If it is from the NTP port it is
  482.          * a sym act, else client.
  483.          */
  484.         if (SRCPORT(&rbufp->recv_srcadr) == NTP_PORT)
  485.             hismode = MODE_ACTIVE;
  486.         else
  487.             hismode = MODE_CLIENT;
  488.     } else {
  489.         if (hismode != MODE_ACTIVE && hismode != MODE_PASSIVE &&
  490.             hismode != MODE_SERVER && hismode != MODE_CLIENT &&
  491.             hismode != MODE_BROADCAST) {
  492.             syslog(LOG_ERR, "bad mode %d received from %s",
  493.                 PKT_MODE(pkt->li_vn_mode),
  494.                 ntoa(&rbufp->recv_srcadr));
  495.             return;
  496.         }
  497.     }
  498.  
  499.  
  500.     /*
  501.      * If he included a mac field, decrypt it to see if it is authentic.
  502.      */
  503.     is_authentic = 0;
  504.     if (has_mac) {
  505.         if (authhavekey(hiskeyid)) {
  506.             if (authdecrypt(hiskeyid, (u_long *)pkt, LEN_PKT_NOMAC,
  507.                     has_mac)) {
  508.                 is_authentic = 1;
  509. #ifdef    DEBUG
  510.                 if (debug > 3)
  511.                     printf("receive: authdecrypt succeeds\n");
  512. #endif
  513.             } else {
  514.                 sys_badauth++;
  515. #ifdef    DEBUG
  516.                 if (debug > 3)
  517.                     printf("receive: authdecrypt fails\n");
  518. #endif
  519.             }
  520.         }
  521.     }
  522.  
  523.     /*
  524.      * If this is someone we don't remember from a previous association,
  525.      * dispatch him now.  Either we send something back quick, we
  526.      * ignore him, or we allocate some memory for him and let
  527.      * him continue.
  528.      */
  529.     if (peer == 0) {
  530.         int mymode;
  531.  
  532.         mymode = MODE_PASSIVE;
  533.         switch(hismode) {
  534.         case MODE_ACTIVE:
  535.             /*
  536.              * See if this guy qualifies as being the least
  537.              * bit memorable.  If so we keep him around for
  538.              * later.  If not, send his time quick.
  539.              */
  540.             if (restrict & RES_NOPEER) {
  541.                 fast_xmit(rbufp, hismode, is_authentic);
  542.                 return;
  543.             }
  544.             break;
  545.  
  546.         case MODE_PASSIVE:
  547.         case MODE_SERVER:
  548.             /*
  549.              * These are obvious errors.  Ignore.
  550.              */
  551.             return;
  552.  
  553.         case MODE_CLIENT:
  554.             /*
  555.              * Send it back quick and go home.
  556.              */
  557.             fast_xmit(rbufp, hismode, is_authentic);
  558.             return;
  559.  
  560.         case MODE_BROADCAST:
  561.             /*
  562.              * Sort of a repeat of the above...
  563.              */
  564.             if ((restrict & RES_NOPEER) || !sys_bclient)
  565.                 return;
  566.             mymode = MODE_BCLIENT;
  567.             break;
  568.         }
  569.  
  570.         /*
  571.          * Okay, we're going to keep him around.  Allocate him
  572.          * some memory.
  573.          */
  574.         peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr, mymode,
  575.                    (int)PKT_VERSION(pkt->li_vn_mode), hiskeyid);
  576.         if (peer == 0) {
  577.             /*
  578.              * The only way this can happen is if the
  579.              * source address looks like a reference
  580.              * clock.  Since this is an illegal address
  581.              * this is one of those "can't happen" things.
  582.              */
  583.             syslog(LOG_ERR,
  584.                 "receive() failed to peer with %s, mode %d",
  585.                 ntoa(&rbufp->recv_srcadr), mymode);
  586.             return;
  587.         }
  588.     }
  589.  
  590.     /*
  591.      * Mark the time of reception
  592.      */
  593.     peer->timereceived = current_time;
  594.  
  595.     /*
  596.      * If the peer isn't configured, set his keyid and authenable
  597.      * status based on the packet.
  598.      */
  599.     if (!(peer->flags & FLAG_CONFIG)) {
  600.         if (has_mac) {
  601.             peer->keyid = hiskeyid;
  602.             peer->flags |= FLAG_AUTHENABLE;
  603.         } else {
  604.             peer->keyid = 0;
  605.             peer->flags &= ~FLAG_AUTHENABLE;
  606.         }
  607.     }
  608.  
  609.  
  610.     /*
  611.      * If this message was authenticated properly, note this
  612.      * in the flags.
  613.      */
  614.     if (is_authentic) {
  615.         peer->flags |= FLAG_AUTHENTIC;
  616.     } else {
  617.         /*
  618.          * If this guy is authenable, and has been authenticated
  619.          * in the past, but just failed the authentic test, report
  620.          * the event.
  621.          */
  622.         if (peer->flags & FLAG_AUTHENABLE
  623.             && peer->flags & FLAG_AUTHENTIC)
  624.             report_event(EVNT_PEERAUTH, peer);
  625.         peer->flags &= ~FLAG_AUTHENTIC;
  626.     }
  627.  
  628.     /*
  629.      * Determine if this guy is basically trustable.
  630.      */
  631.     if (restrict & RES_DONTTRUST)
  632.         trustable = 0;
  633.     else
  634.         trustable = 1;
  635.     
  636.     if (sys_authenticate && trustable) {
  637.         if (!(peer->flags & FLAG_CONFIG)
  638.             || (peer->flags & FLAG_AUTHENABLE))
  639.             trustable = 0;
  640.  
  641.         if (has_mac) {
  642.             if (authistrusted(hiskeyid)) {
  643.                 if (is_authentic) {
  644.                     trustable = 1;
  645.                 } else {
  646.                     trustable = 0;
  647.                     peer->badauth++;
  648.                 }
  649.             }
  650.         }
  651.     }
  652.  
  653.     /*
  654.      * Dispose of the packet based on our respective modes.  We
  655.      * don't drive this with a table, though we probably could.
  656.      */
  657.     switch (peer->hmode) {
  658.     case MODE_ACTIVE:
  659.     case MODE_CLIENT:
  660.         /*
  661.          * Active mode associations are configured.  If the data
  662.          * isn't trustable, ignore it and hope this guy brightens
  663.          * up.  Else accept any data we get and process it.
  664.          */
  665.         switch (hismode) {
  666.         case MODE_ACTIVE:
  667.         case MODE_PASSIVE:
  668.         case MODE_SERVER:
  669.             process_packet(peer, pkt, &(rbufp->recv_time),
  670.                 has_mac, trustable);
  671.             break;
  672.  
  673.         case MODE_CLIENT:
  674.             /*
  675.              * Deepsix client to avoid loops (shudder).
  676.              */
  677.             return;
  678.  
  679.         case MODE_BROADCAST:
  680.             /*
  681.              * No good for us, we want real time.
  682.              */
  683.             break;
  684.         }
  685.         break;
  686.  
  687.     case MODE_PASSIVE:
  688.         /*
  689.          * Passive mode associations are (in the current
  690.          * implementation) always dynamic.  If we get an
  691.          * invalid header, break the connection.  I hate
  692.          * doing this since it seems like a waste.  Oh, well.
  693.          */
  694.         switch (hismode) {
  695.         case MODE_ACTIVE:
  696.             if (process_packet(peer, pkt, &(rbufp->recv_time),
  697.                 has_mac, trustable) == 0) {
  698.                 unpeer(peer);
  699.                 clock_select((struct peer *)0);
  700.                 fast_xmit(rbufp, hismode, is_authentic);
  701.             }
  702.             break;
  703.  
  704.         case MODE_PASSIVE:
  705.         case MODE_SERVER:
  706.         case MODE_BROADCAST:
  707.             /*
  708.              * These are errors.  Just ignore the packet.
  709.              * If he doesn't straighten himself out this
  710.              * association will eventually be disolved.
  711.              */
  712.             break;
  713.         }
  714.         break;
  715.  
  716.     
  717.     case MODE_BCLIENT:
  718.         /*
  719.          * Broadcast client pseudo-mode.  We accept both server
  720.          * and broadcast data.  Passive mode data is an error.
  721.          */
  722.         switch (hismode) {
  723.         case MODE_ACTIVE:
  724.             /*
  725.              * This guy wants to give us real time when we've
  726.              * been existing on lousy broadcasts!  Create a
  727.              * passive mode association and do it that way,
  728.              * but keep the old one in case the packet turns
  729.              * out to be bad.
  730.              */
  731.             peer2 = newpeer(&rbufp->recv_srcadr,
  732.                     rbufp->dstadr, MODE_PASSIVE,
  733.                     (int)PKT_VERSION(pkt->li_vn_mode),
  734.                     hiskeyid);
  735.             if (process_packet(peer2, pkt, &rbufp->recv_time,
  736.                 has_mac, trustable) == 0) {
  737.                 /*
  738.                  * Strange situation.  We've been receiving
  739.                  * broadcasts from him which we liked, but
  740.                  * we don't like his active mode stuff.
  741.                  * Keep his old peer structure and send
  742.                  * him some time quickly, we'll figure it
  743.                  * out later.
  744.                  */
  745.                 unpeer(peer2);
  746.                 fast_xmit(rbufp, hismode, is_authentic);
  747.             } else
  748.                 /*
  749.                  * Drop the old association
  750.                  */
  751.                 unpeer(peer);
  752.             break;
  753.         
  754.         case MODE_PASSIVE:
  755.             break;
  756.         
  757.         case MODE_SERVER:
  758.         case MODE_BROADCAST:
  759.             process_packet(peer, pkt, &rbufp->recv_time,
  760.                 has_mac, trustable);
  761.             /*
  762.              * We don't test for invalid headers.
  763.              * Let him time out.
  764.              */
  765.             break;
  766.         }
  767.     }
  768. }
  769.  
  770.  
  771. /*
  772.  * process_packet - Packet Procedure, a la Section 3.4.3 of the specification.
  773.  *              Or almost, at least.  If we're in here we have a reasonable
  774.  *            expectation that we will be having a long term relationship
  775.  *            with this host.
  776.  */
  777. int
  778. process_packet(peer, pkt, recv_ts, has_mac, trustable)
  779.     register struct peer *peer;
  780.     register struct pkt *pkt;
  781.     l_fp *recv_ts;
  782.     int has_mac;
  783.     int trustable;            /* used as "valid header" */
  784. {
  785.     u_long t23_ui, t23_uf;
  786.     u_long t10_ui, t10_uf;
  787.     s_fp di, ei, p_dist, p_disp;
  788.     l_fp ci, p_rec, p_xmt, p_org;
  789.     int randomize;
  790.     u_char ostratum, oreach;
  791.     void clock_update();
  792.     void poll_update();
  793.     void clock_filter();
  794.     extern char *ntoa();
  795.     extern char *fptoa();
  796.     extern char *umfptoa();
  797.     extern char *mfptoa();
  798.     extern char *lfptoa();
  799.  
  800.     sys_processed++;
  801.     peer->processed++;
  802.  
  803.     peer->rec = *recv_ts;
  804.     p_dist = NTOHS_FP(pkt->rootdelay);
  805.     p_disp = NTOHS_FP(pkt->rootdispersion);
  806.     NTOHL_FP(&pkt->rec, &p_rec);
  807.     NTOHL_FP(&pkt->xmt, &p_xmt);
  808.         NTOHL_FP(&pkt->org, &p_org);
  809.     peer->flash = 0;
  810.     randomize = POLL_RANDOMCHANGE;
  811.  
  812.     /*
  813.      * Test for old or duplicate packets (tests 1 through 3).
  814.      */
  815.     
  816.     if (L_ISHIS(&peer->org, &p_xmt))    /* count old packets */
  817.         peer->oldpkt++;
  818.     if (L_ISEQU(&peer->org, &p_xmt))    /* test 1 */
  819.         peer->flash |= TEST1;        /* duplicate packet */
  820.     if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST) {
  821.         if (!L_ISEQU(&peer->xmt, &p_org)) { /* test 2 */
  822.             randomize = POLL_MAKERANDOM;
  823.             peer->bogusorg++;
  824.             peer->flash |= TEST2;    /* bogus packet */
  825.         }
  826.         if ((p_rec.l_ui == 0 && p_rec.l_uf == 0) ||
  827.             (p_org.l_ui == 0 && p_org.l_uf == 0))
  828.             peer->flash |= TEST3;    /* unsynchronized */
  829.     }
  830.     peer->org = p_xmt;    /* reuse byte-swapped pkt->xmt */
  831.     peer->ppoll = pkt->ppoll;
  832.         
  833.     /*
  834.      * Call poll_update().  This will either start us, if the
  835.      * association is new, or drop the polling interval if the
  836.      * association is existing and peer->ppoll has been reduced.
  837.      */
  838.     poll_update(peer, peer->hpoll, randomize);
  839.  
  840.     /*
  841.      * Test for valid header (tests 5 through 8)
  842.      */
  843.     if (trustable == 0)        /* test 5 */
  844.         peer->flash |= TEST5;    /* authentication failed */
  845.     if (PKT_LEAP(pkt->li_vn_mode) == LEAP_NOTINSYNC || /* test 6 */
  846.         p_xmt.l_ui < ntohl(pkt->reftime.l_ui) ||
  847.         p_xmt.l_ui >= (ntohl(pkt->reftime.l_ui) + NTP_MAXAGE)) {
  848.         peer->seltooold++;    /* test 6 */
  849.         peer->flash |= TEST6;    /* peer clock unsynchronized */
  850.     }
  851.     if (!(peer->flags & FLAG_CONFIG) &&  /* test 7 */
  852.         (PKT_TO_STRATUM(pkt->stratum) >= NTP_MAXSTRATUM ||
  853.         PKT_TO_STRATUM(pkt->stratum) > sys_stratum))
  854.         peer->flash |= TEST7;    /* peer stratum out of bounds */
  855.     if (p_dist >= NTP_MAXDISPERSE    /* test 8 */
  856.         || p_dist <= (-NTP_MAXDISPERSE)
  857.         || p_disp >= NTP_MAXDISPERSE) {
  858.         peer->disttoolarge++;
  859.         peer->flash |= TEST8;    /* delay/dispersion too big */
  860.     }
  861.  
  862.     /*
  863.      * If the packet header is invalid (tests 5 through 8), exit
  864.      */
  865.  
  866.     if (peer->flash & (TEST5 | TEST6 | TEST7 | TEST8)) {
  867.  
  868. #ifdef DEBUG
  869.         if (debug > 1)
  870.         printf("invalid packet header %s %02x\n",
  871.                ntoa(&peer->srcadr), peer->flash);
  872. #endif
  873.  
  874.         return(0);
  875.     }
  876.  
  877.     /*
  878.      * Valid header; update our state.
  879.      */
  880.     peer->leap = PKT_LEAP(pkt->li_vn_mode);
  881.     peer->pmode = PKT_MODE(pkt->li_vn_mode);
  882.     if (has_mac)
  883.         peer->pkeyid = ntohl(pkt->keyid);
  884.     else
  885.         peer->pkeyid = 0;
  886.     ostratum = peer->stratum;
  887.     peer->stratum = PKT_TO_STRATUM(pkt->stratum);
  888.     peer->precision = pkt->precision;
  889.     peer->rootdelay = p_dist;
  890.     peer->rootdispersion = p_disp;
  891.     peer->refid = pkt->refid;
  892.     NTOHL_FP(&pkt->reftime, &peer->reftime);
  893.     oreach = peer->reach;
  894.     if (peer->reach == 0) {
  895.         peer->timereachable = current_time;
  896.         /*
  897.          * If this guy was previously unreachable, set his
  898.          * polling interval to the minimum and reset the
  899.          * unreach counter.
  900.          */
  901.         peer->unreach = 0;
  902.         peer->hpoll = NTP_MINPOLL;
  903.     }
  904.     peer->reach |= 1;
  905.  
  906.     /*
  907.      * If running in a normal polled association, calculate the round
  908.      * trip delay (di) and the clock offset (ci).  We use the equations
  909.      * (reordered from those in the spec):
  910.      *
  911.      * d = (t2 - t3) - (t1 - t0)
  912.      * c = ((t2 - t3) + (t1 - t0)) / 2
  913.      *
  914.      * If running as a broadcast client, these change.  di becomes
  915.      * equal to two times our broadcast delay, while the offset
  916.      * becomes equal to:
  917.      *
  918.      * c = (t1 - t0) + estbdelay
  919.      */
  920.     t10_ui = p_xmt.l_ui;    /* pkt->xmt == t1 */
  921.     t10_uf = p_xmt.l_uf;
  922.     M_SUB(t10_ui, t10_uf, peer->rec.l_ui, peer->rec.l_uf); /*peer->rec==t0*/
  923.  
  924.     if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST) {
  925.         t23_ui = p_rec.l_ui;    /* pkt->rec == t2 */
  926.         t23_uf = p_rec.l_uf;
  927.         M_SUB(t23_ui, t23_uf, p_org.l_ui, p_org.l_uf); /*pkt->org==t3*/
  928.     }
  929.  
  930.     /* now have (t2 - t3) and (t0 - t1).  Calculate (ci), (di) and (ei) */
  931.     ci.l_ui = t10_ui;
  932.     ci.l_uf = t10_uf;
  933.     ei = (FP_SECOND >> (-(int)sys_precision));
  934.     if (peer->hmode == MODE_BCLIENT) {
  935. #ifdef notdef
  936.         if (PKT_MODE(pkt->li_vn_mode) == MODE_CLIENT) {
  937.             /*
  938.              * A client mode packet, used for delay computation.
  939.              * Give the data to the filter.
  940.              */
  941.             bdelay_filter(peer, t23_ui, t23_uf, t10_ui, t10_uf);
  942.         }
  943. #endif
  944.         M_ADDUF(ci.l_ui, ci.l_uf, peer->estbdelay>>1);
  945.         di = MFPTOFP(0, peer->estbdelay);
  946.     } else {
  947.         M_ADD(ci.l_ui, ci.l_uf, t23_ui, t23_uf);
  948.         M_RSHIFT(ci.l_i, ci.l_uf);
  949.  
  950.         /*
  951.          * Calculate di in t23 in full precision, then truncate
  952.          * to an s_fp.
  953.          */
  954.         M_SUB(t23_ui, t23_uf, t10_ui, t10_uf);
  955.         di = MFPTOFP(t23_ui, t23_uf);
  956.         /*
  957.          * Calculate (t3 - t0) in t23 in full precision, convert
  958.          * to single, shift down by MAXSKEW and add to ei.
  959.          * We know NTP_SKEWFACTOR == 16
  960.          */
  961. #if 0
  962.         t23_ui = peer->rec.l_ui;    /* peer->rec == t0 */
  963.         t23_uf = peer->rec.l_uf;
  964.         M_SUB(t23_ui, t23_uf, p_org.l_ui, p_org.l_uf); /*pkt->org==t3*/
  965.         ei += (MFPTOFP(t23_ui, t23_uf) >> NTP_SKEWFACTOR);
  966. #endif
  967.         ei += peer->rec.l_ui - p_org.l_ui;
  968.     }
  969. #ifdef DEBUG
  970.     if (debug > 3)
  971.         printf("offset: %s, delay %s, error %s\n",
  972.                lfptoa(&ci, 9), fptoa(di, 4), fptoa(ei, 4));
  973. #endif
  974.     if (di >= NTP_MAXDISPERSE || di <= (-NTP_MAXDISPERSE)
  975.         || ei >= NTP_MAXDISPERSE) {    /* test 4 */
  976.         peer->bogusdelay++;
  977.         peer->flash |= TEST4;    /* delay/dispersion too big */
  978.     }
  979.  
  980.     /*
  981.      * If the packet data is invalid (tests 1 through 4), exit
  982.      */
  983.     if (peer->flash) {
  984.  
  985. #ifdef DEBUG
  986.         if (debug)
  987.             printf("invalid packet data %s %02x\n",
  988.                 ntoa(&peer->srcadr), peer->flash);
  989. #endif
  990.  
  991.         /*
  992.          * If there was a reachability change report it even
  993.          * though the packet was bogus.
  994.          */
  995.         if (oreach == 0)
  996.             report_event(EVNT_REACH, peer);
  997.         return(1);
  998.     }
  999.  
  1000.     /*
  1001.      * This one is valid.  Mark it so, give it to clock_filter(),
  1002.      */
  1003.     clock_filter(peer, &ci, di, ei);
  1004.  
  1005.     /*
  1006.      * If this guy was previously unreachable, report him
  1007.      * reachable.
  1008.      * Note we do this here so that the peer values we return are
  1009.      * the updated ones.
  1010.      */
  1011.     if (oreach == 0)
  1012.         report_event(EVNT_REACH, peer);
  1013.  
  1014.     /*
  1015.      * Now update the clock.
  1016.      */
  1017.     clock_update(peer);
  1018.     return(1);
  1019. }
  1020.  
  1021.  
  1022. /*
  1023.  * clock_update - Clock-update procedure, see section 3.4.5.
  1024.  */
  1025. void
  1026. clock_update(peer)
  1027.     struct peer *peer;
  1028. {
  1029.     u_char oleap;
  1030.     u_char ostratum;
  1031.     s_fp d;
  1032.     void poll_update();
  1033.     void clock_select();
  1034.     void clear_all();
  1035.     extern u_char leap_mask;
  1036.     extern int local_clock();
  1037.     extern void leap_process();
  1038.     extern char *ntoa();
  1039.     extern void record_stats();
  1040.     u_short ctlpeerstatus();
  1041.  
  1042. #ifdef DEBUG
  1043.     if (debug)
  1044.         printf("clock_update(%s)\n", ntoa(&peer->srcadr));
  1045. #endif
  1046.  
  1047.     record_stats(&peer->srcadr, ctlpeerstatus(peer), &peer->offset,
  1048.         peer->delay, peer->dispersion);
  1049.  
  1050.     /*
  1051.      * Call the clock selection algorithm to see
  1052.      * if this update causes the peer to change.
  1053.      */
  1054.     clock_select(peer);
  1055.  
  1056.     /*
  1057.      * Quit if this peer isn't the system peer.  Other peers
  1058.      * used in the combined offset are not allowed to set
  1059.      * system variables or update the clock.
  1060.      */
  1061.     if (peer != sys_peer)
  1062.         return;
  1063.  
  1064.     /*
  1065.      * Quit if the sys_peer is too far away.
  1066.      */
  1067.     if (peer->synch >= NTP_MAXDISTANCE)
  1068.         return;
  1069.  
  1070.     /*
  1071.      * Update the system state
  1072.      */
  1073.     oleap = sys_leap;
  1074.     ostratum = sys_stratum;
  1075.     sys_leap = peer->leap & leap_mask;
  1076.     /*
  1077.      * N.B. peer->stratum was guaranteed to be less than
  1078.      * NTP_MAXSTRATUM by the receive procedure.
  1079.      * We assume peer->update == sys_clock because
  1080.      * clock_filter was called right before this function.
  1081.      * If the pps signal is in control, the system variables are
  1082.      * set in the ntp_loopfilter.c module.
  1083.      */
  1084.     if (!pps_control) {
  1085.         sys_stratum = peer->stratum + 1;
  1086.         d = peer->delay;
  1087.         if (d < 0)
  1088.             d = -d;
  1089.          sys_rootdelay = peer->rootdelay + d;
  1090.         sys_maxd = peer->dispersion + peer->selectdisp;
  1091.         d = peer->soffset;
  1092.         if (d < 0)
  1093.             d = -d;
  1094.         d += sys_maxd;
  1095.         if (!peer->flags & FLAG_REFCLOCK && d < NTP_MINDISPERSE)
  1096.             d = NTP_MINDISPERSE;
  1097.         sys_rootdispersion = peer->rootdispersion + d;
  1098.     }
  1099.     
  1100.     /*
  1101.      * Hack for reference clocks.  Sigh.  This is the
  1102.      * only real silly part, though, so the analogy isn't
  1103.      * bad.
  1104.      */
  1105.     if (peer->flags & FLAG_REFCLOCK
  1106.         && peer->stratum == STRATUM_REFCLOCK)
  1107.         sys_refid = peer->refid;
  1108.     else {
  1109.         if (pps_control)
  1110.             bcopy(PPSREFID, (char *)&sys_refid, 4);
  1111.         else
  1112.             sys_refid = peer->srcadr.sin_addr.s_addr;
  1113.     }
  1114.  
  1115.     /*
  1116.      * Report changes.  Note that we never sync to
  1117.      * an unsynchronized host.
  1118.      */
  1119.     if (oleap == LEAP_NOTINSYNC)
  1120.         report_event(EVNT_SYNCCHG, (struct peer *)0);
  1121.     else if (ostratum != sys_stratum)
  1122.         report_event(EVNT_PEERSTCHG, (struct peer *)0);
  1123.  
  1124.     sys_reftime = peer->rec;
  1125.     sys_refskew.l_i = 0; sys_refskew.l_f = NTP_SKEWINC;
  1126.  
  1127.     switch (local_clock(&sys_offset, &(peer->srcadr))) {
  1128.     case -1:
  1129.         /*
  1130.          * Clock is too screwed up.  Just exit for now.
  1131.          */
  1132.         report_event(EVNT_SYSFAULT, (struct peer *)0);
  1133.         exit(1);
  1134.         /*NOTREACHED*/
  1135.     case 0:
  1136.         /*
  1137.          * Clock was slewed.  Continue on normally.
  1138.          */
  1139.         break;
  1140.         
  1141.     case 1:
  1142.         /*
  1143.          * Clock was stepped.  Clear filter registers
  1144.          * of all peers.
  1145.          */
  1146.         clear_all();
  1147.         leap_process();        /* reset the leap interrupt */
  1148.         sys_leap = LEAP_NOTINSYNC;
  1149.         sys_refskew.l_i = NTP_MAXSKEW; sys_refskew.l_f = 0;
  1150.         report_event(EVNT_CLOCKRESET, (struct peer *)0);
  1151.         break;
  1152.     }
  1153. }
  1154.  
  1155.  
  1156.  
  1157. /*
  1158.  * poll_update - update peer poll interval.  See Section 3.4.8 of the spec.
  1159.  */
  1160. void
  1161. poll_update(peer, new_hpoll, randomize)
  1162.     struct peer *peer;
  1163.     int new_hpoll;
  1164.     int randomize;
  1165. {
  1166.     register struct event *evp;
  1167.     register u_long new_timer;
  1168.     register int newpoll, oldpoll;
  1169.     u_long ranp2();
  1170.     char *ntoa();
  1171.  
  1172. #ifdef DEBUG
  1173.     if (debug > 1)
  1174.         printf("poll_update(%s, %d, %d)\n", ntoa(&peer->srcadr),
  1175.             new_hpoll, randomize);
  1176. #endif
  1177.     /*
  1178.      * Catch reference clocks here.  The polling interval for a
  1179.      * reference clock is fixed and needn't be maintained by us.
  1180.      */
  1181.     if (peer->flags & FLAG_REFCLOCK)
  1182.         return;
  1183.  
  1184.     /*
  1185.      * This routine * will randomly perturb the new peer.timer if
  1186.      * requested, to try to prevent synchronization with the remote
  1187.      * peer from occuring.  There are three options, based on the
  1188.      * value of randomize:
  1189.      *
  1190.      * POLL_NOTRANDOM - essentially the spec algorithm.  If
  1191.      * peer.timer is greater than the new polling interval,
  1192.      * drop it to the new interval.
  1193.      *
  1194.      * POLL_RANDOMCHANGE - make changes randomly.  If peer.timer
  1195.      * must be changed, based on the comparison about, randomly
  1196.      * perturb the new value of peer.timer.
  1197.      *
  1198.      * POLL_MAKERANDOM - make next interval random.  Calculate
  1199.      * a randomly perturbed poll interval.  If this value is
  1200.      * less that peer.timer, update peer.timer.
  1201.      */
  1202.     oldpoll = peer->hpoll;
  1203.     if ((peer->flags & FLAG_SYSPEER) && new_hpoll > sys_poll)
  1204.         peer->hpoll = sys_poll;
  1205.     else {
  1206.         if (new_hpoll >= NTP_MAXPOLL)
  1207.             peer->hpoll = NTP_MAXPOLL;
  1208.         else if (new_hpoll <= NTP_MINPOLL)
  1209.             peer->hpoll = NTP_MINPOLL;
  1210.         else
  1211.             peer->hpoll = (u_char)new_hpoll;
  1212.     }
  1213.  
  1214.     /* hpoll <= NTP_MAXPOLL for sure */
  1215.     newpoll = (int)max(min(peer->ppoll, peer->hpoll), NTP_MINPOLL);
  1216.     if (randomize == POLL_MAKERANDOM ||
  1217.         (randomize == POLL_RANDOMCHANGE && newpoll != oldpoll))
  1218.         new_timer = (1<<(newpoll - 1))
  1219.             + ranp2(newpoll - 1) + current_time;
  1220.     else
  1221.         new_timer = (1<<newpoll) + current_time;
  1222.     evp = &(peer->event_timer);
  1223.     if (evp->next == 0 || evp->event_time > new_timer) {
  1224.         TIMER_DEQUEUE(evp);
  1225.         evp->event_time = new_timer;
  1226.         TIMER_ENQUEUE(timerqueue, evp);
  1227.     }
  1228. }
  1229.  
  1230.  
  1231. /*
  1232.  * clear_all - clear all peer filter registers.  This is done after
  1233.  *           a step change in the time.
  1234.  */
  1235. void
  1236. clear_all()
  1237. {
  1238.     register int i;
  1239.     register struct peer *peer;
  1240.     extern void unpeer();
  1241.     void clear();
  1242.     void poll_update();
  1243.  
  1244.     for (i = 0; i < HASH_SIZE; i++)
  1245.         for (peer = peer_hash[i]; peer != 0; peer = peer->next) {
  1246.             /*
  1247.              * We used to drop all unconfigured pollers here.
  1248.              * The problem with doing this is that if your best
  1249.              * time source is unconfigured (there are reasons
  1250.              * for doing this) and you drop him, he may not
  1251.              * get around to polling you for a long time.  Hang
  1252.              * on to everyone, dropping their polling intervals
  1253.              * to the minimum.
  1254.              */
  1255.             clear(peer);
  1256.             poll_update(peer, NTP_MINPOLL, POLL_RANDOMCHANGE);
  1257.         }
  1258.  
  1259.     /*
  1260.      * Clear sys_peer.  We'll sync to one later.
  1261.      */
  1262.     sys_peer = 0;
  1263.     sys_stratum = STRATUM_UNSPEC;
  1264.  
  1265. }
  1266.  
  1267.  
  1268. /*
  1269.  * clear - clear peer filter registers.  See Section 3.4.7 of the spec.
  1270.  */
  1271. void
  1272. clear(peer)
  1273.     register struct peer *peer;
  1274. {
  1275.     register int i;
  1276.     extern char *ntoa();
  1277.  
  1278. #ifdef DEBUG
  1279.     if (debug)
  1280.         printf("clear(%s)\n", ntoa(&peer->srcadr));
  1281. #endif
  1282.     bzero(CLEAR_TO_ZERO(peer), LEN_CLEAR_TO_ZERO);
  1283.     peer->dispersion = NTP_MAXDISPERSE;
  1284.     for (i = 0; i < NTP_SHIFT; i++)
  1285.         peer->filter_error[i] = NTP_MAXDISPERSE;
  1286.  
  1287.     /*
  1288.      * Clear out the selection counters
  1289.      */
  1290.     peer->candidate = 0;
  1291.     peer->select = 0;
  1292.     peer->correct = 0;
  1293.     peer->was_sane = 0;
  1294.  
  1295.     /*
  1296.      * Since we have a chance to correct possible funniness in
  1297.      * our selection of interfaces on a multihomed host, do so
  1298.      * by setting us to no particular interface.
  1299.      */
  1300.     peer->dstadr = any_interface;
  1301. }
  1302.  
  1303.  
  1304. /*
  1305.  * clock_filter - add incoming clock sample to filter register and run
  1306.  *          the filter procedure to find the best sample.
  1307.  */
  1308. void
  1309. clock_filter(peer, sample_offset, sample_delay, sample_error)
  1310.     register struct peer *peer;
  1311.     l_fp *sample_offset;
  1312.     s_fp sample_delay;
  1313.     u_fp sample_error;
  1314. {
  1315.     register int i;
  1316.     register u_char *ord;
  1317.     register s_fp sample_distance, sample_soffset, skew;
  1318.     s_fp distance[NTP_SHIFT];
  1319.     extern char *ntoa();
  1320.     extern char *ufptoa();
  1321.     extern char *lfptoa();
  1322.  
  1323. #ifdef DEBUG
  1324.     if (debug)
  1325.         printf("clock_filter(%s, %s, %s, %s)\n",
  1326.             ntoa(&peer->srcadr), lfptoa(sample_offset, 6),
  1327.             fptoa(sample_delay, 5), ufptoa(sample_error, 5));
  1328. #endif
  1329.  
  1330.     /*
  1331.      * Update sample errors and calculate distances.
  1332.      * We know NTP_SKEWFACTOR == 16
  1333.      */
  1334.     skew = sys_clock - peer->update;
  1335.     peer->update = sys_clock;
  1336.     for (i = 0; i < NTP_SHIFT; i++) {
  1337.         distance[i] = peer->filter_error[i];
  1338.         if (peer->filter_error[i] < NTP_MAXDISPERSE) {
  1339.             peer->filter_error[i] += skew;
  1340.             distance[i] += (peer->filter_delay[i] >> 1);
  1341.         }
  1342.     }
  1343.  
  1344.     /*
  1345.      * We keep a sort by distance of the current contents of the
  1346.      * shift registers.  We update this by (1) removing the
  1347.      * register we are going to be replacing from the sort, and
  1348.      * (2) reinserting it based on the new distance value.
  1349.      */
  1350.     ord = peer->filter_order;
  1351.     sample_distance = sample_error + (sample_delay >> 1);
  1352.     sample_soffset = LFPTOFP(sample_offset);
  1353.  
  1354.     for (i = 0; i < NTP_SHIFT-1; i++)    /* find old value */
  1355.         if (ord[i] == peer->filter_nextpt)
  1356.             break;
  1357.     for ( ; i < NTP_SHIFT-1; i++)    /* i is current, move everything up */
  1358.         ord[i] = ord[i+1];
  1359.     /* Here, last slot in ord[] is empty */
  1360.  
  1361.     if (sample_error >= NTP_MAXDISPERSE)
  1362.         /*
  1363.          * Last slot for this guy.
  1364.          */
  1365.         i = NTP_SHIFT-1;
  1366.     else {
  1367.         register int j;
  1368.         register u_fp *errorp;
  1369.  
  1370.         errorp = peer->filter_error;
  1371.         /*
  1372.          * Find where he goes in, then shift everyone else down
  1373.          */
  1374.         if (peer->hmode == MODE_BCLIENT) {
  1375.             register s_fp *soffsetp;
  1376.             /*
  1377.              * Sort by offset.  The most positive offset
  1378.              * should correspond to the minimum delay.
  1379.              */
  1380.             soffsetp = peer->filter_soffset;
  1381.             for (i = 0; i < NTP_SHIFT-1; i++)
  1382.                 if (errorp[ord[i]] >= NTP_MAXDISPERSE
  1383.                     || sample_soffset >= soffsetp[ord[i]])
  1384.                     break;
  1385.         } else {
  1386.             /*
  1387.              * Sort by distance.
  1388.              */
  1389.             for (i = 0; i < NTP_SHIFT-1; i++)
  1390.                 if (errorp[ord[i]] >= NTP_MAXDISPERSE
  1391.                     || sample_distance <= distance[ord[i]])
  1392.                     break;
  1393.         }
  1394.  
  1395.         for (j = NTP_SHIFT-1; j > i; j--)
  1396.             ord[j] = ord[j-1];
  1397.     }
  1398.     ord[i] = peer->filter_nextpt;
  1399.  
  1400.     /*
  1401.      * Got everything in order.  Insert sample in current register
  1402.      * and increment nextpt.
  1403.      */
  1404.     peer->filter_delay[peer->filter_nextpt] = sample_delay;
  1405.     peer->filter_offset[peer->filter_nextpt] = *sample_offset;
  1406.     peer->filter_soffset[peer->filter_nextpt] = sample_soffset;
  1407.     peer->filter_error[peer->filter_nextpt] = sample_error;
  1408.     distance[peer->filter_nextpt] = sample_distance;
  1409.     peer->filter_nextpt++;
  1410.     if (peer->filter_nextpt >= NTP_SHIFT)
  1411.         peer->filter_nextpt = 0;
  1412.     
  1413.     /*
  1414.      * Now compute the dispersion, and assign values to delay and
  1415.      * offset.  If there are no samples in the register, delay and
  1416.      * offset are not touched and dispersion is set to the maximum.
  1417.      */
  1418.     if (peer->filter_error[ord[0]] >= NTP_MAXDISPERSE) {
  1419.         peer->dispersion = NTP_MAXDISPERSE;
  1420.     } else {
  1421.         register s_fp d;
  1422.  
  1423.         peer->delay = peer->filter_delay[ord[0]];
  1424.         peer->offset = peer->filter_offset[ord[0]];
  1425.         peer->soffset = LFPTOFP(&peer->offset);
  1426.         peer->dispersion = peer->filter_error[ord[0]];
  1427.         for (i = 1; i < NTP_SHIFT; i++) {
  1428.             if (peer->filter_error[ord[i]] >= NTP_MAXDISPERSE)
  1429.                 d = NTP_MAXDISPERSE;
  1430.             else {
  1431.                 d = peer->filter_soffset[ord[i]]
  1432.                     - peer->filter_soffset[ord[0]];
  1433.                 if (d < 0)
  1434.                     d = -d;
  1435.                 if (d > NTP_MAXDISPERSE)
  1436.                     d = NTP_MAXDISPERSE;
  1437.             }
  1438.             /*
  1439.              * XXX This *knows* NTP_FILTER is 1/2
  1440.              */
  1441.             peer->dispersion += (u_fp)(d) >> i;
  1442.         }
  1443.         /*
  1444.          * Calculate synchronization distance backdated to
  1445.          * sys_lastselect (clock_select will fix it).
  1446.          * We know NTP_SKEWFACTOR == 16
  1447.          */
  1448.         d = peer->delay;
  1449.         if (d < 0)
  1450.             d = -d;
  1451.         d += peer->rootdelay;
  1452.         peer->synch = (d>>1)
  1453.                   + peer->rootdispersion + peer->dispersion
  1454.                   - (sys_clock - sys_lastselect);
  1455.     }
  1456.     /*
  1457.      * We're done
  1458.      */
  1459. }
  1460.  
  1461.  
  1462. /*
  1463.  * clock_select - find the pick-of-the-litter clock
  1464.  */
  1465. /*ARGSUSED*/
  1466. void
  1467. clock_select(changed_peer)
  1468.     struct peer *changed_peer;    /* for a possible future optimization */
  1469. {
  1470.     register struct peer *peer;
  1471.     register int i;
  1472.     register int nlist, nl3;
  1473.     register s_fp d, e;
  1474.     register int j;
  1475.     register int n;
  1476.     register int allow, found, k;
  1477.     s_fp low, high;
  1478.     u_fp synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
  1479.     struct peer *osys_peer;
  1480.     static int list_alloc = 0;
  1481.     static struct endpoint *endpoint;
  1482.     static int *index;
  1483.     static struct peer **peer_list;
  1484.     static int endpoint_size = 0, index_size = 0, peer_list_size = 0;
  1485.     extern char *emalloc();
  1486.     extern void clock_combine();
  1487.     extern char *ntoa();
  1488.  
  1489. #ifdef DEBUG
  1490.     if (debug > 1)
  1491.         printf("clock_select()\n");
  1492. #endif
  1493.  
  1494.     nlist = 0;
  1495.     for (n = 0; n < HASH_SIZE; n++)
  1496.         nlist += peer_hash_count[n];
  1497.     if (nlist > list_alloc) {
  1498.         if (list_alloc > 0) {
  1499.             free(endpoint);
  1500.             free(index);
  1501.             free(peer_list);
  1502.         }
  1503.         while (list_alloc < nlist) {
  1504.             list_alloc += 5;
  1505.             endpoint_size += 5 * 3 * sizeof *endpoint;
  1506.             index_size += 5 * 3 * sizeof *index;
  1507.             peer_list_size += 5 * sizeof *peer_list;
  1508.         }
  1509.         endpoint = (struct endpoint *)emalloc(endpoint_size);
  1510.         index = (int *)emalloc(index_size);
  1511.         peer_list = (struct peer **)emalloc(peer_list_size);
  1512.     }
  1513.  
  1514.     /*
  1515.      * This first chunk of code is supposed to go through all
  1516.      * peers we know about to find the NTP_MAXLIST peers which
  1517.      * are most likely to succeed.  We run through the list
  1518.      * doing the sanity checks and trying to insert anyone who
  1519.      * looks okay.  We are at all times aware that we should
  1520.      * only keep samples from the top two strata and we only need
  1521.      * NTP_MAXLIST of them.
  1522.      */
  1523.     nlist = nl3 = 0;    /* none yet */
  1524.     for (n = 0; n < HASH_SIZE; n++) {
  1525.         for (peer = peer_hash[n]; peer != 0; peer = peer->next) {
  1526.             /*
  1527.              * Clear peer selection stats
  1528.              */
  1529.             peer->was_sane = 0;
  1530.             peer->correct = 0;
  1531.             peer->candidate = 0;
  1532.             peer->select = 0;
  1533.  
  1534.             peer->flags &= ~FLAG_SYSPEER;
  1535.             /*
  1536.              * Update synch distance (NTP_SKEWFACTOR == 16)
  1537.              */
  1538.             peer->synch += (sys_clock - sys_lastselect);
  1539.  
  1540.             if (peer->reach == 0)
  1541.                 continue;    /* unreachable */
  1542.             if (peer->stratum > 1 &&
  1543.                 peer->refid == peer->dstadr->sin.sin_addr.s_addr)
  1544.                 continue;    /* sync loop */
  1545.             if (peer->stratum >= NTP_MAXSTRATUM ||
  1546.                     peer->stratum > sys_stratum)
  1547.                 continue;    /* bad stratum  */
  1548.  
  1549.             if (peer->dispersion >= NTP_MAXDISPERSE) {
  1550.                 peer->seldisptoolarge++;
  1551.                 continue;    /* too noisy or broken */
  1552.             }
  1553.             if (peer->org.l_ui < peer->reftime.l_ui) {
  1554.                 peer->selbroken++;
  1555.                 continue;    /* very broken host */
  1556.             }
  1557.  
  1558.             /*
  1559.              * This one seems sane.
  1560.              */
  1561.             peer->was_sane = 1;
  1562.             peer_list[nlist++] = peer;
  1563.  
  1564.             /*
  1565.              * Insert each interval endpoint on the sorted list.
  1566.              */
  1567.             e = peer->soffset + peer->synch;    /* Upper end */
  1568.             for (i = nl3 - 1; i >= 0; i--) {
  1569.                 if (e >= endpoint[index[i]].val)
  1570.                     break;
  1571.                 index[i + 3] = index[i];
  1572.             }
  1573.             index[i + 3] = nl3;
  1574.             endpoint[nl3].type = 1;
  1575.             endpoint[nl3++].val = e;
  1576.  
  1577.             e -= peer->synch;    /* Center point */
  1578.             for ( ; i >= 0; i--) {
  1579.                 if (e >= endpoint[index[i]].val)
  1580.                     break;
  1581.                 index[i + 2] = index[i];
  1582.             }
  1583.             index[i + 2] = nl3;
  1584.             endpoint[nl3].type = 0;
  1585.             endpoint[nl3++].val = e;
  1586.  
  1587.             e -= peer->synch;    /* Lower end */
  1588.             for ( ; i >= 0; i--) {
  1589.                 if (e >= endpoint[index[i]].val)
  1590.                     break;
  1591.                 index[i + 1] = index[i];
  1592.             }
  1593.             index[i + 1] = nl3;
  1594.             endpoint[nl3].type = -1;
  1595.             endpoint[nl3++].val = e;
  1596.         }
  1597.     }
  1598.     sys_lastselect = sys_clock;
  1599.  
  1600. #ifdef DEBUG
  1601.     if (debug > 2)
  1602.         for (i = 0; i < nl3; i++)
  1603.             printf("select: endpoint %2d %s\n",
  1604.                    endpoint[index[i]].type,
  1605.                    fptoa(endpoint[index[i]].val, 6));
  1606. #endif
  1607.  
  1608.     i = 0;
  1609.     j = nl3 - 1;
  1610.     allow = nlist;    /* falsetickers assumed */
  1611.     found = 0;
  1612.     while (allow > 0) {
  1613.         allow--;
  1614.         for (n = 0; i <= j; i++) {
  1615.             n += endpoint[index[i]].type;
  1616.             if (n < 0)
  1617.                 break;
  1618.             if (endpoint[index[i]].type == 0)
  1619.                 found++;
  1620.         }
  1621.         for (n = 0; i <= j; j--) {
  1622.             n += endpoint[index[j]].type;
  1623.             if (n > 0)
  1624.                 break;
  1625.             if (endpoint[index[j]].type == 0)
  1626.                 found++;
  1627.         }
  1628.         if (found > allow)
  1629.             break;
  1630.         low = endpoint[index[i++]].val;
  1631.         high = endpoint[index[j--]].val;
  1632.     }
  1633.     if ((allow << 1) >= nlist) {
  1634.         if (debug)
  1635.             printf("clock_select: no intersection\n");
  1636.         if (sys_peer != 0)
  1637.             report_event(EVNT_PEERSTCHG, (struct peer *)0);
  1638.         sys_peer = 0;
  1639.         sys_stratum = STRATUM_UNSPEC;
  1640.         return;
  1641.     }
  1642.  
  1643. #ifdef DEBUG
  1644.     if (debug > 2)
  1645.         printf("select: low %s high %s\n", fptoa(low, 6),
  1646.                fptoa(high, 6));
  1647. #endif
  1648.  
  1649.     /*
  1650.      * Clustering algorithm. Process intersection list to discard
  1651.      * outlyers. First, construct candidate list in cluster order.
  1652.      * Cluster order is determined by the sum of peer
  1653.      * synchronization distance plus scaled stratum.
  1654.      */
  1655.  
  1656.     j = 0;
  1657.     for (i = 0; i < nlist; i++) {
  1658.         peer = peer_list[i];
  1659.         if (peer->soffset < low || high < peer->soffset)
  1660.             continue;
  1661.         peer->correct = 1;
  1662.         d = peer->synch + ((u_long)peer->stratum << NTP_DISPFACTOR);
  1663.         if (j >= NTP_MAXCLOCK) {
  1664.             if (d >= synch[j - 1])
  1665.                 continue;
  1666.             else
  1667.                 j--;
  1668.         }
  1669.         for (k = j; k > 0; k--) {
  1670.             if (d >= synch[k - 1])
  1671.                 break;
  1672.             synch[k] = synch[k - 1];
  1673.             peer_list[k] = peer_list[k - 1];
  1674.         }
  1675.         peer_list[k] = peer;
  1676.         synch[k] = d;
  1677.         j++;
  1678.     }
  1679.     nlist = j;
  1680. #ifdef DEBUG
  1681.     if (debug > 2)
  1682.         for (i = 0; i < nlist; i++)
  1683.             printf("select: candidate %s cdist %s\n",
  1684.                    ntoa(&peer_list[i]->srcadr),
  1685.                    fptoa(synch[i], 6));
  1686. #endif
  1687.  
  1688.     /*
  1689.      * Now, prune outlyers by root dispersion.
  1690.      */
  1691.  
  1692.     for (i = 0; i < nlist; i++) {
  1693.         peer = peer_list[i];
  1694.         peer->candidate = i + 1;
  1695.         error[i] = peer_list[i]->rootdispersion +
  1696.                peer_list[i]->dispersion +
  1697.                (sys_clock - peer_list[i]->update);
  1698.     }
  1699.     while (1) {
  1700.         u_fp maxd = 0;
  1701.         e = error[0];
  1702.         for (i = nlist - 1; i >= 0; i--) {
  1703.             u_fp sdisp = 0;
  1704.  
  1705.             for (j = nlist - 1; j >= 0; j--) {
  1706.                 d = peer_list[i]->soffset
  1707.                     - peer_list[j]->soffset;
  1708.                 if (d < 0)
  1709.                     d = -d;
  1710.                 sdisp += d;
  1711.                 sdisp = ((sdisp>>1) + sdisp) >> 1;
  1712.             }
  1713.             peer_list[i]->selectdisp = sdisp;
  1714.             if (sdisp > maxd) {
  1715.                 maxd = sdisp;
  1716.                 k = i;
  1717.             }
  1718.             if (error[i] < e)
  1719.                 e = error[i];
  1720.         }
  1721.         if (nlist <= NTP_MINCLOCK || maxd <= e)
  1722.             break;
  1723.         for (j = k + 1; j < nlist; j++) {
  1724.             peer_list[j - 1] = peer_list[j];
  1725.             error[j - 1] = error[j];
  1726.         }
  1727.         nlist--;
  1728.     }
  1729.     
  1730. #ifdef DEBUG
  1731.     if (debug > 1) {
  1732.         for (i = 0; i < nlist; i++)
  1733.             printf("select: survivor %s offset %s, cdist %s\n",
  1734.                    ntoa(&peer_list[i]->srcadr),
  1735.                    lfptoa(&peer_list[i]->offset, 6),
  1736.                    fptoa(synch[i], 5));
  1737.     }
  1738. #endif
  1739.  
  1740.     /*
  1741.      * What remains is a list of less than NTP_MINCLOCK peers.
  1742.      * First record their order, then choose a peer.  If the
  1743.      * head of the list has a lower stratum than sys_peer
  1744.      * choose him right off.  If not, see if sys_peer is in
  1745.      * the list.  If so, keep him.  If not, take the top of
  1746.      * the list anyway. Also, clamp the polling intervals.
  1747.      */
  1748.     osys_peer = sys_peer;
  1749.     for (i = nlist - 1; i >= 0; i--) {
  1750.         if (peer_list[i]->flags & FLAG_PREFER)
  1751.             sys_peer = peer_list[i];
  1752.         peer_list[i]->select = i + 1;
  1753.         peer_list[i]->flags |= FLAG_SYSPEER;
  1754.         poll_update(peer_list[i], peer_list[i]->hpoll,
  1755.             POLL_RANDOMCHANGE);
  1756.     }
  1757.     if (sys_peer == 0 || sys_peer->stratum > peer_list[0]->stratum) {
  1758.         sys_peer = peer_list[0];
  1759.     } else {
  1760.         for (i = 1; i < nlist; i++)
  1761.             if (peer_list[i] == sys_peer)
  1762.                 break;
  1763.         if (i < nlist)
  1764.             sys_wanderhold++;
  1765.         else
  1766.             sys_peer = peer_list[0];
  1767.     }
  1768.  
  1769.     /*
  1770.      * If we got a new system peer from all of this, report the event.
  1771.      */
  1772.     if (osys_peer != sys_peer)
  1773.         report_event(EVNT_PEERSTCHG, (struct peer *)0);
  1774.  
  1775.     /*
  1776.      * Combine the offsets of the survivors to form a weighted
  1777.      * offset.
  1778.      */
  1779.     clock_combine(peer_list, nlist);
  1780. }
  1781.  
  1782. /*
  1783.  * clock_combine - combine offsets from selected peers
  1784.  *
  1785.  * Note: this routine uses only those peers at the lowest stratum.
  1786.  * Strictly speaking, this is at variance with the spec.
  1787.  */  
  1788. void
  1789. clock_combine(peers, npeers)
  1790.     struct peer **peers;
  1791.     int npeers;
  1792. {
  1793.     register int i, j, k;
  1794.     register u_fp a, b, d;
  1795.     u_fp synch[NTP_MAXCLOCK];
  1796.     l_fp coffset[NTP_MAXCLOCK];
  1797.     l_fp diff;
  1798.  
  1799.     /*
  1800.      * Sort peers by cluster distance as in the outlyer algorithm. If
  1801.      * the preferred peer is found, use its offset only.
  1802.      */
  1803.     k = 0;
  1804.     for (i = 0; i < npeers; i++) {
  1805.         if (peers[i]->stratum > sys_peer->stratum) continue;
  1806.         if (peers[i]->flags & FLAG_PREFER) {
  1807.             sys_offset = peers[i]->offset;
  1808.             pps_update = current_time;
  1809. #ifdef DEBUG
  1810.                 printf("combine: prefer offset %s\n",
  1811.                 lfptoa(&sys_offset, 6));
  1812. #endif
  1813.             return;
  1814.         }
  1815.         d = peers[i]->synch;
  1816.         for (j = k; j > 0; j--) {
  1817.             if (synch[j - 1] <= d)
  1818.                 break;
  1819.             synch[j] = synch[j - 1];
  1820.             coffset[j] = coffset[j - 1];
  1821.         }
  1822.         synch[j] = d;
  1823.         coffset[j] = peers[i]->offset;
  1824.         k++;
  1825.     }
  1826.     /*
  1827.      * Succesively combine the two offsets with the highest
  1828.      * distance and enter the result into the sorted list.
  1829.      */
  1830.     for (i = k - 2; i >= 0; i--) {
  1831.         /*
  1832.          * The possible weights for the most distant offset
  1833.          * are 1/2, 1/4, 1/8 and zero. We combine the synch
  1834.          * distances as if they were variances of the offsets;
  1835.          * the given weights allow us to stay within 16/15 of
  1836.          * the optimum combined variance at each step, and
  1837.          * within 8/7 on any series.
  1838.          *
  1839.          * The breakeven points for the weigths are found
  1840.          * where the smaller distance is 3/8, 3/16 and 1/16
  1841.          * of the sum, respectively.
  1842.          */
  1843.         d = synch[i];
  1844.         a = (d + synch[i + 1]) >> 2;    /* (d1+d2)/4 */
  1845.         b = a>>1;            /* (d1+d2)/8 */
  1846.         if (d <= (b>>1))        /* d1 <= (d1+d2)/16 */
  1847.             /*
  1848.              * Below 1/16, no combination is done,
  1849.              * we just drop the distant offset.
  1850.              */
  1851.             continue;
  1852.         /*
  1853.          * The offsets are combined by shifting their
  1854.          * difference the appropriate number of times and
  1855.          * adding it back in.
  1856.          */
  1857.         diff = coffset[i + 1];
  1858.         L_SUB(&diff, &coffset[i]);
  1859.         L_RSHIFT(&diff);
  1860.         if (d >= a + b) {        /* d1 >= 3(d1+d2)/8 */
  1861.             /*
  1862.              * Above 3/8, the weight is 1/2, and the
  1863.              * combined distance is (d1+d2)/4
  1864.              */
  1865.             d = a;
  1866.         } else {
  1867.             a >>= 2;        /* (d1+d2)/16 */
  1868.             L_RSHIFT(&diff);
  1869.             if (d >= a + b) {    /* d1 >= 3(d1+d2)/16 */
  1870.                 /*
  1871.                  * Between 3/16 and 3/8, the weight
  1872.                  * is 1/4, and the combined distance
  1873.                  * is (9d1+d2)/16 = d1/2 + (d1+d2)/16
  1874.                  */
  1875.                 d = (d>>1) + a;
  1876.             } else {
  1877.                 /*
  1878.                  * Between 1/16 and 3/16, the weight
  1879.                  * is 1/8, and the combined distance
  1880.                  * is (49d1+d2)/64 = 3d1/4+(d1+d2)/64
  1881.                  * (We know d > a, so the shift is safe).
  1882.                  */
  1883.                 L_RSHIFT(&diff);
  1884.                 d -= (d - a)>>2;
  1885.             }
  1886.         }
  1887.         /*
  1888.          * Now we can make the combined offset and insert it
  1889.          * in the list.
  1890.          */
  1891.         L_ADD(&diff, &coffset[i]);
  1892.         for (j = i; j > 0; j--) {
  1893.             if (d >= synch[j - 1])
  1894.                 break;
  1895.             synch[j] = synch[j - 1];
  1896.             coffset[j] = coffset[j - 1];
  1897.         }
  1898.         synch[j] = d;
  1899.         coffset[j] = diff;
  1900.     }
  1901.     /*
  1902.      * The result is put where clock_update() can find it.
  1903.      */
  1904.     sys_offset = coffset[0];
  1905.  
  1906. #ifdef DEBUG
  1907.     if (debug) {
  1908.     printf("combine: offset %s\n", lfptoa(&sys_offset, 6));
  1909.     }
  1910. #endif
  1911.  
  1912. }
  1913.  
  1914.  
  1915.  
  1916. /*
  1917.  * fast_xmit - fast path send for stateless (non-)associations
  1918.  */
  1919. void
  1920. fast_xmit(rbufp, rmode, authentic)
  1921.     struct recvbuf *rbufp;
  1922.     int rmode;
  1923.     int authentic;
  1924. {
  1925.     struct pkt xpkt;
  1926.     register struct pkt *rpkt;
  1927.     u_char xmode;
  1928.     u_short xkey;
  1929.     int docrypt;
  1930.     l_fp xmt_ts;
  1931.     extern void unpeer();
  1932.     extern void auth1crypt();
  1933.     extern int auth2crypt();
  1934.     extern void sendpkt();
  1935.     extern void get_systime();
  1936.     extern char *ntoa();
  1937.  
  1938. #ifdef DEBUG
  1939.     if (debug > 1)
  1940.         printf("fast_xmit(%s, %d)\n", ntoa(&rbufp->recv_srcadr), rmode);
  1941. #endif
  1942.  
  1943.     /*
  1944.      * Make up new packet and send it quick
  1945.      */
  1946.     rpkt = &rbufp->recv_pkt;
  1947.     if (rmode == MODE_ACTIVE)
  1948.         xmode = MODE_PASSIVE;
  1949.     else
  1950.         xmode = MODE_SERVER;
  1951.  
  1952.     if (rbufp->recv_length >= LEN_PKT_MAC) {
  1953.         docrypt = rbufp->recv_length - LEN_PKT_NOMAC;
  1954.         if (authentic)
  1955.             xkey = ntohl(rpkt->keyid);
  1956.         else
  1957.             xkey = 0;
  1958.     } else {
  1959.         docrypt = 0;
  1960.     }
  1961.  
  1962.     xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
  1963.         PKT_VERSION(rpkt->li_vn_mode), xmode);
  1964.     xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
  1965.     xpkt.ppoll = max(NTP_MINPOLL, rpkt->ppoll);
  1966.     xpkt.precision = sys_precision;
  1967.     xpkt.rootdelay = HTONS_FP(sys_rootdelay);
  1968.     xpkt.rootdispersion = HTONS_FP(sys_rootdispersion +
  1969.                        (FP_SECOND >> (-(int)sys_precision)) +
  1970.                        LFPTOFP(&sys_refskew));
  1971.     xpkt.refid = sys_refid;
  1972.     HTONL_FP(&sys_reftime, &xpkt.reftime);
  1973.     xpkt.org = rpkt->xmt;
  1974.     HTONL_FP(&rbufp->recv_time, &xpkt.rec);
  1975.  
  1976.     /*
  1977.      * If we are encrypting, do it.  Else don't.  Easy.
  1978.      */
  1979.     if (docrypt) {
  1980.         int maclen;
  1981.  
  1982.         xpkt.keyid = htonl(xkey);
  1983.         auth1crypt(xkey, (u_long *)&xpkt, LEN_PKT_NOMAC);
  1984.         get_systime(&xmt_ts);
  1985.         L_ADDUF(&xmt_ts, sys_authdelay);
  1986.         HTONL_FP(&xmt_ts, &xpkt.xmt);
  1987.         maclen = auth2crypt(xkey, (u_long *)&xpkt, LEN_PKT_NOMAC);
  1988.         sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, &xpkt,
  1989.             LEN_PKT_NOMAC + maclen);
  1990.     } else {
  1991.         /*
  1992.          * Get xmt timestamp, then send it without mac field
  1993.          */
  1994.         get_systime(&xmt_ts);
  1995.         HTONL_FP(&xmt_ts, &xpkt.xmt);
  1996.         sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, &xpkt,
  1997.             LEN_PKT_NOMAC);
  1998.     }
  1999. }
  2000.  
  2001.  
  2002.  
  2003. /*
  2004.  * init_proto - initialize the protocol module's data
  2005.  */
  2006. void
  2007. init_proto()
  2008. {
  2009.     l_fp dummy;
  2010.  
  2011.     /*
  2012.      * Fill in the sys_* stuff.  Default is don't listen
  2013.      * to broadcasting, don't authenticate.
  2014.      */
  2015.     sys_leap = LEAP_NOTINSYNC;
  2016.     sys_stratum = STRATUM_UNSPEC;
  2017.     sys_precision = (s_char)DEFAULT_SYS_PRECISION;
  2018.     sys_rootdelay = 0;
  2019.     sys_rootdispersion = 0;
  2020.     sys_refid = 0;
  2021.     sys_reftime.l_ui = sys_reftime.l_uf = 0;
  2022.     sys_refskew.l_i = NTP_MAXSKEW; sys_refskew.l_f = 0;
  2023.     sys_peer = 0;
  2024.     sys_poll = NTP_MINPOLL;
  2025.     get_systime(&dummy);
  2026.     sys_lastselect = sys_clock;
  2027.  
  2028.     sys_bclient = 0;
  2029.     sys_bdelay = DEFBROADDELAY;
  2030.  
  2031.     sys_authenticate = 0;
  2032.  
  2033.     sys_stattime = 0;
  2034.     sys_badstratum = 0;
  2035.     sys_oldversionpkt = 0;
  2036.     sys_newversionpkt = 0;
  2037.     sys_badlength = 0;
  2038.     sys_unknownversion = 0;
  2039.     sys_processed = 0;
  2040.     sys_badauth = 0;
  2041.     sys_wanderhold = 0;
  2042. }
  2043.  
  2044.  
  2045. /*
  2046.  * proto_config - configure the protocol module
  2047.  */
  2048. void
  2049. proto_config(item, value)
  2050.     int item;
  2051.     long value;
  2052. {
  2053.     /*
  2054.      * Figure out what he wants to change, then do it
  2055.      */
  2056.     switch (item) {
  2057.     case PROTO_BROADCLIENT:
  2058.         /*
  2059.          * Turn on/off facility to listen to broadcasts
  2060.          */
  2061.         sys_bclient = (int)value;
  2062.         if (sys_bclient)
  2063.             io_setbclient();
  2064.         else
  2065.             io_unsetbclient();
  2066.         break;
  2067.     
  2068.     case PROTO_PRECISION:
  2069.         /*
  2070.          * Set system precision
  2071.          */
  2072.         sys_precision = (s_char)value;
  2073.         break;
  2074.     
  2075.     case PROTO_BROADDELAY:
  2076.         /*
  2077.          * Set default broadcast delay
  2078.          */
  2079.         sys_bdelay = (((u_long)value) + 0x00000800) & 0xfffff000;
  2080.         break;
  2081.     
  2082.     case PROTO_AUTHENTICATE:
  2083.         /*
  2084.          * Specify the use of authenticated data
  2085.          */
  2086.         sys_authenticate = (int)value;
  2087.         break;
  2088.  
  2089.  
  2090.     case PROTO_AUTHDELAY:
  2091.         /*
  2092.          * Provide an authentication delay value.  Round it to
  2093.          * the microsecond.  This is crude.
  2094.          */
  2095.         sys_authdelay = (((u_long)value) + 0x00000800) & 0xfffff000;
  2096.         break;
  2097.  
  2098.     case PROTO_MAXSKEW:
  2099.         /*
  2100.          * Set the maximum skew value
  2101.          */
  2102.         syslog(LOG_ERR,
  2103.                "proto_config: attempt to set maxskew (obsolete)");
  2104.         break;
  2105.  
  2106.     case PROTO_SELECT:
  2107.         /*
  2108.          * Set the selection algorithm.
  2109.          */
  2110.         syslog(LOG_ERR,
  2111.        "proto_config: attempt to set selection algorithm (obsolete)");
  2112.         break;
  2113.  
  2114.     default:
  2115.         /*
  2116.          * Log this error
  2117.          */
  2118.         syslog(LOG_ERR, "proto_config: illegal item %d, value %ld",
  2119.             item, value);
  2120.         break;
  2121.     }
  2122. }
  2123.  
  2124.  
  2125. /*
  2126.  * proto_clr_stats - clear protocol stat counters
  2127.  */
  2128. void
  2129. proto_clr_stats()
  2130. {
  2131.     sys_badstratum = 0;
  2132.     sys_oldversionpkt = 0;
  2133.     sys_newversionpkt = 0;
  2134.     sys_unknownversion = 0;
  2135.     sys_badlength = 0;
  2136.     sys_processed = 0;
  2137.     sys_badauth = 0;
  2138.     sys_wanderhold = 0;
  2139.     sys_stattime = current_time;
  2140. }
  2141.