Add the DragonFly cvs id and perform general cleanups on cvs/rcs/sccs ids. Most
[dragonfly.git] / contrib / ntp / ntpd / ntp_proto.c
1 /*
2  * ntp_proto.c - NTP version 4 protocol machinery
3  *
4  * $FreeBSD: src/contrib/ntp/ntpd/ntp_proto.c,v 1.3.2.1 2001/12/21 17:39:13 roberto Exp $
5  * $DragonFly: src/contrib/ntp/ntpd/Attic/ntp_proto.c,v 1.2 2003/06/17 04:24:04 dillon Exp $
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 #include "ntp_crypto.h"
17
18 #include <stdio.h>
19
20 #if defined(VMS) && defined(VMS_LOCALUNIT)      /*wjm*/
21 #include "ntp_refclock.h"
22 #endif
23
24 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
25 #include <sys/sysctl.h>
26 #endif
27
28 /*
29  * System variables are declared here. See Section 3.2 of the
30  * specification.
31  */
32 u_char  sys_leap;               /* system leap indicator */
33 u_char  sys_stratum;            /* stratum of system */
34 s_char  sys_precision;          /* local clock precision */
35 double  sys_rootdelay;          /* roundtrip delay to primary source */
36 double  sys_rootdispersion;     /* dispersion to primary source */
37 u_int32 sys_refid;              /* reference source for local clock */
38 static  double sys_offset;      /* current local clock offset */
39 l_fp    sys_reftime;            /* time we were last updated */
40 struct  peer *sys_peer;         /* our current peer */
41 struct  peer *sys_prefer;       /* our cherished peer */
42 #ifdef AUTOKEY
43 u_long  sys_automax;            /* maximum session key lifetime */
44 #endif /* AUTOKEY */
45
46 /*
47  * Nonspecified system state variables.
48  */
49 int     sys_bclient;            /* we set our time to broadcasts */
50 double  sys_bdelay;             /* broadcast client default delay */
51 int     sys_authenticate;       /* requre authentication for config */
52 l_fp    sys_authdelay;          /* authentication delay */
53 static  u_long sys_authdly[2];  /* authentication delay shift reg */
54 static  u_char leap_consensus;  /* consensus of survivor leap bits */
55 static  double sys_selerr;      /* select error (squares) */
56 static  double sys_syserr;      /* system error (squares) */
57 keyid_t sys_private;            /* private value for session seed */
58 int     sys_manycastserver;     /* respond to manycast client pkts */
59 u_int sys_survivors;            /* truest of the truechimers */
60 int     peer_ntpdate;           /* active peers in ntpdate mode */
61 #ifdef AUTOKEY
62 char    *sys_hostname;          /* gethostname() name */
63 #endif /* AUTOKEY */
64
65 /*
66  * Statistics counters
67  */
68 u_long  sys_stattime;           /* time when we started recording */
69 u_long  sys_badstratum;         /* packets with invalid stratum */
70 u_long  sys_oldversionpkt;      /* old version packets received */
71 u_long  sys_newversionpkt;      /* new version packets received */
72 u_long  sys_unknownversion;     /* don't know version packets */
73 u_long  sys_badlength;          /* packets with bad length */
74 u_long  sys_processed;          /* packets processed */
75 u_long  sys_badauth;            /* packets dropped because of auth */
76 u_long  sys_limitrejected;      /* pkts rejected due to client count per net */
77
78 static  double  root_distance   P((struct peer *));
79 static  double  clock_combine   P((struct peer **, int));
80 static  void    peer_xmit       P((struct peer *));
81 static  void    fast_xmit       P((struct recvbuf *, int, keyid_t, int));
82 static  void    clock_update    P((void));
83 int     default_get_precision   P((void));
84
85
86 /*
87  * transmit - Transmit Procedure. See Section 3.4.2 of the
88  *      specification.
89  */
90 void
91 transmit(
92         struct peer *peer       /* peer structure pointer */
93         )
94 {
95         int hpoll;
96
97         hpoll = peer->hpoll;
98         if (peer->burst == 0) {
99                 u_char oreach;
100
101                 /*
102                  * The polling state machine. There are two kinds of
103                  * machines, those that never expect a reply (broadcast
104                  * and manycast server modes) and those that do (all
105                  * other modes). The dance is intricate...
106                  */
107                 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
108
109                         /*
110                          * In broadcast mode the poll interval is fixed
111                          * at minpoll and the ttl at ttlmax.
112                          */
113                         hpoll = peer->minpoll;
114                         peer->ttl = peer->ttlmax;
115 #ifdef AUTOKEY
116                 } else if (peer->cast_flags & MDF_ACAST) {
117
118                         /*
119                          * In manycast mode we start with the minpoll
120                          * interval and ttl. However, the actual poll
121                          * interval is eight times the nominal poll
122                          * interval shown here. If fewer than three
123                          * servers are found, the ttl is increased by
124                          * one and we try again. If this continues to
125                          * the max ttl, the poll interval is bumped by
126                          * one and we try again. If at least three
127                          * servers are found, the poll interval
128                          * increases with the system poll interval to
129                          * the max and we continue indefinately.
130                          * However, about once per day when the
131                          * agreement parameters are refreshed, the
132                          * manycast clients are reset and we start from
133                          * the beginning. This is to catch and clamp the
134                          * ttl to the lowest practical value and avoid
135                          * knocking on spurious doors.
136                          */
137                         if (sys_survivors < NTP_MINCLOCK && peer->ttl <
138                             peer->ttlmax)
139                                 peer->ttl++;
140                         hpoll = sys_poll;
141 #endif /* AUTOKEY */
142                 } else {
143
144                         /*
145                          * For associations expecting a reply, the
146                          * watchdog counter is bumped by one if the peer
147                          * has not been heard since the previous poll.
148                          * If the counter reaches the max, the peer is
149                          * demobilized if not configured and just
150                          * cleared if it is, but in this case the poll
151                          * interval is bumped by one.
152                          */
153                         if (peer->unreach < NTP_UNREACH) {
154                                 peer->unreach++;
155                         } else if (!(peer->flags & FLAG_CONFIG)) {
156                                 unpeer(peer);
157                                 clock_select();
158                                 return;
159
160                         } else {
161                                 peer_clear(peer);
162                                 hpoll++;
163                         }
164                 }
165                 oreach = peer->reach;
166                 peer->reach <<= 1;
167                 if (peer->reach == 0) {
168
169                         /*
170                          * If this association has become unreachable,
171                          * clear it and raise a trap.
172                          */
173                         if (oreach != 0) {
174                                 report_event(EVNT_UNREACH, peer);
175                                 peer->timereachable = current_time;
176                                 if (!(peer->flags & FLAG_CONFIG)) {
177                                         unpeer(peer);
178                                         clock_select();
179                                         return;
180                                 } else {
181                                         peer_clear(peer);
182                                         hpoll = peer->minpoll;
183                                 }
184                         }
185                         if (peer->flags & FLAG_IBURST)
186                                 peer->burst = NTP_SHIFT;
187                 } else {
188
189                         /*
190                          * Here the peer is reachable. If it has not
191                          * been heard for three consecutive polls, stuff
192                          * the clock filter. Next, determine the poll
193                          * interval. If the peer is a synchronization
194                          * candidate, use the system poll interval. If
195                          * the peer is not sane, increase it by one. If
196                          * the number of valid updates is not greater
197                          * than half the register size, clamp it to the
198                          * minimum. This is to quickly recover the time
199                          * variables when a noisy peer shows life.
200                          */
201                         if (!(peer->reach & 0x07)) {
202                                 clock_filter(peer, 0., 0., MAXDISPERSE);
203                                 clock_select();
204                         }
205                         if ((peer->stratum > 1 && peer->refid ==
206                             peer->dstadr->sin.sin_addr.s_addr) ||
207                             peer->stratum >= STRATUM_UNSPEC)
208                                 hpoll++;
209                         else
210                                 hpoll = sys_poll;
211                         if (peer->flags & FLAG_BURST)
212                                 peer->burst = NTP_SHIFT;
213                 }
214         } else {
215                 peer->burst--;
216                 if (peer->burst == 0) {
217
218                         /*
219                          * If a broadcast client at this point, the
220                          * burst has concluded, so we switch to client
221                          * mode and purge the keylist, since no further
222                          * transmissions will be made.
223                          */
224                         if (peer->cast_flags & MDF_BCLNT) {
225                                 peer->hmode = MODE_BCLIENT;
226 #ifdef AUTOKEY
227                                 key_expire(peer);
228 #endif /* AUTOKEY */
229                         }
230                         poll_update(peer, hpoll);
231                         clock_select();
232
233                         /*
234                          * If ntpdate mode and the clock has not been
235                          * set and all peers have completed the burst,
236                          * we declare a successful failure.
237                          */
238                         if (mode_ntpdate) {
239                                 peer_ntpdate--;
240                                 if (peer_ntpdate > 0)
241                                         return;
242                                 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
243                                     msyslog(LOG_NOTICE,
244                                     "no reply; clock not set");
245                                 printf(
246                                     "ntpd: no reply; clock not set\n");
247                                 exit(0);
248                         }
249                         return;
250
251                 }
252         }
253         peer->outdate = current_time;
254         poll_update(peer, hpoll);
255
256         /*
257          * We need to be very careful about honking uncivilized time.
258          * Never transmit if in broadcast client mode or access denied.
259          * If in broadcast mode, transmit only if synchronized to a
260          * valid source. 
261          */
262         if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
263                 return;
264         } else if (peer->hmode == MODE_BROADCAST) {
265                 if (sys_peer == NULL)
266                         return;
267         }
268         peer_xmit(peer);
269 }
270
271 /*
272  * receive - Receive Procedure.  See section 3.4.3 in the specification.
273  */
274 void
275 receive(
276         struct recvbuf *rbufp
277         )
278 {
279         register struct peer *peer;
280         register struct pkt *pkt;
281         int hismode;
282         int oflags;
283         int restrict_mask;
284         int has_mac;                    /* length of MAC field */
285         int authlen;                    /* offset of MAC field */
286         int is_authentic;               /* cryptosum ok */
287         keyid_t skeyid;                 /* cryptographic keys */
288         struct sockaddr_in *dstadr_sin; /* active runway */
289 #ifdef AUTOKEY
290         keyid_t pkeyid, tkeyid;         /* cryptographic keys */
291 #endif /* AUTOKEY */
292         struct peer *peer2;
293         int retcode = AM_NOMATCH;
294
295         /*
296          * Monitor the packet and get restrictions. Note that the packet
297          * length for control and private mode packets must be checked
298          * by the service routines. Note that no statistics counters are
299          * recorded for restrict violations, since these counters are in
300          * the restriction routine. Note the careful distinctions here
301          * between a packet with a format error and a packet that is
302          * simply discarded without prejudice. Some restrictions have to
303          * be handled later in order to generate a kiss-of-death packet.
304          */
305         ntp_monitor(rbufp);
306         restrict_mask = restrictions(&rbufp->recv_srcadr);
307 #ifdef DEBUG
308         if (debug > 2)
309                 printf("receive: at %ld %s<-%s restrict %02x\n",
310                     current_time, ntoa(&rbufp->dstadr->sin),
311                     ntoa(&rbufp->recv_srcadr), restrict_mask);
312 #endif
313         if (restrict_mask & RES_IGNORE)
314                 return;                         /* no anything */
315         if (!(SRCPORT(&rbufp->recv_srcadr) == NTP_PORT ||
316             SRCPORT(&rbufp->recv_srcadr) >= IPPORT_RESERVED)) {
317                 sys_badlength++;
318                 return;                         /* invalid port */
319         }
320         pkt = &rbufp->recv_pkt;
321         if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
322                 sys_newversionpkt++;            /* new version */
323         } else if (!(restrict_mask & RES_VERSION) &&
324             PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
325                 sys_oldversionpkt++;            /* old version */
326         } else {
327                 sys_unknownversion++;
328                 return;                         /* invalid version */
329         }
330         if (PKT_MODE(pkt->li_vn_mode) == MODE_PRIVATE) {
331                 if (restrict_mask & RES_NOQUERY)
332                         return;                 /* no query private */
333                 process_private(rbufp, ((restrict_mask &
334                     RES_NOMODIFY) == 0));
335                 return;
336         }
337         if (PKT_MODE(pkt->li_vn_mode) == MODE_CONTROL) {
338                 if (restrict_mask & RES_NOQUERY)
339                         return;                 /* no query control */
340                 process_control(rbufp, restrict_mask);
341                 return;
342         }
343         if (rbufp->recv_length < LEN_PKT_NOMAC) {
344                 sys_badlength++;
345                 return;                         /* runt packet */
346         }
347
348         /*
349          * Validate mode. Note that NTPv1 is no longer supported.
350          */
351         hismode = (int)PKT_MODE(pkt->li_vn_mode);
352         if (hismode == MODE_UNSPEC) {
353                 sys_badlength++;
354                 return;                         /* invalid mode */
355         }
356
357         /*
358          * Discard broadcast packets received on the wildcard interface
359          * or if not enabled as broadcast client.
360          */
361         if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
362             (rbufp->dstadr == any_interface || !sys_bclient))
363                 return;
364
365         /*
366          * Parse the extension field if present. We figure out whether
367          * an extension field is present by measuring the MAC size. If
368          * the number of words following the packet header is 0 or 1, no
369          * MAC is present and the packet is not authenticated. If 1, the
370          * packet is a reply to a previous request that failed to
371          * authenticate. If 3, the packet is authenticated with DES; if
372          * 5, the packet is authenticated with MD5. If greater than 5,
373          * an extension field is present. If 2 or 4, the packet is a
374          * runt and goes poof! with a brilliant flash.
375          */
376         skeyid = 0;
377 #ifdef AUTOKEY
378         pkeyid = tkeyid = 0;
379 #endif /* AUTOKEY */
380         authlen = LEN_PKT_NOMAC;
381         while ((has_mac = rbufp->recv_length - authlen) > 0) {
382                 int temp;
383
384                 if (has_mac % 4 != 0 || has_mac < 0) {
385                         sys_badlength++;
386                         return;
387                 }
388                 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
389                     MAX_MAC_LEN) {
390                         skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
391                         break;
392
393                 } else if (has_mac > MAX_MAC_LEN) {
394                         temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
395                             0xffff;
396                         if (temp < 4 || temp % 4 != 0) {
397                                 sys_badlength++;
398                                 return;
399                         }
400                         authlen += temp;
401                 } else {
402                         sys_badlength++;
403                         return;
404                 }
405         }
406
407         /*
408          * We have tossed out as many buggy packets as possible early in
409          * the game to reduce the exposure to a clogging attack. Now we
410          * have to burn some cycles to find the association and
411          * authenticate the packet if required. Note that we burn only
412          * MD5 or DES cycles, again to reduce exposure. There may be no
413          * matching association and that's okay.
414          *
415          * More on the autokey mambo. Normally the local interface is
416          * found when the association was mobilized with respect to a
417          * designated remote address. We assume packets arriving from
418          * the remote address arrive via this interface and the local
419          * address used to construct the autokey is the unicast address
420          * of the interface. However, if the sender is a broadcaster,
421          * the interface broadcast address is used instead.
422          * Notwithstanding this technobabble, if the sender is a
423          * multicaster, the broadcast address is null, so we use the
424          * unicast address anyway. Don't ask.
425          */
426         peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
427             hismode, &retcode);
428         is_authentic = 0;
429         dstadr_sin = &rbufp->dstadr->sin;
430         if (has_mac == 0) {
431 #ifdef DEBUG
432                 if (debug)
433                         printf("receive: at %ld %s<-%s mode %d code %d\n",
434                             current_time, ntoa(&rbufp->dstadr->sin),
435                             ntoa(&rbufp->recv_srcadr), hismode, retcode);
436 #endif
437         } else {
438 #ifdef AUTOKEY
439                 /*
440                  * For autokey modes, generate the session key
441                  * and install in the key cache. Use the socket
442                  * broadcast or unicast address as appropriate.
443                  */
444                 if (skeyid > NTP_MAXKEY) {
445                 
446                         /*
447                          * More on the autokey dance (AKD). A cookie is
448                          * constructed from public and private values.
449                          * For broadcast packets, the cookie is public
450                          * (zero). For packets that match no
451                          * association, the cookie is hashed from the
452                          * addresses and private value. For server
453                          * packets, the cookie was previously obtained
454                          * from the server. For symmetric modes, the
455                          * cookie was previously constructed using an
456                          * agreement protocol; however, should PKI be
457                          * unavailable, we construct a fake agreement as
458                          * the EXOR of the peer and host cookies.
459                          *
460                          * hismode      ephemeral       persistent
461                          * =======================================
462                          * active       0               cookie#
463                          * passive      0%              cookie#
464                          * client       sys cookie      0%
465                          * server       0%              sys cookie
466                          * broadcast    0               0
467                          *
468                          * # if unsync, 0
469                          * % can't happen
470                          */
471                         if (hismode == MODE_BROADCAST) {
472
473                                 /*
474                                  * For broadcaster, use the interface
475                                  * broadcast address when available;
476                                  * otherwise, use the unicast address
477                                  * found when the association was
478                                  * mobilized.
479                                  */
480                                 pkeyid = 0;
481                                 if (rbufp->dstadr->bcast.sin_addr.s_addr
482                                     != 0)
483                                         dstadr_sin =
484                                             &rbufp->dstadr->bcast;
485                         } else if (peer == NULL) {
486                                 pkeyid = session_key(
487                                     &rbufp->recv_srcadr, dstadr_sin, 0,
488                                     sys_private, 0);
489                         } else {
490                                 pkeyid = peer->pcookie.key;
491                         }
492
493                         /*
494                          * The session key includes both the public
495                          * values and cookie. In case of an extension
496                          * field, the cookie used for authentication
497                          * purposes is zero. Note the hash is saved for
498                          * use later in the autokey mambo.
499                          */
500                         if (authlen > LEN_PKT_NOMAC && pkeyid != 0) {
501                                 session_key(&rbufp->recv_srcadr,
502                                     dstadr_sin, skeyid, 0, 2);
503                                 tkeyid = session_key(
504                                     &rbufp->recv_srcadr, dstadr_sin,
505                                     skeyid, pkeyid, 0);
506                         } else {
507                                 tkeyid = session_key(
508                                     &rbufp->recv_srcadr, dstadr_sin,
509                                     skeyid, pkeyid, 2);
510                         }
511
512                 }
513 #endif /* AUTOKEY */
514
515                 /*
516                  * Compute the cryptosum. Note a clogging attack may
517                  * succeed in bloating the key cache. If an autokey,
518                  * purge it immediately, since we won't be needing it
519                  * again.
520                  */
521                 if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
522                     has_mac))
523                         is_authentic = 1;
524                 else
525                         sys_badauth++;
526 #ifdef AUTOKEY
527                 if (skeyid > NTP_MAXKEY)
528                         authtrust(skeyid, 0);
529 #endif /* AUTOKEY */
530 #ifdef DEBUG
531                 if (debug)
532                         printf(
533                             "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
534                             current_time, ntoa(dstadr_sin),
535                             ntoa(&rbufp->recv_srcadr), hismode, retcode,
536                             skeyid, authlen, has_mac,
537                             is_authentic);
538 #endif
539         }
540
541         /*
542          * The association matching rules are implemented by a set of
543          * routines and a table in ntp_peer.c. A packet matching an
544          * association is processed by that association. If not and
545          * certain conditions prevail, then an ephemeral association is
546          * mobilized: a broadcast packet mobilizes a broadcast client
547          * aassociation; a server packet mobilizes a client association;
548          * a symmetric active packet mobilizes a symmetric passive
549          * association. And, the adventure continues...
550          */
551         switch (retcode) {
552         case AM_FXMIT:
553
554                 /*
555                  * This is a client mode packet not matching a known
556                  * association. If from a manycast client we run a few
557                  * sanity checks before deciding to send a unicast
558                  * server response. Otherwise, it must be a client
559                  * request, so send a server response and go home.
560                  */
561                 if (sys_manycastserver && (rbufp->dstadr->flags &
562                     INT_MULTICAST)) {
563         
564                         /*
565                          * We are picky about responding to a
566                          * manycaster. There is no reason to respond to
567                          * a request if our time is worse than the
568                          * manycaster. We certainly don't reply if not
569                          * synchronized to proventic time.
570                          */
571                         if (sys_peer == NULL)
572                                 return;
573
574                         /*
575                          * We don't reply if the our stratum is greater
576                          * than the manycaster.
577                          */ 
578                         if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
579                                 return;
580                 }
581
582                 /*
583                  * Note that we don't require an authentication check
584                  * here, since we can't set the system clock; but, we do
585                  * set the key ID to zero to tell the caller about this.
586                  */
587                 if (is_authentic)
588                         fast_xmit(rbufp, MODE_SERVER, skeyid,
589                             restrict_mask);
590                 else
591                         fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
592                 return;
593
594         case AM_MANYCAST:
595
596                 /*
597                  * This is a server mode packet returned in response to
598                  * a client mode packet sent to a multicast group
599                  * address. The originate timestamp is a good nonce to
600                  * reliably associate the reply with what was sent. If
601                  * there is no match, that's curious and could be an
602                  * intruder attempting to clog, so we just ignore it.
603                  *
604                  * First, make sure the packet is authentic. If so and
605                  * the manycast association is found, we mobilize a
606                  * client mode association, copy pertinent variables
607                  * from the manycast to the client mode association and
608                  * wind up the spring.
609                  *
610                  * There is an implosion hazard at the manycast client,
611                  * since the manycast servers send the server packet
612                  * immediately.
613                  */
614                 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
615                     RES_NOPEER)) || (sys_authenticate &&
616                     !is_authentic))
617                         return;
618
619                 peer2 = findmanycastpeer(rbufp);
620                 if (peer2 == 0)
621                         return;
622
623                 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
624                     MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
625                     sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
626                     (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
627                     MDF_UCAST, 0, skeyid);
628                 if (peer == NULL)
629                         return;
630                 break;
631
632         case AM_NEWPASS:
633
634                 /*
635                  * This is the first packet received from a symmetric
636                  * active peer. First, make sure the packet is
637                  * authentic. If so, mobilize a symmetric passive
638                  * association.
639                  */
640                 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
641                     RES_NOPEER)) || (sys_authenticate &&
642                     !is_authentic)) {
643                         fast_xmit(rbufp, MODE_PASSIVE, 0,
644                             restrict_mask);
645                         return;
646                 }
647                 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
648                     MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
649                     sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
650                     FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
651                 if (peer == NULL)
652                         return;
653                 break;
654
655         case AM_NEWBCL:
656
657                 /*
658                  * This is the first packet received from a broadcast
659                  * server. First, make sure the packet is authentic, not
660                  * restricted and that we are a broadcast or multicast
661                  * client. If so, mobilize a broadcast client
662                  * association.
663                  */
664                 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
665                     RES_NOPEER)) || (sys_authenticate &&
666                     !is_authentic) || !sys_bclient)
667                         return;
668
669                 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
670                     MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
671                     sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
672                     FLAG_IBURST | (sys_authenticate ?
673                     FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
674 #ifdef AUTOKEY
675 #ifdef PUBKEY
676                 if (peer == NULL)
677                         return;
678                 if (peer->flags & FLAG_SKEY)
679                         crypto_recv(peer, rbufp);
680 #endif /* PUBKEY */
681 #endif /* AUTOKEY */
682                 return;
683
684         case AM_POSSBCL:
685         case AM_PROCPKT:
686
687                 /*
688                  * Happiness and nothing broke. Earn some revenue.
689                  */
690                 break;
691
692         default:
693
694                 /*
695                  * Invalid mode combination. Leave the island
696                  * immediately.
697                  */
698 #ifdef DEBUG
699                 if (debug)
700                         printf("receive: bad protocol %d\n", retcode);
701 #endif
702                 return;
703         }
704
705         /*
706          * If the peer isn't configured, set his authenable and autokey
707          * status based on the packet. Once the status is set, it can't
708          * be unset. It seems like a silly idea to do this here, rather
709          * in the configuration routine, but in some goofy cases the
710          * first packet sent cannot be authenticated and we need a way
711          * for the dude to change his mind.
712          */
713         oflags = peer->flags;
714         peer->timereceived = current_time;
715         peer->received++;
716         if (!(peer->flags & FLAG_CONFIG) && has_mac) {
717                 peer->flags |= FLAG_AUTHENABLE;
718 #ifdef AUTOKEY
719                 if (skeyid > NTP_MAXKEY)
720                         peer->flags |= FLAG_SKEY;
721 #endif /* AUTOKEY */
722         }
723
724         /*
725          * A valid packet must be from an authentic and allowed source.
726          * All packets must pass the authentication allowed tests.
727          * Autokey authenticated packets must pass additional tests and
728          * public-key authenticated packets must have the credentials
729          * verified. If all tests are passed, the packet is forwarded
730          * for processing. If not, the packet is discarded and the
731          * association demobilized if appropriate.
732          */
733         peer->flash = 0;
734         if (is_authentic) {
735                 peer->flags |= FLAG_AUTHENTIC;
736         } else {
737                 peer->flags &= ~FLAG_AUTHENTIC;
738         }
739         if (peer->hmode == MODE_BROADCAST &&
740             (restrict_mask & RES_DONTTRUST))    /* test 4 */
741                 peer->flash |= TEST4;           /* access denied */
742         if (peer->flags & FLAG_AUTHENABLE) {
743                 if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
744                         peer->flash |= TEST5;   /* auth failed */
745                 else if (!(oflags & FLAG_AUTHENABLE))
746                         report_event(EVNT_PEERAUTH, peer);
747         }
748         if (peer->flash) {
749 #ifdef DEBUG
750                 if (debug)
751                         printf("receive: bad auth %03x\n", peer->flash);
752 #endif
753                 return;
754         }
755
756 #ifdef AUTOKEY
757         /*
758          * More autokey dance. The rules of the cha-cha are as follows:
759          *
760          * 1. If there is no key or the key is not auto, do nothing.
761          *
762          * 2. If an extension field contains a verified signature, it is
763          *    self-authenticated and we sit the dance.
764          *
765          * 3. If this is a server reply, check only to see that the
766          *    transmitted key ID matches the received key ID.
767          *
768          * 4. Check to see that one or more hashes of the current key ID
769          *    matches the previous key ID or ultimate original key ID
770          *    obtained from the broadcaster or symmetric peer. If no
771          *    match, sit the dance and wait for timeout.
772          */
773         if (peer->flags & FLAG_SKEY) {
774                 peer->flash |= TEST10;
775                 crypto_recv(peer, rbufp);
776                 poll_update(peer, peer->hpoll);
777                 if (hismode == MODE_SERVER) {
778                         if (skeyid == peer->keyid)
779                                 peer->flash &= ~TEST10;
780                 } else if (!peer->flash & TEST10) {
781                         peer->pkeyid = skeyid;
782                 } else {
783                         int i;
784
785                         for (i = 0; ; i++) {
786                                 if (tkeyid == peer->pkeyid ||
787                                     tkeyid == peer->recauto.key) {
788                                         peer->flash &= ~TEST10;
789                                         peer->pkeyid = skeyid;
790                                         break;
791                                 }
792                                 if (i > peer->recauto.seq)
793                                         break;
794                                 tkeyid = session_key(
795                                     &rbufp->recv_srcadr, dstadr_sin,
796                                     tkeyid, pkeyid, 0);
797                         }
798                 }
799 #ifdef PUBKEY
800
801                 /*
802                  * This is delicious. Ordinarily, we kick out all errors
803                  * at this point; however, in symmetric mode and just
804                  * warming up, an unsynchronized peer must inject the
805                  * timestamps, even if it fails further up the road. So,
806                  * let the dude by here, but only if the jerk is not yet
807                  * reachable. After that, he's on his own.
808                  */
809                 if (!(peer->flags & FLAG_PROVEN))
810                         peer->flash |= TEST11;
811                 if (peer->flash && peer->reach) {
812 #ifdef DEBUG
813                         if (debug)
814                                 printf("packet: bad autokey %03x\n",
815                                     peer->flash);
816 #endif
817                         return;
818                 }
819 #endif /* PUBKEY */
820         }
821 #endif /* AUTOKEY */
822
823         /*
824          * We have survived the gaunt. Forward to the packet routine. If
825          * a symmetric passive association has been mobilized and the
826          * association doesn't deserve to live, it will die in the
827          * transmit routine if not reachable after timeout.
828          */
829         process_packet(peer, pkt, &rbufp->recv_time);
830 }
831
832
833 /*
834  * process_packet - Packet Procedure, a la Section 3.4.4 of the
835  *      specification. Or almost, at least. If we're in here we have a
836  *      reasonable expectation that we will be having a long term
837  *      relationship with this host.
838  */
839 void
840 process_packet(
841         register struct peer *peer,
842         register struct pkt *pkt,
843         l_fp *recv_ts
844         )
845 {
846         l_fp t10, t23;
847         double p_offset, p_del, p_disp;
848         double dtemp;
849         l_fp p_rec, p_xmt, p_org, p_reftime;
850         l_fp ci;
851         int pmode, pleap, pstratum;
852
853         /*
854          * Swap header fields and keep the books. The books amount to
855          * the receive timestamp and poll interval in the header. We
856          * need these even if there are other problems in order to crank
857          * up the state machine.
858          */
859         sys_processed++;
860         peer->processed++;
861         p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
862         p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
863         NTOHL_FP(&pkt->reftime, &p_reftime);
864         NTOHL_FP(&pkt->rec, &p_rec);
865         NTOHL_FP(&pkt->xmt, &p_xmt);
866         if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST)
867                 NTOHL_FP(&pkt->org, &p_org);
868         else
869                 p_org = peer->rec;
870
871         /*
872          * Test for old, duplicate or unsynch packets (tests 1-3).
873          */
874         peer->rec = *recv_ts;
875         pmode = PKT_MODE(pkt->li_vn_mode);
876         pleap = PKT_LEAP(pkt->li_vn_mode);
877         pstratum = PKT_TO_STRATUM(pkt->stratum);
878         if (L_ISHIS(&peer->org, &p_xmt))        /* count old packets */
879                 peer->oldpkt++;
880         if (L_ISEQU(&peer->org, &p_xmt))        /* 1 */
881                 peer->flash |= TEST1;           /* dupe */
882         if (pmode != MODE_BROADCAST) {
883                 if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
884                         peer->flash |= TEST2;   /* bogus */
885                 if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
886                         peer->flash |= TEST3;   /* unsynch */
887         }
888         if (L_ISZERO(&p_xmt))                   /* 3 */
889                 peer->flash |= TEST3;           /* unsynch */
890         peer->org = p_xmt;
891
892         /*
893          * If tests 1-3 fail, the packet is discarded leaving only the
894          * receive and origin timestamps and poll interval, which is
895          * enough to get the protocol started.
896          */
897         if (peer->flash) {
898 #ifdef DEBUG
899                 if (debug)
900                         printf("packet: bad data %03x\n",
901                             peer->flash);
902 #endif
903                 return;
904         }
905
906         /*
907          * A kiss-of-death (kod) packet is returned by a server in case
908          * the client is denied access. It consists of the client
909          * request packet with the leap bits indicating never
910          * synchronized, stratum zero and reference ID field the ASCII
911          * string "DENY". If the packet originate timestamp matches the
912          * association transmit timestamp the kod is legitimate. If the
913          * peer leap bits indicate never synchronized, this must be
914          * access deny and the association is disabled; otherwise this
915          * must be a limit reject. In either case a naughty message is
916          * forced to the system log.
917          */
918         if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
919             memcmp(&pkt->refid, "DENY", 4) == 0) {
920                 if (peer->leap == LEAP_NOTINSYNC) {
921                         peer->stratum = STRATUM_UNSPEC;
922                         peer->flash |= TEST4;
923                         memcpy(&peer->refid, &pkt->refid, 4);
924                         msyslog(LOG_INFO, "access denied");
925                 } else {
926                         msyslog(LOG_INFO, "limit reject");
927                 }
928                 return;
929         }
930
931         /*
932          * Test for valid peer data (tests 6-8)
933          */
934         ci = p_xmt;
935         L_SUB(&ci, &p_reftime);
936         LFPTOD(&ci, dtemp);
937         if (pleap == LEAP_NOTINSYNC ||          /* 6 */
938             pstratum >= STRATUM_UNSPEC || dtemp < 0)
939                 peer->flash |= TEST6;           /* bad synch */
940         if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
941                 if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
942                         peer->flash |= TEST7;   /* bad stratum */
943                         sys_badstratum++;
944                 }
945         }
946         if (p_del < 0 || p_disp < 0 || p_del /  /* 8 */
947             2 + p_disp >= MAXDISPERSE)
948                 peer->flash |= TEST8;           /* bad peer distance */
949         if (peer->flash) {
950 #ifdef DEBUG
951                 if (debug)
952                         printf("packet: bad header %03x\n",
953                             peer->flash);
954 #endif
955                 return;
956         }
957
958         /*
959          * The header is valid. Capture the remaining header values and
960          * mark as reachable.
961          */
962         record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
963             &p_rec, &p_xmt, &peer->rec);
964         peer->leap = pleap;
965         peer->pmode = pmode;
966         peer->stratum = pstratum;
967         peer->ppoll = pkt->ppoll;
968         peer->precision = pkt->precision;
969         peer->rootdelay = p_del;
970         peer->rootdispersion = p_disp;
971         peer->refid = pkt->refid;
972         peer->reftime = p_reftime;
973         if (!(peer->reach)) {
974                 report_event(EVNT_REACH, peer);
975                 peer->timereachable = current_time;
976         }
977         peer->reach |= 1;
978         peer->unreach = 0;
979         poll_update(peer, peer->hpoll);
980
981         /*
982          * If running in a client/server association, calculate the
983          * clock offset c, roundtrip delay d and dispersion e. We use
984          * the equations (reordered from those in the spec). Note that,
985          * in a broadcast association, org has been set to the time of
986          * last reception. Note the computation of dispersion includes
987          * the system precision plus that due to the frequency error
988          * since the originate time.
989          *
990          * c = ((t2 - t3) + (t1 - t0)) / 2
991          * d = (t2 - t3) - (t1 - t0)
992          * e = (org - rec) (seconds only)
993          */
994         t10 = p_xmt;                    /* compute t1 - t0 */
995         L_SUB(&t10, &peer->rec);
996         t23 = p_rec;                    /* compute t2 - t3 */
997         L_SUB(&t23, &p_org);
998         ci = t10;
999         p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
1000
1001         /*
1002          * If running in a broadcast association, the clock offset is
1003          * (t1 - t0) corrected by the one-way delay, but we can't
1004          * measure that directly. Therefore, we start up in MODE_CLIENT
1005          * mode, set FLAG_MCAST and exchange eight messages to determine
1006          * the clock offset. When the last message is sent, we switch to
1007          * MODE_BCLIENT mode. The next broadcast message after that
1008          * computes the broadcast offset and clears FLAG_MCAST.
1009          */
1010         if (pmode == MODE_BROADCAST) {
1011                 if (peer->flags & FLAG_MCAST) {
1012                         LFPTOD(&ci, p_offset);
1013                         peer->estbdelay = peer->offset - p_offset;
1014                         if (peer->hmode == MODE_CLIENT)
1015                                 return;
1016
1017                         peer->flags &= ~FLAG_MCAST;
1018                 }
1019                 DTOLFP(peer->estbdelay, &t10);
1020                 L_ADD(&ci, &t10);
1021                 p_del = peer->delay;
1022         } else {
1023                 L_ADD(&ci, &t23);
1024                 L_RSHIFT(&ci);
1025                 L_SUB(&t23, &t10);
1026                 LFPTOD(&t23, p_del);
1027         }
1028         p_del = max(p_del, LOGTOD(sys_precision));
1029         LFPTOD(&ci, p_offset);
1030         if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1031             p_disp >= MAXDISPERSE)              /* 9 */
1032                 peer->flash |= TEST9;           /* bad peer distance */
1033
1034         /*
1035          * If any flasher bits remain set at this point, abandon ship.
1036          * Otherwise, forward to the clock filter.
1037          */
1038         if (peer->flash) {
1039 #ifdef DEBUG
1040                 if (debug)
1041                         printf("packet: bad packet data %03x\n",
1042                             peer->flash);
1043 #endif
1044                 return;
1045         }
1046         clock_filter(peer, p_offset, p_del, p_disp);
1047         clock_select();
1048         record_peer_stats(&peer->srcadr, ctlpeerstatus(peer),
1049             peer->offset, peer->delay, peer->disp,
1050             SQRT(peer->jitter));
1051 }
1052
1053
1054 /*
1055  * clock_update - Called at system process update intervals.
1056  */
1057 static void
1058 clock_update(void)
1059 {
1060         u_char oleap;
1061         u_char ostratum;
1062
1063         /*
1064          * Reset/adjust the system clock. Do this only if there is a
1065          * system peer and we haven't seen that peer lately. Watch for
1066          * timewarps here.
1067          */
1068         if (sys_peer == NULL)
1069                 return;
1070         if (sys_peer->pollsw == FALSE || sys_peer->burst > 0)
1071                 return;
1072         sys_peer->pollsw = FALSE;
1073 #ifdef DEBUG
1074         if (debug)
1075                 printf("clock_update: at %ld assoc %d \n", current_time,
1076                     peer_associations);
1077 #endif
1078         oleap = sys_leap;
1079         ostratum = sys_stratum;
1080         switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1081
1082         /*
1083          * Clock is too screwed up. Just exit for now.
1084          */
1085         case -1:
1086                 report_event(EVNT_SYSFAULT, (struct peer *)0);
1087                 exit(1);
1088                 /*NOTREACHED*/
1089
1090         /*
1091          * Clock was stepped. Flush all time values of all peers.
1092          */
1093         case 1:
1094                 clear_all();
1095                 sys_peer = NULL;
1096                 sys_stratum = STRATUM_UNSPEC;
1097                 sys_poll = NTP_MINPOLL;
1098                 NLOG(NLOG_SYNCSTATUS)
1099                     msyslog(LOG_INFO, "synchronisation lost");
1100                 report_event(EVNT_CLOCKRESET, (struct peer *)0);
1101                 break;
1102
1103         /*
1104          * Update the system stratum, leap bits, root delay, root
1105          * dispersion, reference ID and reference time. We also update
1106          * select dispersion and max frequency error. If the leap
1107          * changes, we gotta reroll the keys.
1108          */
1109         default:
1110                 sys_stratum = sys_peer->stratum + 1;
1111                 if (sys_stratum == 1)
1112                         sys_refid = sys_peer->refid;
1113                 else
1114                         sys_refid = sys_peer->srcadr.sin_addr.s_addr;
1115                 sys_reftime = sys_peer->rec;
1116                 sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1117                 sys_leap = leap_consensus;
1118         }
1119         if (oleap == LEAP_NOTINSYNC) {
1120                 report_event(EVNT_SYNCCHG, (struct peer *)0);
1121 #ifdef AUTOKEY
1122                 expire_all();
1123 #endif /* AUTOKEY */
1124         }
1125         if (ostratum != sys_stratum)
1126                 report_event(EVNT_PEERSTCHG, (struct peer *)0);
1127 }
1128
1129
1130 /*
1131  * poll_update - update peer poll interval
1132  */
1133 void
1134 poll_update(
1135         struct peer *peer,
1136         int hpoll
1137         )
1138 {
1139 #ifdef AUTOKEY
1140         int oldpoll;
1141 #endif /* AUTOKEY */
1142
1143         /*
1144          * A little foxtrot to determine what controls the poll
1145          * interval. If the peer is reachable, but the last four polls
1146          * have not been answered, use the minimum. If declared
1147          * truechimer, use the system poll interval. This allows each
1148          * association to ramp up the poll interval for useless sources
1149          * and to clamp it to the minimum when first starting up.
1150          */
1151 #ifdef AUTOKEY
1152         oldpoll = peer->kpoll;
1153 #endif /* AUTOKEY */
1154         if (hpoll > peer->maxpoll)
1155                 peer->hpoll = peer->maxpoll;
1156         else if (hpoll < peer->minpoll)
1157                 peer->hpoll = peer->minpoll;
1158         else
1159                 peer->hpoll = hpoll;
1160
1161         /*
1162          * Bit of adventure here. If during a burst and not timeout,
1163          * just slink away. If timeout, figure what the next timeout
1164          * should be. If IBURST or a reference clock, use one second. If
1165          * not and the dude was reachable during the previous poll
1166          * interval, randomize over 1-4 seconds; otherwise, randomize
1167          * over 15-18 seconds. This is to give time for a modem to
1168          * complete the call, for example. If not during a burst,
1169          * randomize over the poll interval -1 to +2 seconds.
1170          *
1171          * In case of manycast server, make the poll interval, which is
1172          * axtually the manycast beacon interval, eight times the system
1173          * poll interval. Normally when the host poll interval settles
1174          * up to 17.1 s, the beacon interval settles up to 2.3 hours.
1175          */
1176         if (peer->burst > 0) {
1177                 if (peer->nextdate != current_time)
1178                         return;
1179 #ifdef REFCLOCK
1180                 else if (peer->flags & FLAG_REFCLOCK)
1181                         peer->nextdate++;
1182 #endif
1183                 else if (peer->reach & 0x1)
1184                         peer->nextdate += RANDPOLL(BURST_INTERVAL2);
1185                 else
1186                         peer->nextdate += RANDPOLL(BURST_INTERVAL1);
1187         } else if (peer->cast_flags & MDF_ACAST) {
1188                 if (sys_survivors < NTP_MINCLOCK)
1189                         peer->kpoll = peer->hpoll;
1190                 else
1191                         peer->kpoll = peer->hpoll + 3;
1192                 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1193         } else {
1194                 peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1195                     peer->minpoll);
1196                 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1197         }
1198         if (peer->nextdate < current_time)
1199                 peer->nextdate = current_time;
1200 #ifdef AUTOKEY
1201         /*
1202          * Bit of crass arrogance at this point. If the poll interval
1203          * has changed and we have a keylist, the lifetimes in the
1204          * keylist are probably bogus. In this case purge the keylist
1205          * and regenerate it later.
1206          */
1207         if (peer->kpoll != oldpoll)
1208                 key_expire(peer);
1209 #endif /* AUTOKEY */
1210 #ifdef DEBUG
1211         if (debug > 1)
1212                 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1213                     current_time, ntoa(&peer->srcadr), peer->flags,
1214                     peer->kpoll, peer->burst, peer->outdate,
1215                     peer->nextdate);
1216 #endif
1217 }
1218
1219
1220 /*
1221  * clear - clear peer filter registers.  See Section 3.4.8 of the spec.
1222  */
1223 void
1224 peer_clear(
1225         register struct peer *peer
1226         )
1227 {
1228         register int i;
1229         u_long u_rand;
1230
1231         /*
1232          * If cryptographic credentials have been acquired, toss them to
1233          * Valhalla. Note that autokeys are ephemeral, in that they are
1234          * tossed immediately upon use. Therefore, the keylist can be
1235          * purged anytime without needing to preserve random keys. Note
1236          * that, if the peer is purged, the cryptographic variables are
1237          * purged, too. This makes it much harder to sneak in some
1238          * unauthenticated data in the clock filter.
1239          */
1240 #ifdef DEBUG
1241         if (debug)
1242                 printf("peer_clear: at %ld assoc ID %d\n", current_time,
1243                     peer->associd);
1244 #endif
1245 #ifdef AUTOKEY
1246         key_expire(peer);
1247 #ifdef PUBKEY
1248         if (peer->keystr != NULL)
1249                 free(peer->keystr);
1250         if (peer->pubkey.ptr != NULL)
1251                 free(peer->pubkey.ptr);
1252         if (peer->certif.ptr != NULL)
1253                 free(peer->certif.ptr);
1254 #endif /* PUBKEY */
1255 #endif /* AUTOKEY */
1256         memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1257
1258         /*
1259          * If he dies as a broadcast client, he comes back to life as
1260          * a broadcast client in client mode in order to recover the
1261          * initial autokey values. Note that there is no need to call
1262          * clock_select(), since the perp has already been voted off
1263          * the island at this point.
1264          */
1265         if (peer->cast_flags & MDF_BCLNT) {
1266                 peer->flags |= FLAG_MCAST;
1267                 peer->hmode = MODE_CLIENT;
1268         }
1269         peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1270         peer->estbdelay = sys_bdelay;
1271         peer->hpoll = peer->kpoll = peer->minpoll;
1272         peer->ppoll = peer->maxpoll;
1273         peer->pollsw = FALSE;
1274         peer->jitter = MAXDISPERSE;
1275         peer->epoch = current_time;
1276 #ifdef REFCLOCK
1277         if (!(peer->flags & FLAG_REFCLOCK)) {
1278                 peer->leap = LEAP_NOTINSYNC;
1279                 peer->stratum = STRATUM_UNSPEC;
1280         }
1281 #endif
1282         for (i = 0; i < NTP_SHIFT; i++) {
1283                 peer->filter_order[i] = i;
1284                 peer->filter_disp[i] = MAXDISPERSE;
1285                 peer->filter_epoch[i] = current_time;
1286         }
1287
1288         /*
1289          * Randomize the first poll over 1-16s to avoid bunching.
1290          */
1291         peer->update = peer->outdate = current_time;
1292         u_rand = RANDOM;
1293         peer->nextdate = current_time + (u_rand & ((1 <<
1294             BURST_INTERVAL1) - 1)) + 1;
1295 }
1296
1297
1298 /*
1299  * clock_filter - add incoming clock sample to filter register and run
1300  *                the filter procedure to find the best sample.
1301  */
1302 void
1303 clock_filter(
1304         register struct peer *peer,     /* peer structure pointer */
1305         double sample_offset,           /* clock offset */
1306         double sample_delay,            /* roundtrip delay */
1307         double sample_disp              /* dispersion */
1308         )
1309 {
1310         double dst[NTP_SHIFT];          /* distance vector */
1311         int ord[NTP_SHIFT];             /* index vector */
1312         register int i, j, k, m;
1313         double dsp, jit, dtemp, etemp;
1314
1315         /*
1316          * Shift the new sample into the register and discard the oldest
1317          * one. The new offset and delay come directly from the
1318          * timestamp calculations. The dispersion grows from the last
1319          * outbound packet or reference clock update to the present time
1320          * and increased by the sum of the peer precision and the system
1321          * precision. The delay can sometimes swing negative due to
1322          * frequency skew, so it is clamped non-negative.
1323          */
1324         dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1325             sample_disp, MAXDISPERSE);
1326         j = peer->filter_nextpt;
1327         peer->filter_offset[j] = sample_offset;
1328         peer->filter_delay[j] = max(0, sample_delay);
1329         peer->filter_disp[j] = dsp;
1330         peer->filter_epoch[j] = current_time;
1331         j++; j %=NTP_SHIFT;
1332         peer->filter_nextpt = j;
1333
1334         /*
1335          * Update dispersions since the last update and at the same
1336          * time initialize the distance and index lists. The distance
1337          * list uses a compound metric. If the sample is valid and
1338          * younger than the minimum Allan intercept, use delay;
1339          * otherwise, use biased dispersion.
1340          */
1341         dtemp = clock_phi * (current_time - peer->update);
1342         peer->update = current_time;
1343         for (i = NTP_SHIFT - 1; i >= 0; i--) {
1344                 if (i != 0) {
1345                         peer->filter_disp[j] += dtemp;
1346                         if (peer->filter_disp[j] > MAXDISPERSE)
1347                                 peer->filter_disp[j] = MAXDISPERSE;
1348                 }
1349                 if (peer->filter_disp[j] >= MAXDISPERSE)
1350                         dst[i] = MAXDISPERSE;
1351                 else if (peer->update - peer->filter_epoch[j] >
1352                     allan_xpt)
1353                         dst[i] = MAXDISTANCE + peer->filter_disp[j];
1354                 else
1355                         dst[i] = peer->filter_delay[j];
1356                 ord[i] = j;
1357                 j++; j %= NTP_SHIFT;
1358         }
1359
1360         /*
1361          * Sort the samples in both lists by distance.
1362          */
1363         for (i = 1; i < NTP_SHIFT; i++) {
1364                 for (j = 0; j < i; j++) {
1365                         if (dst[j] > dst[i]) {
1366                                 k = ord[j];
1367                                 ord[j] = ord[i];
1368                                 ord[i] = k;
1369                                 etemp = dst[j];
1370                                 dst[j] = dst[i];
1371                                 dst[i] = etemp;
1372                         }
1373                 }
1374         }
1375
1376         /*
1377          * Copy the index list to the association structure so ntpq
1378          * can see it later. Prune the distance list to samples less
1379          * than MAXDISTANCE, but keep at least two valid samples for
1380          * jitter calculation.
1381          */
1382         m = 0;
1383         for (i = 0; i < NTP_SHIFT; i++) {
1384                 peer->filter_order[i] = ord[i];
1385                 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1386                     MAXDISTANCE))
1387                         continue;
1388                 m++;
1389         }
1390         
1391         /*
1392          * Compute the dispersion and jitter squares. The dispersion
1393          * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1394          * normalized close to 1.0. The jitter is the mean of the square
1395          * differences relative to the lowest delay sample. If no
1396          * acceptable samples remain in the shift register, quietly
1397          * tiptoe home leaving only the
1398          * dispersion.
1399          */
1400         jit = 0;
1401         peer->disp = 0;
1402         k = ord[0];
1403         for (i = NTP_SHIFT - 1; i >= 0; i--) {
1404
1405                 j = ord[i];
1406                 peer->disp = NTP_FWEIGHT * (peer->disp +
1407                     peer->filter_disp[j]);
1408                 if (i < m)
1409                         jit += DIFF(peer->filter_offset[j],
1410                             peer->filter_offset[k]);
1411         }
1412
1413         /*
1414          * If no acceptable samples remain in the shift register,
1415          * quietly tiptoe home leaving only the dispersion. Otherwise,
1416          * save the offset, delay and jitter average. Note the jitter
1417          * must not be less than the system precision.
1418          */
1419         if (m == 0)
1420                 return;
1421         etemp = peer->offset;
1422         peer->offset = peer->filter_offset[k];
1423         peer->delay = peer->filter_delay[k];
1424         if (m > 1)
1425                 jit /= m - 1;
1426         peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1427
1428         /*
1429          * A new sample is useful only if it is younger than the last
1430          * one used.
1431          */
1432         if (peer->filter_epoch[k] <= peer->epoch) {
1433 #ifdef DEBUG
1434                 if (debug)
1435                         printf("clock_filter: discard %lu\n",
1436                             peer->epoch - peer->filter_epoch[k]);
1437 #endif
1438                 return;
1439         }
1440
1441         /*
1442          * If the difference between the last offset and the current one
1443          * exceeds the jitter by CLOCK_SGATE (4) and the interval since
1444          * the last update is less than twice the system poll interval,
1445          * consider the update a popcorn spike and ignore it.
1446          */
1447         if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
1448             CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
1449             (1 << (sys_poll + 1))) {
1450 #ifdef DEBUG
1451                 if (debug)
1452                         printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
1453                             m, peer->offset, SQRT(peer->jitter));
1454 #endif
1455                 return;
1456         }
1457
1458         /*
1459          * The mitigated sample statistics are saved for later
1460          * processing, but can be processed only once.
1461          */
1462         peer->epoch = peer->filter_epoch[k];
1463         peer->pollsw = TRUE;
1464 #ifdef DEBUG
1465         if (debug)
1466                 printf(
1467                     "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1468                     m, peer->offset, peer->delay, peer->disp,
1469                     SQRT(peer->jitter), peer->update - peer->epoch);
1470 #endif
1471 }
1472
1473
1474 /*
1475  * clock_select - find the pick-of-the-litter clock
1476  */
1477 void
1478 clock_select(void)
1479 {
1480         register struct peer *peer;
1481         int i, j, k, n;
1482         int nreach, nlist, nl3;
1483         double d, e, f;
1484         int allow, found, sw;
1485         double high, low;
1486         double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1487         struct peer *osys_peer;
1488         struct peer *typeacts = NULL;
1489         struct peer *typelocal = NULL;
1490         struct peer *typepps = NULL;
1491         struct peer *typesystem = NULL;
1492
1493         static int list_alloc = 0;
1494         static struct endpoint *endpoint = NULL;
1495         static int *indx = NULL;
1496         static struct peer **peer_list = NULL;
1497         static u_int endpoint_size = 0;
1498         static u_int indx_size = 0;
1499         static u_int peer_list_size = 0;
1500
1501         /*
1502          * Initialize and create endpoint, index and peer lists big
1503          * enough to handle all associations.
1504          */
1505         osys_peer = sys_peer;
1506         sys_peer = NULL;
1507         sys_prefer = NULL;
1508         nreach = nlist = 0;
1509         low = 1e9;
1510         high = -1e9;
1511         for (n = 0; n < HASH_SIZE; n++)
1512                 nlist += peer_hash_count[n];
1513         if (nlist > list_alloc) {
1514                 if (list_alloc > 0) {
1515                         free(endpoint);
1516                         free(indx);
1517                         free(peer_list);
1518                 }
1519                 while (list_alloc < nlist) {
1520                         list_alloc += 5;
1521                         endpoint_size += 5 * 3 * sizeof(*endpoint);
1522                         indx_size += 5 * 3 * sizeof(*indx);
1523                         peer_list_size += 5 * sizeof(*peer_list);
1524                 }
1525                 endpoint = (struct endpoint *)emalloc(endpoint_size);
1526                 indx = (int *)emalloc(indx_size);
1527                 peer_list = (struct peer **)emalloc(peer_list_size);
1528         }
1529
1530         /*
1531          * Initially, we populate the island with all the rifraff peers
1532          * that happen to be lying around. Those with seriously
1533          * defective clocks are immediately booted off the island. Then,
1534          * the falsetickers are culled and put to sea. The truechimers
1535          * remaining are subject to repeated rounds where the most
1536          * unpopular at each round is kicked off. When the population
1537          * has dwindled to NTP_MINCLOCK (3), the survivors split a
1538          * million bucks and collectively crank the chimes.
1539          */
1540         nlist = nl3 = 0;        /* none yet */
1541         for (n = 0; n < HASH_SIZE; n++) {
1542                 for (peer = peer_hash[n]; peer != NULL; peer =
1543                     peer->next) {
1544                         peer->flags &= ~FLAG_SYSPEER;
1545                         peer->status = CTL_PST_SEL_REJECT;
1546
1547                         /*
1548                          * A peer leaves the island immediately if
1549                          * unreachable, synchronized to us or suffers
1550                          * excessive root distance. Careful with the
1551                          * root distance, since the poll interval can
1552                          * increase to a day and a half.
1553                          */ 
1554                         if (!peer->reach || (peer->stratum > 1 &&
1555                             peer->refid ==
1556                             peer->dstadr->sin.sin_addr.s_addr) ||
1557                             peer->stratum >= STRATUM_UNSPEC ||
1558                             (root_distance(peer) >= MAXDISTANCE + 2 *
1559                             clock_phi * ULOGTOD(sys_poll)))
1560                                 continue;
1561
1562                         /*
1563                          * Don't allow the local clock or modem drivers
1564                          * in the kitchen at this point, unless the
1565                          * prefer peer. Do that later, but only if
1566                          * nobody else is around. These guys are all
1567                          * configured, so we never throw them away.
1568                          */
1569                         if (peer->refclktype == REFCLK_LOCALCLOCK
1570 #if defined(VMS) && defined(VMS_LOCALUNIT)
1571                                 /* wjm: local unit VMS_LOCALUNIT taken seriously */
1572                                 && REFCLOCKUNIT(&peer->srcadr) != VMS_LOCALUNIT
1573 #endif  /* VMS && VMS_LOCALUNIT */
1574                                 ) {
1575                                 typelocal = peer;
1576                                 if (!(peer->flags & FLAG_PREFER))
1577                                         continue; /* no local clock */
1578                         }
1579                         if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1580                                 typeacts = peer;
1581                                 if (!(peer->flags & FLAG_PREFER))
1582                                         continue; /* no acts */
1583                         }
1584
1585                         /*
1586                          * If we get this far, the peer can stay on the
1587                          * island, but does not yet have the immunity
1588                          * idol.
1589                          */
1590                         nreach++;
1591                         peer->status = CTL_PST_SEL_SANE;
1592                         peer_list[nlist++] = peer;
1593
1594                         /*
1595                          * Insert each interval endpoint on the sorted
1596                          * list.
1597                          */
1598                         e = peer->offset;        /* Upper end */
1599                         f = root_distance(peer);
1600                         e = e + f;
1601                         for (i = nl3 - 1; i >= 0; i--) {
1602                                 if (e >= endpoint[indx[i]].val)
1603                                         break;
1604                                 indx[i + 3] = indx[i];
1605                         }
1606                         indx[i + 3] = nl3;
1607                         endpoint[nl3].type = 1;
1608                         endpoint[nl3++].val = e;
1609
1610                         e = e - f;              /* Center point */
1611                         for ( ; i >= 0; i--) {
1612                                 if (e >= endpoint[indx[i]].val)
1613                                         break;
1614                                 indx[i + 2] = indx[i];
1615                         }
1616                         indx[i + 2] = nl3;
1617                         endpoint[nl3].type = 0;
1618                         endpoint[nl3++].val = e;
1619
1620                         e = e - f;              /* Lower end */
1621                         for ( ; i >= 0; i--) {
1622                                 if (e >= endpoint[indx[i]].val)
1623                                         break;
1624                                 indx[i + 1] = indx[i];
1625                         }
1626                         indx[i + 1] = nl3;
1627                         endpoint[nl3].type = -1;
1628                         endpoint[nl3++].val = e;
1629                 }
1630         }
1631 #ifdef DEBUG
1632         if (debug > 2)
1633                 for (i = 0; i < nl3; i++)
1634                         printf("select: endpoint %2d %.6f\n",
1635                            endpoint[indx[i]].type,
1636                            endpoint[indx[i]].val);
1637 #endif
1638         i = 0;
1639         j = nl3 - 1;
1640         allow = nlist;          /* falsetickers assumed */
1641         found = 0;
1642         while (allow > 0) {
1643                 allow--;
1644                 for (n = 0; i <= j; i++) {
1645                         n += endpoint[indx[i]].type;
1646                         if (n < 0)
1647                                 break;
1648                         if (endpoint[indx[i]].type == 0)
1649                                 found++;
1650                 }
1651                 for (n = 0; i <= j; j--) {
1652                         n += endpoint[indx[j]].type;
1653                         if (n > 0)
1654                                 break;
1655                         if (endpoint[indx[j]].type == 0)
1656                                 found++;
1657                 }
1658                 if (found > allow)
1659                         break;
1660                 low = endpoint[indx[i++]].val;
1661                 high = endpoint[indx[j--]].val;
1662         }
1663
1664         /*
1665          * If no survivors remain at this point, check if the local
1666          * clock or modem drivers have been found. If so, nominate one
1667          * of them as the only survivor. Otherwise, give up and declare
1668          * us unsynchronized.
1669          */
1670         if ((allow << 1) >= nlist) {
1671                 if (typeacts != 0) {
1672                         typeacts->status = CTL_PST_SEL_SANE;
1673                         peer_list[0] = typeacts;
1674                         nlist = 1;
1675                 } else if (typelocal != 0) {
1676                         typelocal->status = CTL_PST_SEL_SANE;
1677                         peer_list[0] = typelocal;
1678                         nlist = 1;
1679                 } else {
1680                         if (osys_peer != NULL) {
1681                                 sys_poll = NTP_MINPOLL;
1682                                 NLOG(NLOG_SYNCSTATUS)
1683                                     msyslog(LOG_INFO,
1684                                     "synchronisation lost");
1685                                 report_event(EVNT_PEERSTCHG,
1686                                     (struct peer *)0);
1687                         }
1688                         sys_survivors = 0;
1689 #ifdef AUTOKEY
1690                         resetmanycast();
1691 #endif /* AUTOKEY */
1692                         return;
1693                 }
1694         }
1695 #ifdef DEBUG
1696         if (debug > 2)
1697                 printf("select: low %.6f high %.6f\n", low, high);
1698 #endif
1699
1700         /*
1701          * Clustering algorithm. Construct candidate list in order first
1702          * by stratum then by root distance. If we have more than
1703          * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
1704          * list to find falsetickers, who leave the island immediately.
1705          * If a falseticker is not configured, his association raft is
1706          * drowned as well. We must leave at least one peer to collect
1707          * the million bucks.
1708          */
1709         j = 0;
1710         for (i = 0; i < nlist; i++) {
1711                 peer = peer_list[i];
1712                 if (nlist > 1 && (low >= peer->offset || peer->offset >=
1713                     high)) {
1714                         if (!(peer->flags & FLAG_CONFIG))
1715                                 unpeer(peer);
1716                         continue;
1717                 }
1718                 peer->status = CTL_PST_SEL_DISTSYSPEER;
1719                 d = root_distance(peer) + peer->stratum * MAXDISPERSE;
1720                 if (j >= NTP_MAXCLOCK) {
1721                         if (d >= synch[j - 1])
1722                                 continue;
1723                         else
1724                                 j--;
1725                 }
1726                 for (k = j; k > 0; k--) {
1727                         if (d >= synch[k - 1])
1728                                 break;
1729                         peer_list[k] = peer_list[k - 1];
1730                         error[k] = error[k - 1];
1731                         synch[k] = synch[k - 1];
1732                 }
1733                 peer_list[k] = peer;
1734                 error[k] = peer->jitter;
1735                 synch[k] = d;
1736                 j++;
1737         }
1738         nlist = j;
1739         for (i = 0; i < nlist; i++) {
1740                 peer_list[i]->status = CTL_PST_SEL_SELCAND;
1741
1742 #ifdef DEBUG
1743                 if (debug > 2)
1744                         printf("select: %s distance %.6f\n",
1745                             ntoa(&peer_list[i]->srcadr), synch[i]);
1746 #endif
1747         }
1748
1749         /*
1750          * Now, vote outlyers off the island by select jitter weighted
1751          * by root dispersion. Continue voting as long as there are more
1752          * than NTP_MINCLOCK survivors and the minimum select jitter
1753          * squared is greater than the maximum peer jitter squared. Stop
1754          * if we are about to discard a prefer peer, who of course has
1755          * the immunity idol.
1756          */
1757         while (1) {
1758                 d = 1e9;
1759                 e = -1e9;
1760                 k = 0;
1761                 for (i = 0; i < nlist; i++) {
1762
1763                         if (error[i] < d)
1764                                 d = error[i];
1765                         f = 0;
1766                         if (nlist > 1) {
1767                                 for (j = 0; j < nlist; j++)
1768                                         f += DIFF(peer_list[j]->offset,
1769                                             peer_list[i]->offset);
1770                                 f /= nlist - 1;
1771                         }
1772                         f = max(f, SQUARE(LOGTOD(sys_precision))); 
1773                         if (f * synch[i] > e) {
1774                                 sys_selerr = f;
1775                                 e = f * synch[i];
1776                                 k = i;
1777                         }
1778                 }
1779
1780 #ifdef DEBUG
1781                 if (debug > 2)
1782                         printf(
1783                             "select: survivors %d select %.6f peer %.6f\n",
1784                             k, SQRT(sys_selerr), SQRT(d));
1785 #endif
1786                 if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
1787                     peer_list[k]->flags & FLAG_PREFER)
1788                         break;
1789                 if (!(peer_list[k]->flags & FLAG_CONFIG))
1790                         unpeer(peer_list[k]);
1791                 for (j = k + 1; j < nlist; j++) {
1792                         peer_list[j - 1] = peer_list[j];
1793                         error[j - 1] = error[j];
1794                 }
1795                 nlist--;
1796         }
1797
1798 #ifdef AUTOKEY
1799         /*
1800          * In manycast client mode we may have spooked a sizeable number
1801          * of servers that we don't need. If there are at least
1802          * NTP_MINCLOCK of them, the manycast message will be turned
1803          * off. By the time we get here we nay be ready to prune some of
1804          * them back, but we want to make sure all the candicates have
1805          * had a chance. If they didn't pass the sanity and intersection
1806          * tests, they have already been voted off the island.
1807          */
1808         if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
1809                 resetmanycast();
1810 #endif /* AUTOKEY */
1811         sys_survivors = nlist;
1812
1813 #ifdef DEBUG
1814         if (debug > 2) {
1815                 for (i = 0; i < nlist; i++)
1816                         printf(
1817                             "select: %s offset %.6f, distance %.6f poll %d\n",
1818                             ntoa(&peer_list[i]->srcadr),
1819                             peer_list[i]->offset, synch[i],
1820                             peer_list[i]->pollsw);
1821         }
1822 #endif
1823
1824         /*
1825          * What remains is a list of not greater than NTP_MINCLOCK
1826          * peers. We want only a peer at the lowest stratum to become
1827          * the system peer, although all survivors are eligible for the
1828          * combining algorithm. First record their order, diddle the
1829          * flags and clamp the poll intervals. Then, consider the peers
1830          * at the lowest stratum. Of these, OR the leap bits on the
1831          * assumption that, if some of them honk nonzero bits, they must
1832          * know what they are doing. Also, check for prefer and pps
1833          * peers. If a prefer peer is found within clock_max, update the
1834          * pps switch. Of the other peers not at the lowest stratum,
1835          * check if the system peer is among them and, if found, zap
1836          * him. We note that the head of the list is at the lowest
1837          * stratum and that unsynchronized peers cannot survive this
1838          * far.
1839          *
1840          * Note that we go no further, unless the number of survivors is
1841          * a majority of the suckers that have been found reachable and
1842          * no prior source is available. This avoids the transient when
1843          * one of a flock of sources is out to lunch and just happens
1844          * to be the first survivor.
1845          */
1846         if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
1847                 return;
1848         leap_consensus = 0;
1849         for (i = nlist - 1; i >= 0; i--) {
1850                 peer = peer_list[i];
1851                 peer->status = CTL_PST_SEL_SYNCCAND;
1852                 peer->flags |= FLAG_SYSPEER;
1853                 poll_update(peer, peer->hpoll);
1854                 if (peer->stratum == peer_list[0]->stratum) {
1855                         leap_consensus |= peer->leap;
1856                         if (peer->refclktype == REFCLK_ATOM_PPS &&
1857                             peer->stratum < STRATUM_UNSPEC)
1858                                 typepps = peer;
1859                         if (peer == osys_peer)
1860                                 typesystem = peer;
1861                         if (peer->flags & FLAG_PREFER)
1862                                 sys_prefer = peer;
1863                 }
1864         }
1865
1866         /*
1867          * Mitigation rules of the game. There are several types of
1868          * peers that make a difference here: (1) prefer local peers
1869          * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
1870          * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
1871          * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
1872          * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
1873          * the head of the survivor list. Note that only one peer can be
1874          * declared prefer. The order of preference is in the order
1875          * stated. Note that all of these must be at the lowest stratum,
1876          * i.e., the stratum of the head of the survivor list.
1877          */
1878         if (sys_prefer)
1879                 sw = sys_prefer->refclktype == REFCLK_LOCALCLOCK ||
1880                     sys_prefer->sstclktype == CTL_SST_TS_TELEPHONE ||
1881                     !typepps;
1882         else
1883                 sw = 0;
1884         if (sw) {
1885                 sys_peer = sys_prefer;
1886                 sys_peer->status = CTL_PST_SEL_SYSPEER;
1887                 sys_offset = sys_peer->offset;
1888                 sys_syserr = sys_peer->jitter;
1889 #ifdef DEBUG
1890                 if (debug > 1)
1891                         printf("select: prefer offset %.6f\n",
1892                             sys_offset);
1893 #endif
1894         } else if (typepps) {
1895                 sys_peer = typepps;
1896                 sys_peer->status = CTL_PST_SEL_PPS;
1897                 sys_offset = sys_peer->offset;
1898                 sys_syserr = sys_peer->jitter;
1899                 if (!pps_control)
1900                         NLOG(NLOG_SYSEVENT)
1901                             msyslog(LOG_INFO,
1902                             "pps sync enabled");
1903                 pps_control = current_time;
1904 #ifdef DEBUG
1905                 if (debug > 1)
1906                         printf("select: pps offset %.6f\n",
1907                             sys_offset);
1908 #endif
1909         } else {
1910                 if (typesystem)
1911                         sys_peer = osys_peer;
1912                 else
1913                         sys_peer = peer_list[0];
1914                 sys_peer->status = CTL_PST_SEL_SYSPEER;
1915                 sys_offset = clock_combine(peer_list, nlist);
1916                 sys_syserr = sys_peer->jitter + sys_selerr;
1917 #ifdef DEBUG
1918                 if (debug > 1)
1919                         printf("select: combine offset %.6f\n",
1920                            sys_offset);
1921 #endif
1922         }
1923         if (osys_peer != sys_peer)
1924                 report_event(EVNT_PEERSTCHG, (struct peer *)0);
1925         clock_update();
1926 }
1927
1928 /*
1929  * clock_combine - combine offsets from selected peers
1930  */
1931 static double
1932 clock_combine(
1933         struct peer **peers,
1934         int npeers
1935         )
1936 {
1937         int i;
1938         double x, y, z;
1939         y = z = 0;
1940         for (i = 0; i < npeers; i++) {
1941                 x = root_distance(peers[i]);
1942                 y += 1. / x;
1943                 z += peers[i]->offset / x;
1944         }
1945         return (z / y);
1946 }
1947
1948 /*
1949  * root_distance - compute synchronization distance from peer to root
1950  */
1951 static double
1952 root_distance(
1953         struct peer *peer
1954         )
1955 {
1956         /*
1957          * Careful squeak here. The value returned must be greater than
1958          * zero blamed on the peer jitter, which must be at least the
1959          * square of sys_precision.
1960          */
1961         return ((peer->rootdelay + peer->delay) / 2 +
1962             peer->rootdispersion + peer->disp + clock_phi *
1963             (current_time - peer->update) + SQRT(peer->jitter));
1964 }
1965
1966 /*
1967  * peer_xmit - send packet for persistent association.
1968  */
1969 static void
1970 peer_xmit(
1971         struct peer *peer       /* peer structure pointer */
1972         )
1973 {
1974         struct pkt xpkt;        /* transmit packet */
1975         int sendlen, authlen;
1976         keyid_t xkeyid;         /* transmit key ID */
1977         l_fp xmt_tx;
1978
1979         /*
1980          * Initialize transmit packet header fields.
1981          */
1982         xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
1983             peer->hmode);
1984         xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
1985         xpkt.ppoll = peer->hpoll;
1986         xpkt.precision = sys_precision;
1987         xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
1988         xpkt.rootdispersion = HTONS_FP(DTOUFP(sys_rootdispersion));
1989         xpkt.refid = sys_refid;
1990         HTONL_FP(&sys_reftime, &xpkt.reftime);
1991         HTONL_FP(&peer->org, &xpkt.org);
1992         HTONL_FP(&peer->rec, &xpkt.rec);
1993
1994         /*
1995          * If the received packet contains a MAC, the transmitted packet
1996          * is authenticated and contains a MAC. If not, the transmitted
1997          * packet is not authenticated.
1998          *
1999          * In the current I/O semantics the default interface is set
2000          * until after receiving a packet and setting the right
2001          * interface. So, the first packet goes out unauthenticated.
2002          * That's why the really icky test next is here.
2003          */
2004         sendlen = LEN_PKT_NOMAC;
2005         if (!(peer->flags & FLAG_AUTHENABLE)) {
2006                 get_systime(&peer->xmt);
2007                 HTONL_FP(&peer->xmt, &xpkt.xmt);
2008                 sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
2009                     sendlen);
2010                 peer->sent++;
2011 #ifdef DEBUG
2012                 if (debug)
2013                         printf("transmit: at %ld %s->%s mode %d\n",
2014                             current_time, ntoa(&peer->dstadr->sin),
2015                             ntoa(&peer->srcadr), peer->hmode);
2016 #endif
2017                 return;
2018         }
2019
2020         /*
2021          * The received packet contains a MAC, so the transmitted packet
2022          * must be authenticated. If autokey is enabled, fuss with the
2023          * various modes; otherwise, private key cryptography is used.
2024          */
2025 #ifdef AUTOKEY
2026         if ((peer->flags & FLAG_SKEY)) {
2027                 u_int cmmd;
2028
2029                 /*
2030                  * The Public Key Dance (PKD): Cryptographic credentials
2031                  * are contained in extension fields, each including a
2032                  * 4-octet length/code word followed by a 4-octet
2033                  * association ID and optional additional data. Optional
2034                  * data includes a 4-octet data length field followed by
2035                  * the data itself. Request messages are sent from a
2036                  * configured association; response messages can be sent
2037                  * from a configured association or can take the fast
2038                  * path without ever matching an association. Response
2039                  * messages have the same code as the request, but have
2040                  * a response bit and possibly an error bit set. In this
2041                  * implementation, a message may contain no more than
2042                  * one command and no more than one response.
2043                  *
2044                  * Cryptographic session keys include both a public and
2045                  * a private componet. Request and response messages
2046                  * using extension fields are always sent with the
2047                  * private component set to zero. Packets without
2048                  * extension fields indlude the private component when
2049                  * the session key is generated.
2050                  */
2051                 while (1) {
2052                 
2053                         /*
2054                          * Allocate and initialize a keylist if not
2055                          * already done. Then, use the list in inverse
2056                          * order, discarding keys once used. Keep the
2057                          * latest key around until the next one, so
2058                          * clients can use client/server packets to
2059                          * compute propagation delay.
2060                          *
2061                          * Note that once a key is used from the list,
2062                          * it is retained in the key cache until the
2063                          * next key is used. This is to allow a client
2064                          * to retrieve the encrypted session key
2065                          * identifier to verify authenticity.
2066                          *
2067                          * If for some reason a key is no longer in the
2068                          * key cache, a birthday has happened and the
2069                          * pseudo-random sequence is probably broken. In
2070                          * that case, purge the keylist and regenerate
2071                          * it.
2072                          */
2073                         if (peer->keynumber == 0)
2074                                 make_keylist(peer, peer->dstadr);
2075                         else
2076                                 peer->keynumber--;
2077                         xkeyid = peer->keylist[peer->keynumber];
2078                         if (authistrusted(xkeyid))
2079                                 break;
2080                         else
2081                                 key_expire(peer);
2082                 }
2083                 peer->keyid = xkeyid;
2084                 switch (peer->hmode) {
2085
2086                 /*
2087                  * In broadcast mode the autokey values are required.
2088                  * Send them when a new keylist is generated; otherwise,
2089                  * send the association ID so the client can request
2090                  * them at other times.
2091                  */
2092                 case MODE_BROADCAST:
2093                         if (peer->flags & FLAG_ASSOC)
2094                                 cmmd = CRYPTO_AUTO | CRYPTO_RESP;
2095                         else
2096                                 cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
2097                         sendlen += crypto_xmit((u_int32 *)&xpkt,
2098                             sendlen, cmmd, 0, peer->associd);
2099                         break;
2100
2101                 /*
2102                  * In symmetric modes the public key, leapsecond table,
2103                  * agreement parameters and autokey values are required.
2104                  *
2105                  * 1. If a response is pending, always send it first.
2106                  *
2107                  * 2. Don't send anything except a public-key request
2108                  *    until the public key has been stored. 
2109                  *
2110                  * 3. Once the public key has been stored, don't send
2111                  *    anything except an agreement parameter request
2112                  *    until the agreement parameters have been stored.
2113                  *
2114                  * 4. Once the argeement parameters have been stored,
2115                  *    don't send anything except a public value request
2116                  *    until the agreed key has been stored.
2117                  *
2118                  * 5. When the agreed key has been stored and the key
2119                  *    list is regenerated, send the autokey values
2120                  *    gratis unless they have already been sent.
2121                  */
2122                 case MODE_ACTIVE:
2123                 case MODE_PASSIVE:
2124 #ifdef PUBKEY
2125                         if (peer->cmmd != 0)
2126                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2127                                     sendlen, (peer->cmmd >> 16) |
2128                                     CRYPTO_RESP, peer->hcookie,
2129                                     peer->associd);
2130                         if (!peer->crypto)
2131                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2132                                     sendlen, CRYPTO_ASSOC,
2133                                     peer->hcookie, peer->assoc);
2134                         else if (!crypto_flags &&
2135                             peer->pcookie.tstamp == 0 && sys_leap !=
2136                             LEAP_NOTINSYNC)
2137                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2138                                     sendlen, CRYPTO_PRIV, peer->hcookie,
2139                                     peer->assoc);
2140                         else if (crypto_flags && peer->pubkey.ptr ==
2141                             NULL)
2142                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2143                                     sendlen, CRYPTO_NAME, peer->hcookie,
2144                                     peer->assoc);
2145                         else if (peer->crypto & CRYPTO_FLAG_CERT)
2146                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2147                                     sendlen, CRYPTO_CERT, peer->hcookie,
2148                                     peer->assoc);
2149                         else if (crypto_flags && peer->crypto &
2150                             CRYPTO_FLAG_DH && sys_leap !=
2151                             LEAP_NOTINSYNC)
2152                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2153                                     sendlen, CRYPTO_DHPAR,
2154                                     peer->hcookie, peer->assoc);
2155                         else if (crypto_flags && peer->pcookie.tstamp ==
2156                             0 && sys_leap != LEAP_NOTINSYNC)
2157                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2158                                     sendlen, CRYPTO_DH, peer->hcookie,
2159                                     peer->assoc);
2160 #else
2161                         if (peer->cmmd != 0)
2162                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2163                                     sendlen, (peer->cmmd >> 16) |
2164                                     CRYPTO_RESP, peer->hcookie,
2165                                     peer->associd);
2166                         if (peer->pcookie.tstamp == 0 && sys_leap !=
2167                             LEAP_NOTINSYNC)
2168                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2169                                     sendlen, CRYPTO_PRIV, peer->hcookie,
2170                                     peer->assoc);
2171 #endif /* PUBKEY */
2172                         else if (!(peer->flags & FLAG_AUTOKEY))
2173                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2174                                     sendlen, CRYPTO_AUTO, peer->hcookie,
2175                                     peer->assoc);
2176                         else if ((peer->flags & FLAG_ASSOC) &&
2177                             (peer->cmmd >> 16) != CRYPTO_AUTO)
2178                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2179                                     sendlen, CRYPTO_AUTO | CRYPTO_RESP,
2180                                     peer->hcookie, peer->associd);
2181 #ifdef PUBKEY
2182                         else if (peer->crypto & CRYPTO_FLAG_TAI)
2183                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2184                                     sendlen, CRYPTO_TAI, peer->hcookie,
2185                                     peer->assoc);
2186 #endif /* PUBKEY */
2187                         peer->cmmd = 0;
2188                         break;
2189
2190                 /*
2191                  * In client mode, the public key, host cookie and
2192                  * autokey values are required. In broadcast client
2193                  * mode, these values must be acquired during the
2194                  * client/server exchange to avoid having to wait until
2195                  * the next key list regeneration. Otherwise, the poor
2196                  * dude may die a lingering death until becoming
2197                  * unreachable and attempting rebirth. Note that we ask
2198                  * for the cookie at each key list regeneration anyway.
2199                  */
2200                 case MODE_CLIENT:
2201                         if (peer->cmmd != 0)
2202                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2203                                     sendlen, (peer->cmmd >> 16) |
2204                                     CRYPTO_RESP, peer->hcookie,
2205                                     peer->associd);
2206                         if (!peer->crypto)
2207                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2208                                     sendlen, CRYPTO_ASSOC,
2209                                     peer->hcookie, peer->assoc);
2210 #ifdef PUBKEY
2211                         else if (crypto_flags && peer->pubkey.ptr ==
2212                             NULL)
2213                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2214                                     sendlen, CRYPTO_NAME, peer->hcookie,
2215                                     peer->assoc);
2216                         else if (peer->crypto & CRYPTO_FLAG_CERT)
2217                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2218                                     sendlen, CRYPTO_CERT, peer->hcookie,
2219                                     peer->assoc);
2220 #endif /* PUBKEY */
2221                         else if (peer->pcookie.tstamp == 0)
2222                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2223                                     sendlen, CRYPTO_PRIV, peer->hcookie,
2224                                     peer->assoc);
2225                         else if (!(peer->flags & FLAG_AUTOKEY) &&
2226                             (peer->cast_flags & MDF_BCLNT))
2227                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2228                                     sendlen, CRYPTO_AUTO, peer->hcookie,
2229                                     peer->assoc);
2230 #ifdef PUBKEY
2231                         else if (peer->crypto & CRYPTO_FLAG_TAI)
2232                                 sendlen += crypto_xmit((u_int32 *)&xpkt,
2233                                     sendlen, CRYPTO_TAI, peer->hcookie,
2234                                     peer->assoc);
2235 #endif /* PUBKEY */
2236                         peer->cmmd = 0;
2237                         break;
2238                 }
2239
2240                 /*
2241                  * If extension fields are present, we must use a
2242                  * private value of zero and force min poll interval.  
2243                  * Most intricate.
2244                  */
2245                 if (sendlen > LEN_PKT_NOMAC)
2246                         session_key(&peer->dstadr->sin, &peer->srcadr,
2247                             xkeyid, 0, 2);
2248         } 
2249 #endif /* AUTOKEY */
2250         xkeyid = peer->keyid;
2251         get_systime(&peer->xmt);
2252         L_ADD(&peer->xmt, &sys_authdelay);
2253         HTONL_FP(&peer->xmt, &xpkt.xmt);
2254         authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2255         if (authlen == 0) {
2256                 msyslog(LOG_NOTICE,
2257                         "transmit: no encryption key found");
2258                 peer->flash |= TEST4 | TEST5;
2259                 return;
2260         }
2261         sendlen += authlen;
2262 #ifdef AUTOKEY
2263         if (xkeyid > NTP_MAXKEY)
2264                 authtrust(xkeyid, 0);
2265 #endif /* AUTOKEY */
2266         get_systime(&xmt_tx);
2267         if (sendlen > sizeof(xpkt)) {
2268                 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2269                 exit(-1);
2270         }
2271         sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
2272
2273         /*
2274          * Calculate the encryption delay. Keep the minimum over
2275          * the latest two samples.
2276          */
2277         L_SUB(&xmt_tx, &peer->xmt);
2278         L_ADD(&xmt_tx, &sys_authdelay);
2279         sys_authdly[1] = sys_authdly[0];
2280         sys_authdly[0] = xmt_tx.l_uf;
2281         if (sys_authdly[0] < sys_authdly[1])
2282                 sys_authdelay.l_uf = sys_authdly[0];
2283         else
2284                 sys_authdelay.l_uf = sys_authdly[1];
2285         peer->sent++;
2286 #ifdef AUTOKEY
2287 #ifdef DEBUG
2288         if (debug)
2289                 printf(
2290                     "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2291                     current_time, ntoa(&peer->dstadr->sin),
2292                     ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2293                     authlen, peer->keynumber);
2294 #endif
2295 #else
2296 #ifdef DEBUG
2297         if (debug)
2298                 printf(
2299                     "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2300                     current_time, ntoa(&peer->dstadr->sin),
2301                     ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2302                     authlen);
2303 #endif
2304 #endif /* AUTOKEY */
2305 }
2306
2307
2308 /*
2309  * fast_xmit - Send packet for nonpersistent association. Note that
2310  * neither the source or destination can be a broadcast address.
2311  */
2312 static void
2313 fast_xmit(
2314         struct recvbuf *rbufp,  /* receive packet pointer */
2315         int xmode,              /* transmit mode */
2316         keyid_t xkeyid,         /* transmit key ID */
2317         int mask                /* restrict mask */
2318         )
2319 {
2320         struct pkt xpkt;        /* transmit packet structure */
2321         struct pkt *rpkt;       /* receive packet structure */
2322         l_fp xmt_ts;            /* transmit timestamp */
2323         l_fp xmt_tx;            /* transmit timestamp after authent */
2324         int sendlen, authlen;
2325
2326         /*
2327          * Initialize transmit packet header fields from the receive
2328          * buffer provided. We leave some fields intact as received. If
2329          * the gazinta was from a multicast address, the gazouta must go
2330          * out another way.
2331          */
2332         rpkt = &rbufp->recv_pkt;
2333         if (rbufp->dstadr->flags & INT_MULTICAST)
2334                 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2335
2336         /*
2337          * If the caller is restricted, return a kiss-of-death packet;
2338          * otherwise, smooch politely.
2339          */
2340         if (mask & (RES_DONTSERVE | RES_LIMITED)) {
2341                 if (!(mask & RES_DEMOBILIZE)) {
2342                         return;
2343                 } else {
2344                         xpkt.li_vn_mode =
2345                             PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2346                             PKT_VERSION(rpkt->li_vn_mode), xmode);
2347                         xpkt.stratum = STRATUM_UNSPEC;
2348                         memcpy(&xpkt.refid, "DENY", 4);
2349                 }
2350         } else {
2351                 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2352                     PKT_VERSION(rpkt->li_vn_mode), xmode);
2353                 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2354                 xpkt.refid = sys_refid;
2355         }
2356         xpkt.ppoll = rpkt->ppoll;
2357         xpkt.precision = sys_precision;
2358         xpkt.rootdelay = HTONS_FP(DTOFP(sys_rootdelay));
2359         xpkt.rootdispersion =
2360             HTONS_FP(DTOUFP(sys_rootdispersion));
2361         HTONL_FP(&sys_reftime, &xpkt.reftime);
2362         xpkt.org = rpkt->xmt;
2363         HTONL_FP(&rbufp->recv_time, &xpkt.rec);
2364
2365         /*
2366          * If the received packet contains a MAC, the transmitted packet
2367          * is authenticated and contains a MAC. If not, the transmitted
2368          * packet is not authenticated.
2369          */
2370         sendlen = LEN_PKT_NOMAC;
2371         if (rbufp->recv_length == sendlen) {
2372                 get_systime(&xmt_ts);
2373                 HTONL_FP(&xmt_ts, &xpkt.xmt);
2374                 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2375                     sendlen);
2376 #ifdef DEBUG
2377                 if (debug)
2378                         printf("transmit: at %ld %s->%s mode %d\n",
2379                             current_time, ntoa(&rbufp->dstadr->sin),
2380                             ntoa(&rbufp->recv_srcadr), xmode);
2381 #endif
2382                 return;
2383         }
2384
2385         /*
2386          * The received packet contains a MAC, so the transmitted packet
2387          * must be authenticated. For private-key cryptography, use the
2388          * predefined private keys to generate the cryptosum. For
2389          * autokey cryptography, use the server private value to
2390          * generate the cookie, which is unique for every source-
2391          * destination-key ID combination.
2392          */
2393 #ifdef AUTOKEY
2394         if (xkeyid > NTP_MAXKEY) {
2395                 keyid_t cookie;
2396                 u_int code, associd;
2397
2398                 /*
2399                  * The only way to get here is a reply to a legitimate
2400                  * client request message, so the mode must be
2401                  * MODE_SERVER. If an extension field is present, there
2402                  * can be only one and that must be a command. Do what
2403                  * needs, but with private value of zero so the poor
2404                  * jerk can decode it. If no extension field is present,
2405                  * use the cookie to generate the session key.
2406                  */
2407                 code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
2408                 cookie = session_key(&rbufp->recv_srcadr,
2409                     &rbufp->dstadr->sin, 0, sys_private, 0);
2410                 associd = htonl(rpkt->exten[1]);
2411                 if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
2412                     sizeof(u_int32)) {
2413                         session_key(&rbufp->dstadr->sin,
2414                             &rbufp->recv_srcadr, xkeyid, 0, 2);
2415                         sendlen += crypto_xmit((u_int32 *)&xpkt,
2416                             sendlen, code, cookie, associd);
2417                 } else {
2418                         session_key(&rbufp->dstadr->sin,
2419                             &rbufp->recv_srcadr, xkeyid, cookie, 2);
2420                 }
2421         }
2422 #endif /* AUTOKEY */
2423         get_systime(&xmt_ts);
2424         L_ADD(&xmt_ts, &sys_authdelay);
2425         HTONL_FP(&xmt_ts, &xpkt.xmt);
2426         authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2427         sendlen += authlen;
2428 #ifdef AUTOKEY
2429         if (xkeyid > NTP_MAXKEY)
2430                 authtrust(xkeyid, 0);
2431 #endif /* AUTOKEY */
2432         get_systime(&xmt_tx);
2433         if (sendlen > sizeof(xpkt)) {
2434                 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2435                 exit(-1);
2436         }
2437         sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2438
2439         /*
2440          * Calculate the encryption delay. Keep the minimum over the
2441          * latest two samples.
2442          */
2443         L_SUB(&xmt_tx, &xmt_ts);
2444         L_ADD(&xmt_tx, &sys_authdelay);
2445         sys_authdly[1] = sys_authdly[0];
2446         sys_authdly[0] = xmt_tx.l_uf;
2447         if (sys_authdly[0] < sys_authdly[1])
2448                 sys_authdelay.l_uf = sys_authdly[0];
2449         else
2450                 sys_authdelay.l_uf = sys_authdly[1];
2451 #ifdef DEBUG
2452         if (debug)
2453                 printf(
2454                     "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2455                     current_time, ntoa(&rbufp->dstadr->sin),
2456                     ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
2457                     authlen);
2458 #endif
2459 }
2460
2461
2462 #ifdef AUTOKEY
2463 /*
2464  * key_expire - purge the key list
2465  */
2466 void
2467 key_expire(
2468         struct peer *peer       /* peer structure pointer */
2469         )
2470 {
2471         int i;
2472
2473         if (peer->keylist != NULL) {
2474                 for (i = 0; i <= peer->keynumber; i++)
2475                         authtrust(peer->keylist[i], 0);
2476                 free(peer->keylist);
2477                 peer->keylist = NULL;
2478         }
2479         peer->keynumber = peer->sndauto.seq = 0;
2480 #ifdef DEBUG
2481         if (debug)
2482                 printf("key_expire: at %lu\n", current_time);
2483 #endif
2484 }
2485 #endif /* AUTOKEY */
2486
2487 /*
2488  * Find the precision of this particular machine
2489  */
2490 #define DUSECS  1000000 /* us in a s */
2491 #define HUSECS  (1 << 20) /* approx DUSECS for shifting etc */
2492 #define MINSTEP 5       /* minimum clock increment (us) */
2493 #define MAXSTEP 20000   /* maximum clock increment (us) */
2494 #define MINLOOPS 5      /* minimum number of step samples */
2495
2496 /*
2497  * This routine calculates the differences between successive calls to
2498  * gettimeofday(). If a difference is less than zero, the us field
2499  * has rolled over to the next second, so we add a second in us. If
2500  * the difference is greater than zero and less than MINSTEP, the
2501  * clock has been advanced by a small amount to avoid standing still.
2502  * If the clock has advanced by a greater amount, then a timer interrupt
2503  * has occurred and this amount represents the precision of the clock.
2504  * In order to guard against spurious values, which could occur if we
2505  * happen to hit a fat interrupt, we do this for MINLOOPS times and
2506  * keep the minimum value obtained.
2507  */
2508 int
2509 default_get_precision(void)
2510 {
2511         struct timeval tp;
2512 #if !defined(SYS_WINNT) && !defined(VMS) && !defined(_SEQUENT_)
2513         struct timezone tzp;
2514 #elif defined(VMS) || defined(_SEQUENT_)
2515         struct timezone {
2516                 int tz_minuteswest;
2517                 int tz_dsttime;
2518         } tzp;
2519 #endif /* defined(VMS) || defined(_SEQUENT_) */
2520         long last;
2521         int i;
2522         long diff;
2523         long val;
2524         long usec;
2525 #ifdef HAVE_GETCLOCK
2526         struct timespec ts;
2527 #endif
2528 #if defined(__FreeBSD__) && __FreeBSD__ >= 3
2529         u_long freq;
2530         size_t j;
2531
2532         /* Try to see if we can find the frequency of of the counter
2533          * which drives our timekeeping
2534          */
2535         j = sizeof freq;
2536         i = sysctlbyname("kern.timecounter.frequency", &freq, &j , 0,
2537             0);
2538         if (i)
2539                 i = sysctlbyname("machdep.tsc_freq", &freq, &j , 0, 0);
2540         if (i)
2541                 i = sysctlbyname("machdep.i586_freq", &freq, &j , 0, 0);
2542         if (i)
2543                 i = sysctlbyname("machdep.i8254_freq", &freq, &j , 0,
2544                     0);
2545         if (!i) {
2546                 for (i = 1; freq ; i--)
2547                         freq >>= 1;
2548                 return (i);
2549         }
2550 #endif
2551         usec = 0;
2552         val = MAXSTEP;
2553 #ifdef HAVE_GETCLOCK
2554         (void) getclock(TIMEOFDAY, &ts);
2555         tp.tv_sec = ts.tv_sec;
2556         tp.tv_usec = ts.tv_nsec / 1000;
2557 #else /*  not HAVE_GETCLOCK */
2558         GETTIMEOFDAY(&tp, &tzp);
2559 #endif /* not HAVE_GETCLOCK */
2560         last = tp.tv_usec;
2561         for (i = 0; i < MINLOOPS && usec < HUSECS;) {
2562 #ifdef HAVE_GETCLOCK
2563                 (void) getclock(TIMEOFDAY, &ts);
2564                 tp.tv_sec = ts.tv_sec;
2565                 tp.tv_usec = ts.tv_nsec / 1000;
2566 #else /*  not HAVE_GETCLOCK */
2567                 GETTIMEOFDAY(&tp, &tzp);
2568 #endif /* not HAVE_GETCLOCK */
2569                 diff = tp.tv_usec - last;
2570                 last = tp.tv_usec;
2571                 if (diff < 0)
2572                         diff += DUSECS;
2573                 usec += diff;
2574                 if (diff > MINSTEP) {
2575                         i++;
2576                         if (diff < val)
2577                                 val = diff;
2578                 }
2579         }
2580         NLOG(NLOG_SYSINFO)
2581                 msyslog(LOG_INFO, "precision = %ld usec", val);
2582         if (usec >= HUSECS)
2583                 val = MINSTEP;  /* val <= MINSTEP; fast machine */
2584         diff = HUSECS;
2585         for (i = 0; diff > val; i--)
2586                 diff >>= 1;
2587         return (i);
2588 }
2589
2590 /*
2591  * init_proto - initialize the protocol module's data
2592  */
2593 void
2594 init_proto(void)
2595 {
2596         l_fp dummy;
2597
2598         /*
2599          * Fill in the sys_* stuff.  Default is don't listen to
2600          * broadcasting, authenticate.
2601          */
2602         sys_leap = LEAP_NOTINSYNC;
2603         sys_stratum = STRATUM_UNSPEC;
2604         sys_precision = (s_char)default_get_precision();
2605         sys_jitter = LOGTOD(sys_precision);
2606         sys_rootdelay = 0;
2607         sys_rootdispersion = 0;
2608         sys_refid = 0;
2609         L_CLR(&sys_reftime);
2610         sys_peer = NULL;
2611         sys_survivors = 0;
2612         get_systime(&dummy);
2613         sys_bclient = 0;
2614         sys_bdelay = DEFBROADDELAY;
2615         sys_authenticate = 1;
2616         L_CLR(&sys_authdelay);
2617         sys_authdly[0] = sys_authdly[1] = 0;
2618         sys_stattime = 0;
2619         sys_badstratum = 0;
2620         sys_oldversionpkt = 0;
2621         sys_newversionpkt = 0;
2622         sys_badlength = 0;
2623         sys_unknownversion = 0;
2624         sys_processed = 0;
2625         sys_badauth = 0;
2626         sys_manycastserver = 0;
2627 #ifdef AUTOKEY
2628         sys_automax = 1 << NTP_AUTOMAX;
2629 #endif /* AUTOKEY */
2630
2631         /*
2632          * Default these to enable
2633          */
2634         ntp_enable = 1;
2635 #ifndef KERNEL_FLL_BUG
2636         kern_enable = 1;
2637 #endif
2638         pps_enable = 0;
2639         stats_control = 1;
2640
2641         /*
2642          * Some system clocks should only be adjusted in 10ms
2643          * increments.
2644          */
2645 #if defined RELIANTUNIX_CLOCK
2646         systime_10ms_ticks = 1;           /* Reliant UNIX */
2647 #elif defined SCO5_CLOCK
2648         if (sys_precision >= (s_char)-10) /* pre-SCO OpenServer 5.0.6 */
2649                 systime_10ms_ticks = 1;
2650 #endif
2651         if (systime_10ms_ticks)
2652                 msyslog(LOG_INFO, "using 10ms tick adjustments");
2653 }
2654
2655
2656 /*
2657  * proto_config - configure the protocol module
2658  */
2659 void
2660 proto_config(
2661         int item,
2662         u_long value,
2663         double dvalue
2664         )
2665 {
2666         /*
2667          * Figure out what he wants to change, then do it
2668          */
2669         switch (item) {
2670         case PROTO_KERNEL:
2671
2672                 /*
2673                  * Turn on/off kernel discipline
2674                  */
2675                 kern_enable = (int)value;
2676                 break;
2677
2678         case PROTO_NTP:
2679
2680                 /*
2681                  * Turn on/off clock discipline
2682                  */
2683                 ntp_enable = (int)value;
2684                 break;
2685
2686         case PROTO_MONITOR:
2687
2688                 /*
2689                  * Turn on/off monitoring
2690                  */
2691                 if (value)
2692                         mon_start(MON_ON);
2693                 else
2694                         mon_stop(MON_ON);
2695                 break;
2696
2697         case PROTO_FILEGEN:
2698
2699                 /*
2700                  * Turn on/off statistics
2701                  */
2702                 stats_control = (int)value;
2703                 break;
2704
2705         case PROTO_BROADCLIENT:
2706
2707                 /*
2708                  * Turn on/off facility to listen to broadcasts
2709                  */
2710                 sys_bclient = (int)value;
2711                 if (value)
2712                         io_setbclient();
2713                 else
2714                         io_unsetbclient();
2715                 break;
2716
2717         case PROTO_MULTICAST_ADD:
2718
2719                 /*
2720                  * Add muliticast group address
2721                  */
2722                 io_multicast_add(value);
2723                 break;
2724
2725         case PROTO_MULTICAST_DEL:
2726
2727                 /*
2728                  * Delete multicast group address
2729                  */
2730                 io_multicast_del(value);
2731                 break;
2732
2733         case PROTO_BROADDELAY:
2734
2735                 /*
2736                  * Set default broadcast delay
2737                  */
2738                 sys_bdelay = dvalue;
2739                 break;
2740
2741         case PROTO_AUTHENTICATE:
2742
2743                 /*
2744                  * Specify the use of authenticated data
2745                  */
2746                 sys_authenticate = (int)value;
2747                 break;
2748
2749         case PROTO_PPS:
2750
2751                 /*
2752                  * Turn on/off PPS discipline
2753                  */
2754                 pps_enable = (int)value;
2755                 break;
2756
2757 #ifdef REFCLOCK
2758         case PROTO_CAL:
2759
2760                 /*
2761                  * Turn on/off refclock calibrate
2762                  */
2763                 cal_enable = (int)value;
2764                 break;
2765 #endif
2766
2767         default:
2768
2769                 /*
2770                  * Log this error
2771                  */
2772                 msyslog(LOG_ERR,
2773                     "proto_config: illegal item %d, value %ld",
2774                         item, value);
2775                 break;
2776         }
2777 }
2778
2779
2780 /*
2781  * proto_clr_stats - clear protocol stat counters
2782  */
2783 void
2784 proto_clr_stats(void)
2785 {
2786         sys_badstratum = 0;
2787         sys_oldversionpkt = 0;
2788         sys_newversionpkt = 0;
2789         sys_unknownversion = 0;
2790         sys_badlength = 0;
2791         sys_processed = 0;
2792         sys_badauth = 0;
2793         sys_stattime = current_time;
2794         sys_limitrejected = 0;
2795 }