~ubuntu-branches/debian/squeeze/ntp/squeeze-201010051545

« back to all changes in this revision

Viewing changes to ntpd/ntp_proto.c

  • Committer: Bazaar Package Importer
  • Author(s): Matt Zimmerman
  • Date: 2004-10-11 16:10:27 UTC
  • mfrom: (1.1.1 upstream)
  • Revision ID: james.westby@ubuntu.com-20041011161027-icyjbji8ujym633o
Tags: 1:4.2.0a-10ubuntu2
Use ntp.ubuntulinux.org instead of pool.ntp.org

Show diffs side-by-side

added added

removed removed

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