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