Deleted Added
full compact
ntp_proto.c (106166) ntp_proto.c (132454)
1/*
2 * ntp_proto.c - NTP version 4 protocol machinery
3 *
1/*
2 * ntp_proto.c - NTP version 4 protocol machinery
3 *
4 * $FreeBSD: head/contrib/ntp/ntpd/ntp_proto.c 106166 2002-10-29 20:04:27Z roberto $
4 * ATTENTION: Get approval from Dave Mills on all changes to this file!
5 *
5 */
6#ifdef HAVE_CONFIG_H
7#include <config.h>
8#endif
9
10#include "ntpd.h"
11#include "ntp_stdlib.h"
12#include "ntp_unixtime.h"
13#include "ntp_control.h"
14#include "ntp_string.h"
6 */
7#ifdef HAVE_CONFIG_H
8#include <config.h>
9#endif
10
11#include "ntpd.h"
12#include "ntp_stdlib.h"
13#include "ntp_unixtime.h"
14#include "ntp_control.h"
15#include "ntp_string.h"
15#include "ntp_crypto.h"
16
17#include <stdio.h>
18
19#if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
20#include "ntp_refclock.h"
21#endif
22
23#if defined(__FreeBSD__) && __FreeBSD__ >= 3

--- 5 unchanged lines hidden (view full) ---

29 * specification.
30 */
31u_char sys_leap; /* system leap indicator */
32u_char sys_stratum; /* stratum of system */
33s_char sys_precision; /* local clock precision */
34double sys_rootdelay; /* roundtrip delay to primary source */
35double sys_rootdispersion; /* dispersion to primary source */
36u_int32 sys_refid; /* reference source for local clock */
16
17#include <stdio.h>
18
19#if defined(VMS) && defined(VMS_LOCALUNIT) /*wjm*/
20#include "ntp_refclock.h"
21#endif
22
23#if defined(__FreeBSD__) && __FreeBSD__ >= 3

--- 5 unchanged lines hidden (view full) ---

29 * specification.
30 */
31u_char sys_leap; /* system leap indicator */
32u_char sys_stratum; /* stratum of system */
33s_char sys_precision; /* local clock precision */
34double sys_rootdelay; /* roundtrip delay to primary source */
35double sys_rootdispersion; /* dispersion to primary source */
36u_int32 sys_refid; /* reference source for local clock */
37u_int32 sys_peer_refid; /* hashed refid of our current peer */
37static double sys_offset; /* current local clock offset */
38l_fp sys_reftime; /* time we were last updated */
38static double sys_offset; /* current local clock offset */
39l_fp sys_reftime; /* time we were last updated */
39struct peer *sys_peer; /* our current peer */
40struct peer *sys_peer; /* our current peer */
40struct peer *sys_prefer; /* our cherished peer */
41struct peer *sys_prefer; /* our cherished peer */
41#ifdef AUTOKEY
42int sys_kod; /* kod credit */
43int sys_kod_rate = 2; /* max kod packets per second */
44#ifdef OPENSSL
42u_long sys_automax; /* maximum session key lifetime */
45u_long sys_automax; /* maximum session key lifetime */
43#endif /* AUTOKEY */
46#endif /* OPENSSL */
44
45/*
46 * Nonspecified system state variables.
47 */
47
48/*
49 * Nonspecified system state variables.
50 */
48int sys_bclient; /* we set our time to broadcasts */
49double sys_bdelay; /* broadcast client default delay */
51int sys_bclient; /* broadcast client enable */
52double sys_bdelay; /* broadcast client default delay */
53int sys_calldelay; /* modem callup delay (s) */
50int sys_authenticate; /* requre authentication for config */
51l_fp sys_authdelay; /* authentication delay */
54int sys_authenticate; /* requre authentication for config */
55l_fp sys_authdelay; /* authentication delay */
52static u_long sys_authdly[2]; /* authentication delay shift reg */
56static u_long sys_authdly[2]; /* authentication delay shift reg */
53static u_char leap_consensus; /* consensus of survivor leap bits */
57static u_char leap_consensus; /* consensus of survivor leap bits */
54static double sys_selerr; /* select error (squares) */
58static double sys_selerr; /* select error (squares) */
55static double sys_syserr; /* system error (squares) */
56keyid_t sys_private; /* private value for session seed */
57int sys_manycastserver; /* respond to manycast client pkts */
59static double sys_syserr; /* system error (squares) */
60keyid_t sys_private; /* private value for session seed */
61int sys_manycastserver; /* respond to manycast client pkts */
58u_int sys_survivors; /* truest of the truechimers */
59int peer_ntpdate; /* active peers in ntpdate mode */
62int peer_ntpdate; /* active peers in ntpdate mode */
60#ifdef AUTOKEY
63int sys_survivors; /* truest of the truechimers */
64#ifdef OPENSSL
61char *sys_hostname; /* gethostname() name */
65char *sys_hostname; /* gethostname() name */
62#endif /* AUTOKEY */
66#endif /* OPENSSL */
63
64/*
67
68/*
69 * TOS and multicast mapping stuff
70 */
71int sys_floor = 1; /* cluster stratum floor */
72int sys_ceiling = STRATUM_UNSPEC; /* cluster stratum ceiling*/
73int sys_minsane = 1; /* minimum candidates */
74int sys_minclock = NTP_MINCLOCK; /* minimum survivors */
75int sys_cohort = 0; /* cohort switch */
76int sys_ttlmax; /* max ttl mapping vector index */
77u_char sys_ttl[MAX_TTL]; /* ttl mapping vector */
78
79/*
65 * Statistics counters
66 */
80 * Statistics counters
81 */
67u_long sys_stattime; /* time when we started recording */
68u_long sys_badstratum; /* packets with invalid stratum */
69u_long sys_oldversionpkt; /* old version packets received */
70u_long sys_newversionpkt; /* new version packets received */
71u_long sys_unknownversion; /* don't know version packets */
72u_long sys_badlength; /* packets with bad length */
82u_long sys_stattime; /* time since reset */
83u_long sys_received; /* packets received */
73u_long sys_processed; /* packets processed */
84u_long sys_processed; /* packets processed */
74u_long sys_badauth; /* packets dropped because of auth */
75u_long sys_limitrejected; /* pkts rejected due to client count per net */
85u_long sys_newversionpkt; /* current version */
86u_long sys_oldversionpkt; /* recent version */
87u_long sys_unknownversion; /* invalid version */
88u_long sys_restricted; /* access denied */
89u_long sys_badlength; /* bad length or format */
90u_long sys_badauth; /* bad authentication */
91u_long sys_limitrejected; /* rate exceeded */
76
77static double root_distance P((struct peer *));
78static double clock_combine P((struct peer **, int));
79static void peer_xmit P((struct peer *));
80static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
81static void clock_update P((void));
82int default_get_precision P((void));
92
93static double root_distance P((struct peer *));
94static double clock_combine P((struct peer **, int));
95static void peer_xmit P((struct peer *));
96static void fast_xmit P((struct recvbuf *, int, keyid_t, int));
97static void clock_update P((void));
98int default_get_precision P((void));
99static int peer_unfit P((struct peer *));
83
100
84
85/*
86 * transmit - Transmit Procedure. See Section 3.4.2 of the
87 * specification.
88 */
89void
90transmit(
91 struct peer *peer /* peer structure pointer */
92 )
93{
101/*
102 * transmit - Transmit Procedure. See Section 3.4.2 of the
103 * specification.
104 */
105void
106transmit(
107 struct peer *peer /* peer structure pointer */
108 )
109{
94 int hpoll;
110 int hpoll;
95
111
112
113 /*
114 * The polling state machine. There are two kinds of machines,
115 * those that never expect a reply (broadcast and manycast
116 * server modes) and those that do (all other modes). The dance
117 * is intricate...
118 */
96 hpoll = peer->hpoll;
119 hpoll = peer->hpoll;
97 if (peer->burst == 0) {
98 u_char oreach;
120 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
99
100 /*
121
122 /*
101 * The polling state machine. There are two kinds of
102 * machines, those that never expect a reply (broadcast
103 * and manycast server modes) and those that do (all
104 * other modes). The dance is intricate...
123 * In broadcast mode the poll interval is fixed
124 * at minpoll.
105 */
125 */
106 if (peer->cast_flags & (MDF_BCAST | MDF_MCAST)) {
126 hpoll = peer->minpoll;
127 } else if (peer->cast_flags & MDF_ACAST) {
107
128
108 /*
109 * In broadcast mode the poll interval is fixed
110 * at minpoll and the ttl at ttlmax.
111 */
112 hpoll = peer->minpoll;
113 peer->ttl = peer->ttlmax;
114#ifdef AUTOKEY
115 } else if (peer->cast_flags & MDF_ACAST) {
129 /*
130 * In manycast mode we start with the minpoll interval
131 * and ttl. However, the actual poll interval is eight
132 * times the nominal poll interval shown here. If fewer
133 * than sys_minclock servers are found, the ttl is
134 * increased by one and we try again. If this continues
135 * to the max ttl, the poll interval is bumped by one
136 * and we try again. If at least sys_minclock servers
137 * are found, the poll interval increases with the
138 * system poll interval to the max and we continue
139 * indefinately. However, about once per day when the
140 * agreement parameters are refreshed, the manycast
141 * clients are reset and we start from the beginning.
142 * This is to catch and clamp the ttl to the lowest
143 * practical value and avoid knocking on spurious doors.
144 */
145 if (sys_survivors < sys_minclock && peer->ttl <
146 sys_ttlmax)
147 peer->ttl++;
148 hpoll = sys_poll;
149 } else {
116
150
117 /*
118 * In manycast mode we start with the minpoll
119 * interval and ttl. However, the actual poll
120 * interval is eight times the nominal poll
121 * interval shown here. If fewer than three
122 * servers are found, the ttl is increased by
123 * one and we try again. If this continues to
124 * the max ttl, the poll interval is bumped by
125 * one and we try again. If at least three
126 * servers are found, the poll interval
127 * increases with the system poll interval to
128 * the max and we continue indefinately.
129 * However, about once per day when the
130 * agreement parameters are refreshed, the
131 * manycast clients are reset and we start from
132 * the beginning. This is to catch and clamp the
133 * ttl to the lowest practical value and avoid
134 * knocking on spurious doors.
135 */
136 if (sys_survivors < NTP_MINCLOCK && peer->ttl <
137 peer->ttlmax)
138 peer->ttl++;
139 hpoll = sys_poll;
140#endif /* AUTOKEY */
141 } else {
151 /*
152 * For associations expecting a reply, the watchdog
153 * counter is bumped by one if the peer has not been
154 * heard since the previous poll. If the counter reaches
155 * the max, the poll interval is doubled and the peer is
156 * demobilized if not configured.
157 */
158 peer->unreach++;
159 if (peer->unreach >= NTP_UNREACH) {
160 hpoll++;
161 if (peer->flags & FLAG_CONFIG) {
142
162
143 /*
144 * For associations expecting a reply, the
145 * watchdog counter is bumped by one if the peer
146 * has not been heard since the previous poll.
147 * If the counter reaches the max, the peer is
148 * demobilized if not configured and just
149 * cleared if it is, but in this case the poll
150 * interval is bumped by one.
151 */
152 if (peer->unreach < NTP_UNREACH) {
153 peer->unreach++;
154 } else if (!(peer->flags & FLAG_CONFIG)) {
163 /*
164 * If nothing is likely to change in
165 * future, flash the access denied bit
166 * so we won't bother the dude again.
167 */
168 if (memcmp((char *)&peer->refid,
169 "DENY", 4) == 0 ||
170 memcmp((char *)&peer->refid,
171 "CRYP", 4) == 0)
172 peer->flash |= TEST4;
173 } else {
155 unpeer(peer);
174 unpeer(peer);
156 clock_select();
157 return;
175 return;
158
159 } else {
160 peer_clear(peer);
161 hpoll++;
162 }
163 }
176 }
177 }
164 oreach = peer->reach;
165 peer->reach <<= 1;
166 if (peer->reach == 0) {
178 if (peer->burst == 0) {
179 u_char oreach;
167
180
168 /*
169 * If this association has become unreachable,
170 * clear it and raise a trap.
171 */
172 if (oreach != 0) {
173 report_event(EVNT_UNREACH, peer);
174 peer->timereachable = current_time;
175 if (!(peer->flags & FLAG_CONFIG)) {
176 unpeer(peer);
181 oreach = peer->reach;
182 peer->reach <<= 1;
183 peer->hyst *= HYST_TC;
184 if (peer->reach == 0) {
185
186 /*
187 * If this association has become
188 * unreachable, clear it and raise a
189 * trap.
190 */
191 if (oreach != 0) {
192 report_event(EVNT_UNREACH,
193 peer);
194 peer->timereachable =
195 current_time;
196 if (peer->flags & FLAG_CONFIG) {
197 peer_clear(peer,
198 "INIT");
199 } else {
200 unpeer(peer);
201 return;
202 }
203 }
204 if (peer->flags & FLAG_IBURST)
205 peer->burst = NTP_BURST;
206 } else {
207 /*
208 * Here the peer is reachable. If it has
209 * not been heard for three consecutive
210 * polls, stuff the clock filter. Next,
211 * determine the poll interval. If the
212 * peer is unfit for synchronization,
213 * increase it by one; otherwise, use
214 * the system poll interval.
215 */
216 if (!(peer->reach & 0x07)) {
217 clock_filter(peer, 0., 0.,
218 MAXDISPERSE);
177 clock_select();
219 clock_select();
178 return;
179 } else {
180 peer_clear(peer);
181 hpoll = peer->minpoll;
182 }
220 }
221 if (peer_unfit(peer))
222 hpoll++;
223 else
224 hpoll = sys_poll;
225 if (peer->flags & FLAG_BURST)
226 peer->burst = NTP_BURST;
183 }
227 }
184 if (peer->flags & FLAG_IBURST)
185 peer->burst = NTP_SHIFT;
186 } else {
187
188 /*
228 } else {
229
230 /*
189 * Here the peer is reachable. If it has not
190 * been heard for three consecutive polls, stuff
191 * the clock filter. Next, determine the poll
192 * interval. If the peer is a synchronization
193 * candidate, use the system poll interval. If
194 * the peer is not sane, increase it by one. If
195 * the number of valid updates is not greater
196 * than half the register size, clamp it to the
197 * minimum. This is to quickly recover the time
198 * variables when a noisy peer shows life.
231 * Source rate control. If we are restrained,
232 * each burst consists of only one packet.
199 */
233 */
200 if (!(peer->reach & 0x07)) {
201 clock_filter(peer, 0., 0., MAXDISPERSE);
202 clock_select();
203 }
204 if ((peer->stratum > 1 && peer->refid ==
205 peer->dstadr->sin.sin_addr.s_addr) ||
206 peer->stratum >= STRATUM_UNSPEC)
207 hpoll++;
234 if (memcmp((char *)&peer->refid, "RSTR", 4) ==
235 0)
236 peer->burst = 0;
208 else
237 else
209 hpoll = sys_poll;
210 if (peer->flags & FLAG_BURST)
211 peer->burst = NTP_SHIFT;
212 }
213 } else {
214 peer->burst--;
215 if (peer->burst == 0) {
238 peer->burst--;
239 if (peer->burst == 0) {
240 /*
241 * If a broadcast client at this point,
242 * the burst has concluded, so we switch
243 * to client mode and purge the keylist,
244 * since no further transmissions will
245 * be made.
246 */
247 if (peer->cast_flags & MDF_BCLNT) {
248 peer->hmode = MODE_BCLIENT;
249#ifdef OPENSSL
250 key_expire(peer);
251#endif /* OPENSSL */
252 }
253 poll_update(peer, hpoll);
254 clock_select();
216
255
217 /*
218 * If a broadcast client at this point, the
219 * burst has concluded, so we switch to client
220 * mode and purge the keylist, since no further
221 * transmissions will be made.
222 */
223 if (peer->cast_flags & MDF_BCLNT) {
224 peer->hmode = MODE_BCLIENT;
225#ifdef AUTOKEY
226 key_expire(peer);
227#endif /* AUTOKEY */
256 /*
257 * If ntpdate mode and the clock has not
258 * been set and all peers have completed
259 * the burst, we declare a successful
260 * failure.
261 */
262 if (mode_ntpdate) {
263 peer_ntpdate--;
264 if (peer_ntpdate > 0) {
265 poll_update(
266 peer, hpoll);
267 return;
268 }
269 msyslog(LOG_NOTICE,
270 "no reply; clock not set");
271 exit (0);
272 }
273 poll_update(peer, hpoll);
274 return;
228 }
275 }
229 poll_update(peer, hpoll);
230 clock_select();
231
232 /*
233 * If ntpdate mode and the clock has not been
234 * set and all peers have completed the burst,
235 * we declare a successful failure.
236 */
237 if (mode_ntpdate) {
238 peer_ntpdate--;
239 if (peer_ntpdate > 0)
240 return;
241 NLOG(NLOG_SYNCEVENT | NLOG_SYSEVENT)
242 msyslog(LOG_NOTICE,
243 "no reply; clock not set");
244 printf(
245 "ntpd: no reply; clock not set\n");
246 exit(0);
247 }
248 return;
249
250 }
251 }
252 peer->outdate = current_time;
276 }
277 }
278 peer->outdate = current_time;
253 poll_update(peer, hpoll);
254
255 /*
279
280 /*
256 * We need to be very careful about honking uncivilized time.
257 * Never transmit if in broadcast client mode or access denied.
258 * If in broadcast mode, transmit only if synchronized to a
259 * valid source.
281 * Do not transmit if in broadcast cclient mode or access has
282 * been denied.
260 */
261 if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
283 */
284 if (peer->hmode == MODE_BCLIENT || peer->flash & TEST4) {
285 poll_update(peer, hpoll);
262 return;
286 return;
263 } else if (peer->hmode == MODE_BROADCAST) {
264 if (sys_peer == NULL)
265 return;
287
288 /*
289 * Do not transmit in broadcast mode unless we are synchronized.
290 */
291 } else if (peer->hmode == MODE_BROADCAST && sys_peer == NULL) {
292 poll_update(peer, hpoll);
293 return;
266 }
267 peer_xmit(peer);
294 }
295 peer_xmit(peer);
296 poll_update(peer, hpoll);
268}
269
270/*
271 * receive - Receive Procedure. See section 3.4.3 in the specification.
272 */
273void
274receive(
275 struct recvbuf *rbufp
276 )
277{
297}
298
299/*
300 * receive - Receive Procedure. See section 3.4.3 in the specification.
301 */
302void
303receive(
304 struct recvbuf *rbufp
305 )
306{
278 register struct peer *peer;
279 register struct pkt *pkt;
280 int hismode;
281 int oflags;
282 int restrict_mask;
283 int has_mac; /* length of MAC field */
284 int authlen; /* offset of MAC field */
285 int is_authentic; /* cryptosum ok */
286 keyid_t skeyid; /* cryptographic keys */
287 struct sockaddr_in *dstadr_sin; /* active runway */
288#ifdef AUTOKEY
289 keyid_t pkeyid, tkeyid; /* cryptographic keys */
290#endif /* AUTOKEY */
291 struct peer *peer2;
307 register struct peer *peer; /* peer structure pointer */
308 register struct pkt *pkt; /* receive packet pointer */
309 int hismode; /* packet mode */
310 int restrict_mask; /* restrict bits */
311 int has_mac; /* length of MAC field */
312 int authlen; /* offset of MAC field */
313 int is_authentic; /* cryptosum ok */
314 keyid_t skeyid = 0; /* key ID */
315 struct sockaddr_storage *dstadr_sin; /* active runway */
316 struct peer *peer2; /* aux peer structure pointer */
317 l_fp p_org; /* originate timestamp */
318 l_fp p_xmt; /* transmit timestamp */
319#ifdef OPENSSL
320 keyid_t tkeyid = 0; /* temporary key ID */
321 keyid_t pkeyid = 0; /* previous key ID */
322 struct autokey *ap; /* autokey structure pointer */
323 int rval; /* cookie snatcher */
324#endif /* OPENSSL */
292 int retcode = AM_NOMATCH;
293
294 /*
295 * Monitor the packet and get restrictions. Note that the packet
296 * length for control and private mode packets must be checked
297 * by the service routines. Note that no statistics counters are
298 * recorded for restrict violations, since these counters are in
299 * the restriction routine. Note the careful distinctions here
300 * between a packet with a format error and a packet that is
301 * simply discarded without prejudice. Some restrictions have to
302 * be handled later in order to generate a kiss-of-death packet.
303 */
325 int retcode = AM_NOMATCH;
326
327 /*
328 * Monitor the packet and get restrictions. Note that the packet
329 * length for control and private mode packets must be checked
330 * by the service routines. Note that no statistics counters are
331 * recorded for restrict violations, since these counters are in
332 * the restriction routine. Note the careful distinctions here
333 * between a packet with a format error and a packet that is
334 * simply discarded without prejudice. Some restrictions have to
335 * be handled later in order to generate a kiss-of-death packet.
336 */
337 /*
338 * Bogus port check is before anything, since it probably
339 * reveals a clogging attack.
340 */
341 sys_received++;
342 if (SRCPORT(&rbufp->recv_srcadr) == 0) {
343 sys_badlength++;
344 return; /* bogus port */
345 }
304 ntp_monitor(rbufp);
305 restrict_mask = restrictions(&rbufp->recv_srcadr);
306#ifdef DEBUG
346 ntp_monitor(rbufp);
347 restrict_mask = restrictions(&rbufp->recv_srcadr);
348#ifdef DEBUG
307 if (debug > 2)
308 printf("receive: at %ld %s<-%s restrict %02x\n",
309 current_time, ntoa(&rbufp->dstadr->sin),
310 ntoa(&rbufp->recv_srcadr), restrict_mask);
349 if (debug > 1)
350 printf("receive: at %ld %s<-%s restrict %03x\n",
351 current_time, stoa(&rbufp->dstadr->sin),
352 stoa(&rbufp->recv_srcadr), restrict_mask);
311#endif
353#endif
312 if (restrict_mask & RES_IGNORE)
354 if (restrict_mask & RES_IGNORE) {
355 sys_restricted++;
313 return; /* no anything */
356 return; /* no anything */
314
315 pkt = &rbufp->recv_pkt;
316 if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
317 sys_newversionpkt++; /* new version */
318 } else if (!(restrict_mask & RES_VERSION) &&
319 PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
320 sys_oldversionpkt++; /* old version */
321 } else {
322 sys_unknownversion++;
323 return; /* invalid version */
324 }
357 }
325 if (PKT_MODE(pkt->li_vn_mode) == MODE_PRIVATE) {
326 if (restrict_mask & RES_NOQUERY)
358 pkt = &rbufp->recv_pkt;
359 hismode = (int)PKT_MODE(pkt->li_vn_mode);
360 if (hismode == MODE_PRIVATE) {
361 if (restrict_mask & RES_NOQUERY) {
362 sys_restricted++;
327 return; /* no query private */
363 return; /* no query private */
364 }
328 process_private(rbufp, ((restrict_mask &
329 RES_NOMODIFY) == 0));
330 return;
331 }
365 process_private(rbufp, ((restrict_mask &
366 RES_NOMODIFY) == 0));
367 return;
368 }
332 if (PKT_MODE(pkt->li_vn_mode) == MODE_CONTROL) {
333 if (restrict_mask & RES_NOQUERY)
369 if (hismode == MODE_CONTROL) {
370 if (restrict_mask & RES_NOQUERY) {
371 sys_restricted++;
334 return; /* no query control */
372 return; /* no query control */
373 }
335 process_control(rbufp, restrict_mask);
336 return;
337 }
374 process_control(rbufp, restrict_mask);
375 return;
376 }
377 if (restrict_mask & RES_DONTSERVE) {
378 sys_restricted++;
379 return; /* no time */
380 }
338 if (rbufp->recv_length < LEN_PKT_NOMAC) {
339 sys_badlength++;
340 return; /* runt packet */
341 }
381 if (rbufp->recv_length < LEN_PKT_NOMAC) {
382 sys_badlength++;
383 return; /* runt packet */
384 }
385
386 /*
387 * Version check must be after the query packets, since they
388 * intentionally use early version.
389 */
390 if (PKT_VERSION(pkt->li_vn_mode) == NTP_VERSION) {
391 sys_newversionpkt++; /* new version */
392 } else if (!(restrict_mask & RES_VERSION) &&
393 PKT_VERSION(pkt->li_vn_mode) >= NTP_OLDVERSION) {
394 sys_oldversionpkt++; /* previous version */
395 } else {
396 sys_unknownversion++;
397 return; /* old version */
398 }
342
343 /*
399
400 /*
344 * Validate mode. Note that NTPv1 is no longer supported.
401 * Figure out his mode and validate the packet. This has some
402 * legacy raunch that probably should be removed. In very early
403 * NTP versions mode 0 was equivalent to what later versions
404 * would interpret as client mode.
345 */
405 */
346 hismode = (int)PKT_MODE(pkt->li_vn_mode);
347 if (hismode == MODE_UNSPEC) {
406 if (hismode == MODE_UNSPEC) {
348 sys_badlength++;
349 return; /* invalid mode */
407 if (PKT_VERSION(pkt->li_vn_mode) == NTP_OLDVERSION) {
408 hismode = MODE_CLIENT;
409 } else {
410 sys_badlength++;
411 return; /* invalid mode */
412 }
350 }
351
352 /*
413 }
414
415 /*
353 * Discard broadcast packets received on the wildcard interface
354 * or if not enabled as broadcast client.
416 * Discard broadcast if not enabled as broadcast client. If
417 * Autokey, the wildcard interface cannot be used, so dump
418 * packets gettiing off the bus at that stop as well. This means
419 * that some systems with broken interface code, specifically
420 * Linux, will not work with Autokey.
355 */
421 */
356 if (PKT_MODE(pkt->li_vn_mode) == MODE_BROADCAST &&
357 (rbufp->dstadr == any_interface || !sys_bclient))
358 return;
422 if (hismode == MODE_BROADCAST) {
423 if (!sys_bclient || restrict_mask & RES_NOPEER) {
424 sys_restricted++;
425 return; /* no client */
426 }
427#ifdef OPENSSL
428 if (crypto_flags && rbufp->dstadr == any_interface) {
429 sys_restricted++;
430 return; /* no client */
431 }
432#endif /* OPENSSL */
433 }
359
360 /*
361 * Parse the extension field if present. We figure out whether
362 * an extension field is present by measuring the MAC size. If
363 * the number of words following the packet header is 0 or 1, no
364 * MAC is present and the packet is not authenticated. If 1, the
365 * packet is a reply to a previous request that failed to
366 * authenticate. If 3, the packet is authenticated with DES; if
367 * 5, the packet is authenticated with MD5. If greater than 5,
368 * an extension field is present. If 2 or 4, the packet is a
369 * runt and goes poof! with a brilliant flash.
370 */
434
435 /*
436 * Parse the extension field if present. We figure out whether
437 * an extension field is present by measuring the MAC size. If
438 * the number of words following the packet header is 0 or 1, no
439 * MAC is present and the packet is not authenticated. If 1, the
440 * packet is a reply to a previous request that failed to
441 * authenticate. If 3, the packet is authenticated with DES; if
442 * 5, the packet is authenticated with MD5. If greater than 5,
443 * an extension field is present. If 2 or 4, the packet is a
444 * runt and goes poof! with a brilliant flash.
445 */
371 skeyid = 0;
372#ifdef AUTOKEY
373 pkeyid = tkeyid = 0;
374#endif /* AUTOKEY */
375 authlen = LEN_PKT_NOMAC;
446 authlen = LEN_PKT_NOMAC;
376 while ((has_mac = rbufp->recv_length - authlen) > 0) {
447 has_mac = rbufp->recv_length - authlen;
448 while (has_mac > 0) {
377 int temp;
378
379 if (has_mac % 4 != 0 || has_mac < 0) {
380 sys_badlength++;
449 int temp;
450
451 if (has_mac % 4 != 0 || has_mac < 0) {
452 sys_badlength++;
381 return;
453 return; /* bad MAC length */
382 }
383 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
384 MAX_MAC_LEN) {
385 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
386 break;
387
388 } else if (has_mac > MAX_MAC_LEN) {
389 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
390 0xffff;
454 }
455 if (has_mac == 1 * 4 || has_mac == 3 * 4 || has_mac ==
456 MAX_MAC_LEN) {
457 skeyid = ntohl(((u_int32 *)pkt)[authlen / 4]);
458 break;
459
460 } else if (has_mac > MAX_MAC_LEN) {
461 temp = ntohl(((u_int32 *)pkt)[authlen / 4]) &
462 0xffff;
391 if (temp < 4 || temp % 4 != 0) {
463 if (temp < 4 || temp > NTP_MAXEXTEN || temp % 4
464 != 0) {
392 sys_badlength++;
465 sys_badlength++;
393 return;
466 return; /* bad MAC length */
394 }
395 authlen += temp;
467 }
468 authlen += temp;
469 has_mac -= temp;
396 } else {
397 sys_badlength++;
470 } else {
471 sys_badlength++;
398 return;
472 return; /* bad MAC length */
399 }
400 }
473 }
474 }
475#ifdef OPENSSL
476 pkeyid = tkeyid = 0;
477#endif /* OPENSSL */
401
402 /*
403 * We have tossed out as many buggy packets as possible early in
404 * the game to reduce the exposure to a clogging attack. Now we
405 * have to burn some cycles to find the association and
406 * authenticate the packet if required. Note that we burn only
478
479 /*
480 * We have tossed out as many buggy packets as possible early in
481 * the game to reduce the exposure to a clogging attack. Now we
482 * have to burn some cycles to find the association and
483 * authenticate the packet if required. Note that we burn only
407 * MD5 or DES cycles, again to reduce exposure. There may be no
484 * MD5 cycles, again to reduce exposure. There may be no
408 * matching association and that's okay.
409 *
410 * More on the autokey mambo. Normally the local interface is
411 * found when the association was mobilized with respect to a
412 * designated remote address. We assume packets arriving from
413 * the remote address arrive via this interface and the local
414 * address used to construct the autokey is the unicast address
415 * of the interface. However, if the sender is a broadcaster,

--- 5 unchanged lines hidden (view full) ---

421 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
422 hismode, &retcode);
423 is_authentic = 0;
424 dstadr_sin = &rbufp->dstadr->sin;
425 if (has_mac == 0) {
426#ifdef DEBUG
427 if (debug)
428 printf("receive: at %ld %s<-%s mode %d code %d\n",
485 * matching association and that's okay.
486 *
487 * More on the autokey mambo. Normally the local interface is
488 * found when the association was mobilized with respect to a
489 * designated remote address. We assume packets arriving from
490 * the remote address arrive via this interface and the local
491 * address used to construct the autokey is the unicast address
492 * of the interface. However, if the sender is a broadcaster,

--- 5 unchanged lines hidden (view full) ---

498 peer = findpeer(&rbufp->recv_srcadr, rbufp->dstadr, rbufp->fd,
499 hismode, &retcode);
500 is_authentic = 0;
501 dstadr_sin = &rbufp->dstadr->sin;
502 if (has_mac == 0) {
503#ifdef DEBUG
504 if (debug)
505 printf("receive: at %ld %s<-%s mode %d code %d\n",
429 current_time, ntoa(&rbufp->dstadr->sin),
430 ntoa(&rbufp->recv_srcadr), hismode, retcode);
506 current_time, stoa(&rbufp->dstadr->sin),
507 stoa(&rbufp->recv_srcadr), hismode,
508 retcode);
431#endif
432 } else {
509#endif
510 } else {
433#ifdef AUTOKEY
511#ifdef OPENSSL
434 /*
435 * For autokey modes, generate the session key
436 * and install in the key cache. Use the socket
437 * broadcast or unicast address as appropriate.
438 */
439 if (skeyid > NTP_MAXKEY) {
440
441 /*

--- 26 unchanged lines hidden (view full) ---

468 /*
469 * For broadcaster, use the interface
470 * broadcast address when available;
471 * otherwise, use the unicast address
472 * found when the association was
473 * mobilized.
474 */
475 pkeyid = 0;
512 /*
513 * For autokey modes, generate the session key
514 * and install in the key cache. Use the socket
515 * broadcast or unicast address as appropriate.
516 */
517 if (skeyid > NTP_MAXKEY) {
518
519 /*

--- 26 unchanged lines hidden (view full) ---

546 /*
547 * For broadcaster, use the interface
548 * broadcast address when available;
549 * otherwise, use the unicast address
550 * found when the association was
551 * mobilized.
552 */
553 pkeyid = 0;
476 if (rbufp->dstadr->bcast.sin_addr.s_addr
477 != 0)
554 if (!SOCKNUL(&rbufp->dstadr->bcast))
478 dstadr_sin =
479 &rbufp->dstadr->bcast;
480 } else if (peer == NULL) {
481 pkeyid = session_key(
482 &rbufp->recv_srcadr, dstadr_sin, 0,
483 sys_private, 0);
484 } else {
555 dstadr_sin =
556 &rbufp->dstadr->bcast;
557 } else if (peer == NULL) {
558 pkeyid = session_key(
559 &rbufp->recv_srcadr, dstadr_sin, 0,
560 sys_private, 0);
561 } else {
485 pkeyid = peer->pcookie.key;
562 pkeyid = peer->pcookie;
486 }
487
488 /*
489 * The session key includes both the public
490 * values and cookie. In case of an extension
491 * field, the cookie used for authentication
492 * purposes is zero. Note the hash is saved for
493 * use later in the autokey mambo.

--- 6 unchanged lines hidden (view full) ---

500 skeyid, pkeyid, 0);
501 } else {
502 tkeyid = session_key(
503 &rbufp->recv_srcadr, dstadr_sin,
504 skeyid, pkeyid, 2);
505 }
506
507 }
563 }
564
565 /*
566 * The session key includes both the public
567 * values and cookie. In case of an extension
568 * field, the cookie used for authentication
569 * purposes is zero. Note the hash is saved for
570 * use later in the autokey mambo.

--- 6 unchanged lines hidden (view full) ---

577 skeyid, pkeyid, 0);
578 } else {
579 tkeyid = session_key(
580 &rbufp->recv_srcadr, dstadr_sin,
581 skeyid, pkeyid, 2);
582 }
583
584 }
508#endif /* AUTOKEY */
585#endif /* OPENSSL */
509
510 /*
511 * Compute the cryptosum. Note a clogging attack may
512 * succeed in bloating the key cache. If an autokey,
513 * purge it immediately, since we won't be needing it
586
587 /*
588 * Compute the cryptosum. Note a clogging attack may
589 * succeed in bloating the key cache. If an autokey,
590 * purge it immediately, since we won't be needing it
514 * again.
591 * again. If the packet is authentic, it may mobilize an
592 * association.
515 */
516 if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
593 */
594 if (authdecrypt(skeyid, (u_int32 *)pkt, authlen,
517 has_mac))
595 has_mac)) {
518 is_authentic = 1;
596 is_authentic = 1;
519 else
597 restrict_mask &= ~RES_DONTTRUST;
598 } else {
520 sys_badauth++;
599 sys_badauth++;
521#ifdef AUTOKEY
600 }
601#ifdef OPENSSL
522 if (skeyid > NTP_MAXKEY)
523 authtrust(skeyid, 0);
602 if (skeyid > NTP_MAXKEY)
603 authtrust(skeyid, 0);
524#endif /* AUTOKEY */
604#endif /* OPENSSL */
525#ifdef DEBUG
526 if (debug)
527 printf(
528 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
605#ifdef DEBUG
606 if (debug)
607 printf(
608 "receive: at %ld %s<-%s mode %d code %d keyid %08x len %d mac %d auth %d\n",
529 current_time, ntoa(dstadr_sin),
530 ntoa(&rbufp->recv_srcadr), hismode, retcode,
609 current_time, stoa(dstadr_sin),
610 stoa(&rbufp->recv_srcadr), hismode, retcode,
531 skeyid, authlen, has_mac,
532 is_authentic);
533#endif
534 }
535
536 /*
537 * The association matching rules are implemented by a set of
538 * routines and a table in ntp_peer.c. A packet matching an
539 * association is processed by that association. If not and
540 * certain conditions prevail, then an ephemeral association is
541 * mobilized: a broadcast packet mobilizes a broadcast client
611 skeyid, authlen, has_mac,
612 is_authentic);
613#endif
614 }
615
616 /*
617 * The association matching rules are implemented by a set of
618 * routines and a table in ntp_peer.c. A packet matching an
619 * association is processed by that association. If not and
620 * certain conditions prevail, then an ephemeral association is
621 * mobilized: a broadcast packet mobilizes a broadcast client
542 * aassociation; a server packet mobilizes a client association;
543 * a symmetric active packet mobilizes a symmetric passive
544 * association. And, the adventure continues...
622 * aassociation; a manycast server packet mobilizes a manycast
623 * client association; a symmetric active packet mobilizes a
624 * symmetric passive association. And, the adventure
625 * continues...
545 */
546 switch (retcode) {
547 case AM_FXMIT:
548
549 /*
550 * This is a client mode packet not matching a known
551 * association. If from a manycast client we run a few
552 * sanity checks before deciding to send a unicast
553 * server response. Otherwise, it must be a client
554 * request, so send a server response and go home.
555 */
556 if (sys_manycastserver && (rbufp->dstadr->flags &
557 INT_MULTICAST)) {
558
559 /*
626 */
627 switch (retcode) {
628 case AM_FXMIT:
629
630 /*
631 * This is a client mode packet not matching a known
632 * association. If from a manycast client we run a few
633 * sanity checks before deciding to send a unicast
634 * server response. Otherwise, it must be a client
635 * request, so send a server response and go home.
636 */
637 if (sys_manycastserver && (rbufp->dstadr->flags &
638 INT_MULTICAST)) {
639
640 /*
560 * We are picky about responding to a
561 * manycaster. There is no reason to respond to
562 * a request if our time is worse than the
563 * manycaster. We certainly don't reply if not
564 * synchronized to proventic time.
641 * There is no reason to respond to a request if
642 * our time is worse than the manycaster or it
643 * has already synchronized to us.
565 */
644 */
566 if (sys_peer == NULL)
567 return;
568
569 /*
570 * We don't reply if the our stratum is greater
571 * than the manycaster.
572 */
573 if (PKT_TO_STRATUM(pkt->stratum) < sys_stratum)
574 return;
645 if (sys_peer == NULL ||
646 PKT_TO_STRATUM(pkt->stratum) <
647 sys_stratum || (sys_cohort &&
648 PKT_TO_STRATUM(pkt->stratum) ==
649 sys_stratum) ||
650 rbufp->dstadr->addr_refid == pkt->refid)
651 return; /* manycast dropped */
575 }
576
577 /*
578 * Note that we don't require an authentication check
579 * here, since we can't set the system clock; but, we do
652 }
653
654 /*
655 * Note that we don't require an authentication check
656 * here, since we can't set the system clock; but, we do
580 * set the key ID to zero to tell the caller about this.
657 * send a crypto-NAK to tell the caller about this.
581 */
658 */
582 if (is_authentic)
659 if (has_mac && !is_authentic)
660 fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
661 else
583 fast_xmit(rbufp, MODE_SERVER, skeyid,
584 restrict_mask);
662 fast_xmit(rbufp, MODE_SERVER, skeyid,
663 restrict_mask);
585 else
586 fast_xmit(rbufp, MODE_SERVER, 0, restrict_mask);
587 return;
588
589 case AM_MANYCAST:
590
591 /*
592 * This is a server mode packet returned in response to
593 * a client mode packet sent to a multicast group
594 * address. The originate timestamp is a good nonce to
595 * reliably associate the reply with what was sent. If
596 * there is no match, that's curious and could be an
597 * intruder attempting to clog, so we just ignore it.
598 *
664 return;
665
666 case AM_MANYCAST:
667
668 /*
669 * This is a server mode packet returned in response to
670 * a client mode packet sent to a multicast group
671 * address. The originate timestamp is a good nonce to
672 * reliably associate the reply with what was sent. If
673 * there is no match, that's curious and could be an
674 * intruder attempting to clog, so we just ignore it.
675 *
599 * First, make sure the packet is authentic. If so and
600 * the manycast association is found, we mobilize a
601 * client mode association, copy pertinent variables
602 * from the manycast to the client mode association and
603 * wind up the spring.
676 * First, make sure the packet is authentic and not
677 * restricted. If so and the manycast association is
678 * found, we mobilize a client association and copy
679 * pertinent variables from the manycast association to
680 * the new client association.
604 *
605 * There is an implosion hazard at the manycast client,
606 * since the manycast servers send the server packet
681 *
682 * There is an implosion hazard at the manycast client,
683 * since the manycast servers send the server packet
607 * immediately.
684 * immediately. If the guy is already here, don't fire
685 * up a duplicate.
608 */
686 */
609 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
610 RES_NOPEER)) || (sys_authenticate &&
611 !is_authentic))
612 return;
687 if (restrict_mask & RES_DONTTRUST) {
688 sys_restricted++;
689 return; /* no trust */
690 }
613
691
614 peer2 = findmanycastpeer(rbufp);
615 if (peer2 == 0)
616 return;
692 if (sys_authenticate && !is_authentic)
693 return; /* bad auth */
617
694
618 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
695 if ((peer2 = findmanycastpeer(rbufp)) == NULL)
696 return; /* no assoc match */
697
698 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
619 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
699 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
620 sys_minpoll, NTP_MAXDPOLL, FLAG_IBURST |
621 (peer2->flags & (FLAG_AUTHENABLE | FLAG_SKEY)),
622 MDF_UCAST, 0, skeyid);
623 if (peer == NULL)
624 return;
700 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_IBURST, MDF_UCAST |
701 MDF_ACLNT, 0, skeyid)) == NULL)
702 return; /* system error */
703
704 /*
705 * We don't need these, but it warms the billboards.
706 */
707 peer->ttl = peer2->ttl;
625 break;
626
627 case AM_NEWPASS:
628
629 /*
630 * This is the first packet received from a symmetric
708 break;
709
710 case AM_NEWPASS:
711
712 /*
713 * This is the first packet received from a symmetric
631 * active peer. First, make sure the packet is
632 * authentic. If so, mobilize a symmetric passive
633 * association.
714 * active peer. First, make sure it is authentic and not
715 * restricted. If so, mobilize a passive association.
716 * If authentication fails send a crypto-NAK; otherwise,
717 * kiss the frog.
634 */
718 */
635 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
636 RES_NOPEER)) || (sys_authenticate &&
637 !is_authentic)) {
719 if (restrict_mask & RES_DONTTRUST) {
720 sys_restricted++;
721 return; /* no trust */
722 }
723 if (sys_authenticate && !is_authentic) {
638 fast_xmit(rbufp, MODE_PASSIVE, 0,
639 restrict_mask);
724 fast_xmit(rbufp, MODE_PASSIVE, 0,
725 restrict_mask);
640 return;
726 return; /* bad auth */
641 }
727 }
642 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
728 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
643 MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
729 MODE_PASSIVE, PKT_VERSION(pkt->li_vn_mode),
644 sys_minpoll, NTP_MAXDPOLL, sys_authenticate ?
645 FLAG_AUTHENABLE : 0, MDF_UCAST, 0, skeyid);
646 if (peer == NULL)
647 return;
730 NTP_MINDPOLL, NTP_MAXDPOLL, 0, MDF_UCAST, 0,
731 skeyid)) == NULL)
732 return; /* system error */
733
648 break;
649
650 case AM_NEWBCL:
651
652 /*
653 * This is the first packet received from a broadcast
734 break;
735
736 case AM_NEWBCL:
737
738 /*
739 * This is the first packet received from a broadcast
654 * server. First, make sure the packet is authentic, not
655 * restricted and that we are a broadcast or multicast
656 * client. If so, mobilize a broadcast client
657 * association.
740 * server. First, make sure it is authentic and not
741 * restricted and that we are a broadcast client. If so,
742 * mobilize a broadcast client association. We don't
743 * kiss any frogs here.
658 */
744 */
659 if ((restrict_mask & (RES_DONTSERVE | RES_LIMITED |
660 RES_NOPEER)) || (sys_authenticate &&
661 !is_authentic) || !sys_bclient)
662 return;
745 if (restrict_mask & RES_DONTTRUST) {
746 sys_restricted++;
747 return; /* no trust */
748 }
749 if (sys_authenticate && !is_authentic)
750 return; /* bad auth */
663
751
664 peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
752 if (!sys_bclient)
753 return; /* not a client */
754
755 if ((peer = newpeer(&rbufp->recv_srcadr, rbufp->dstadr,
665 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
756 MODE_CLIENT, PKT_VERSION(pkt->li_vn_mode),
666 sys_minpoll, NTP_MAXDPOLL, FLAG_MCAST |
667 FLAG_IBURST | (sys_authenticate ?
668 FLAG_AUTHENABLE : 0), MDF_BCLNT, 0, skeyid);
669#ifdef AUTOKEY
670#ifdef PUBKEY
671 if (peer == NULL)
672 return;
673 if (peer->flags & FLAG_SKEY)
674 crypto_recv(peer, rbufp);
675#endif /* PUBKEY */
676#endif /* AUTOKEY */
757 NTP_MINDPOLL, NTP_MAXDPOLL, FLAG_MCAST |
758 FLAG_IBURST, MDF_BCLNT, 0, skeyid)) == NULL)
759 return; /* system error */
760#ifdef OPENSSL
761 /*
762 * Danger looms. If this is autokey, go process the
763 * extension fields. If something goes wrong, abandon
764 * ship and don't trust subsequent packets.
765 */
766 if (crypto_flags) {
767 if ((rval = crypto_recv(peer, rbufp)) !=
768 XEVNT_OK) {
769 struct sockaddr_storage mskadr_sin;
770
771 unpeer(peer);
772 sys_restricted++;
773 SET_HOSTMASK(&mskadr_sin,
774 rbufp->recv_srcadr.ss_family);
775 hack_restrict(RESTRICT_FLAGS,
776 &rbufp->recv_srcadr, &mskadr_sin,
777 0, RES_DONTTRUST | RES_TIMEOUT);
778#ifdef DEBUG
779 if (debug)
780 printf(
781 "packet: bad exten %x\n",
782 rval);
783#endif
784 }
785 }
786#endif /* OPENSSL */
677 return;
678
679 case AM_POSSBCL:
787 return;
788
789 case AM_POSSBCL:
790
791 /*
792 * This is a broadcast packet received in client mode.
793 * It could happen if the initial client/server volley
794 * is not complete before the next broadcast packet is
795 * received. Be liberal in what we accept.
796 */
680 case AM_PROCPKT:
681
682 /*
797 case AM_PROCPKT:
798
799 /*
683 * Happiness and nothing broke. Earn some revenue.
800 * This is a symmetric mode packet received in symmetric
801 * mode, a server packet received in client mode or a
802 * broadcast packet received in broadcast client mode.
803 * If it is restricted, this is very strange because it
804 * is rude to send a packet to a restricted address. If
805 * anyway, flash a restrain kiss and skedaddle to
806 * Seattle. If not authentic, leave a light on and
807 * continue.
684 */
808 */
809 peer->flash = 0;
810 if (restrict_mask & RES_DONTTRUST) {
811 sys_restricted++;
812 if (peer->flags & FLAG_CONFIG)
813 peer_clear(peer, "RSTR");
814 else
815 unpeer(peer);
816 return; /* no trust */
817 }
818 if (has_mac && !is_authentic)
819 peer->flash |= TEST5; /* bad auth */
685 break;
686
687 default:
688
689 /*
820 break;
821
822 default:
823
824 /*
690 * Invalid mode combination. Leave the island
691 * immediately.
825 * Invalid mode combination. This happens when a passive
826 * mode packet arrives and matches another passive
827 * association or no association at all, or when a
828 * server mode packet arrives and matches a broadcast
829 * client association. This is usually the result of
830 * reconfiguring a client on-fly. If authenticated
831 * passive mode packet, send a crypto-NAK; otherwise,
832 * ignore it.
692 */
833 */
834 if (has_mac && hismode == MODE_PASSIVE)
835 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
693#ifdef DEBUG
694 if (debug)
695 printf("receive: bad protocol %d\n", retcode);
696#endif
697 return;
698 }
699
700 /*
836#ifdef DEBUG
837 if (debug)
838 printf("receive: bad protocol %d\n", retcode);
839#endif
840 return;
841 }
842
843 /*
701 * If the peer isn't configured, set his authenable and autokey
702 * status based on the packet. Once the status is set, it can't
703 * be unset. It seems like a silly idea to do this here, rather
704 * in the configuration routine, but in some goofy cases the
705 * first packet sent cannot be authenticated and we need a way
706 * for the dude to change his mind.
844 * We do a little homework. Note we can get here with an
845 * authentication error. We Need to do this in order to validate
846 * a crypto-NAK later. Note the order of processing; it is very
847 * important to avoid livelocks, deadlocks and lockpicks.
707 */
848 */
708 oflags = peer->flags;
709 peer->timereceived = current_time;
710 peer->received++;
849 peer->timereceived = current_time;
850 peer->received++;
711 if (!(peer->flags & FLAG_CONFIG) && has_mac) {
712 peer->flags |= FLAG_AUTHENABLE;
713#ifdef AUTOKEY
714 if (skeyid > NTP_MAXKEY)
715 peer->flags |= FLAG_SKEY;
716#endif /* AUTOKEY */
717 }
851 if (peer->flash & TEST5)
852 peer->flags &= ~FLAG_AUTHENTIC;
853 else
854 peer->flags |= FLAG_AUTHENTIC;
855 NTOHL_FP(&pkt->org, &p_org);
856 NTOHL_FP(&pkt->xmt, &p_xmt);
718
719 /*
857
858 /*
720 * A valid packet must be from an authentic and allowed source.
721 * All packets must pass the authentication allowed tests.
722 * Autokey authenticated packets must pass additional tests and
723 * public-key authenticated packets must have the credentials
724 * verified. If all tests are passed, the packet is forwarded
725 * for processing. If not, the packet is discarded and the
726 * association demobilized if appropriate.
859 * If the packet is an old duplicate, we let it through so the
860 * extension fields will be processed.
727 */
861 */
728 peer->flash = 0;
729 if (is_authentic) {
730 peer->flags |= FLAG_AUTHENTIC;
862 if (L_ISEQU(&peer->org, &p_xmt)) { /* test 1 */
863 peer->flash |= TEST1; /* dupe */
864 /* fall through */
865
866 /*
867 * For broadcast server mode, loopback checking is disabled. An
868 * authentication error probably means the server restarted or
869 * rolled a new private value. If so, dump the association
870 * and wait for the next message.
871 */
872 } else if (hismode == MODE_BROADCAST) {
873 if (peer->flash & TEST5) {
874 unpeer(peer);
875 return;
876 }
877 /* fall through */
878
879 /*
880 * For server and symmetric modes, if the association transmit
881 * timestamp matches the packet originate timestamp, loopback is
882 * confirmed. Note in symmetric modes this also happens when the
883 * first packet from the active peer arrives at the newly
884 * mobilized passive peer. An authentication error probably
885 * means the server or peer restarted or rolled a new private
886 * value, but could be an intruder trying to stir up trouble.
887 * However, if this is a crypto-NAK, we know it is authentic, so
888 * dump the association and wait for the next message.
889 */
890 } else if (L_ISEQU(&peer->xmt, &p_org)) {
891 if (peer->flash & TEST5) {
892 if (has_mac == 4 && pkt->exten[0] == 0) {
893 if (peer->flags & FLAG_CONFIG)
894 peer_clear(peer, "AUTH");
895 else
896 unpeer(peer);
897 }
898 return;
899 }
900 /* fall through */
901
902 /*
903 * If the client or passive peer has never transmitted anything,
904 * this is either the first message from a symmetric peer or
905 * possibly a duplicate received before the transmit timeout.
906 * Pass it on.
907 */
908 } else if (L_ISZERO(&peer->xmt)) {
909 /* fall through */
910
911 /*
912 * Now it gets interesting. We have transmitted at least one
913 * packet. If the packet originate timestamp is nonzero, it
914 * does not match the association transmit timestamp, which is a
915 * loopback error. This error might mean a manycast server has
916 * answered a manycast honk from us and we already have an
917 * association for him, in which case quietly drop the packet
918 * here. It might mean an old duplicate, dropped packet or
919 * intruder replay, in which case we drop it later after
920 * extension field processing, but never let it touch the time
921 * values.
922 */
923 } else if (!L_ISZERO(&p_org)) {
924 if (peer->cast_flags & MDF_ACLNT)
925 return; /* not a client */
926
927 peer->flash |= TEST2;
928 /* fall through */
929
930 /*
931 * The packet originate timestamp is zero, meaning the other guy
932 * either didn't receive the first packet or died and restarted.
933 * If the association originate timestamp is zero, this is the
934 * first packet received, so we pass it on.
935 */
936 } else if (L_ISZERO(&peer->org)) {
937 /* fall through */
938
939 /*
940 * The other guy has restarted and we are still on the wire. We
941 * should demobilize/clear and get out of Dodge. If this is
942 * symmetric mode, we should also send a crypto-NAK.
943 */
731 } else {
944 } else {
732 peer->flags &= ~FLAG_AUTHENTIC;
733 }
734 if (peer->hmode == MODE_BROADCAST &&
735 (restrict_mask & RES_DONTTRUST)) /* test 4 */
736 peer->flash |= TEST4; /* access denied */
737 if (peer->flags & FLAG_AUTHENABLE) {
738 if (!(peer->flags & FLAG_AUTHENTIC)) /* test 5 */
739 peer->flash |= TEST5; /* auth failed */
740 else if (!(oflags & FLAG_AUTHENABLE))
741 report_event(EVNT_PEERAUTH, peer);
742 }
743 if (peer->flash) {
744#ifdef DEBUG
945 if (hismode == MODE_ACTIVE)
946 fast_xmit(rbufp, MODE_PASSIVE, 0,
947 restrict_mask);
948 else if (hismode == MODE_PASSIVE)
949 fast_xmit(rbufp, MODE_ACTIVE, 0, restrict_mask);
950#if DEBUG
745 if (debug)
951 if (debug)
746 printf("receive: bad auth %03x\n", peer->flash);
952 printf("receive: dropped %03x\n", peer->flash);
747#endif
953#endif
954 if (peer->flags & FLAG_CONFIG)
955 peer_clear(peer, "DROP");
956 else
957 unpeer(peer);
748 return;
749 }
958 return;
959 }
960 if (peer->flash & ~TEST2) {
961 return;
962 }
750
963
751#ifdef AUTOKEY
964#ifdef OPENSSL
752 /*
753 * More autokey dance. The rules of the cha-cha are as follows:
754 *
755 * 1. If there is no key or the key is not auto, do nothing.
756 *
965 /*
966 * More autokey dance. The rules of the cha-cha are as follows:
967 *
968 * 1. If there is no key or the key is not auto, do nothing.
969 *
757 * 2. If an extension field contains a verified signature, it is
970 * 2. If this packet is in response to the one just previously
971 * sent or from a broadcast server, do the extension fields.
972 * Otherwise, assume bogosity and bail out.
973 *
974 * 3. If an extension field contains a verified signature, it is
758 * self-authenticated and we sit the dance.
759 *
975 * self-authenticated and we sit the dance.
976 *
760 * 3. If this is a server reply, check only to see that the
977 * 4. If this is a server reply, check only to see that the
761 * transmitted key ID matches the received key ID.
762 *
978 * transmitted key ID matches the received key ID.
979 *
763 * 4. Check to see that one or more hashes of the current key ID
980 * 5. Check to see that one or more hashes of the current key ID
764 * matches the previous key ID or ultimate original key ID
765 * obtained from the broadcaster or symmetric peer. If no
766 * match, sit the dance and wait for timeout.
767 */
981 * matches the previous key ID or ultimate original key ID
982 * obtained from the broadcaster or symmetric peer. If no
983 * match, sit the dance and wait for timeout.
984 */
768 if (peer->flags & FLAG_SKEY) {
985 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
769 peer->flash |= TEST10;
986 peer->flash |= TEST10;
770 crypto_recv(peer, rbufp);
771 poll_update(peer, peer->hpoll);
772 if (hismode == MODE_SERVER) {
987 rval = crypto_recv(peer, rbufp);
988 if (rval != XEVNT_OK) {
989 /* fall through */
990
991 } else if (hismode == MODE_SERVER) {
773 if (skeyid == peer->keyid)
774 peer->flash &= ~TEST10;
775 } else if (!peer->flash & TEST10) {
776 peer->pkeyid = skeyid;
992 if (skeyid == peer->keyid)
993 peer->flash &= ~TEST10;
994 } else if (!peer->flash & TEST10) {
995 peer->pkeyid = skeyid;
777 } else {
996 } else if ((ap = (struct autokey *)peer->recval.ptr) !=
997 NULL) {
778 int i;
779
780 for (i = 0; ; i++) {
781 if (tkeyid == peer->pkeyid ||
998 int i;
999
1000 for (i = 0; ; i++) {
1001 if (tkeyid == peer->pkeyid ||
782 tkeyid == peer->recauto.key) {
1002 tkeyid == ap->key) {
783 peer->flash &= ~TEST10;
784 peer->pkeyid = skeyid;
785 break;
786 }
1003 peer->flash &= ~TEST10;
1004 peer->pkeyid = skeyid;
1005 break;
1006 }
787 if (i > peer->recauto.seq)
1007 if (i > ap->seq)
788 break;
789 tkeyid = session_key(
790 &rbufp->recv_srcadr, dstadr_sin,
791 tkeyid, pkeyid, 0);
792 }
793 }
1008 break;
1009 tkeyid = session_key(
1010 &rbufp->recv_srcadr, dstadr_sin,
1011 tkeyid, pkeyid, 0);
1012 }
1013 }
794#ifdef PUBKEY
1014 if (!(peer->crypto & CRYPTO_FLAG_PROV)) /* test 11 */
1015 peer->flash |= TEST11; /* not proventic */
795
796 /*
1016
1017 /*
797 * This is delicious. Ordinarily, we kick out all errors
798 * at this point; however, in symmetric mode and just
799 * warming up, an unsynchronized peer must inject the
800 * timestamps, even if it fails further up the road. So,
801 * let the dude by here, but only if the jerk is not yet
802 * reachable. After that, he's on his own.
1018 * If the transmit queue is nonempty, clamp the host
1019 * poll interval to the packet poll interval.
803 */
1020 */
804 if (!(peer->flags & FLAG_PROVEN))
805 peer->flash |= TEST11;
806 if (peer->flash && peer->reach) {
1021 if (peer->cmmd != 0) {
1022 peer->ppoll = pkt->ppoll;
1023 poll_update(peer, 0);
1024 }
1025
1026 /*
1027 * If the return code from extension field processing is
1028 * not okay, we scrub the association and start over.
1029 */
1030 if (rval != XEVNT_OK) {
1031
1032 /*
1033 * If the return code is bad, the crypto machine
1034 * may be jammed or an intruder may lurk. First,
1035 * we demobilize the association, then see if
1036 * the error is recoverable.
1037 */
1038 if (peer->flags & FLAG_CONFIG)
1039 peer_clear(peer, "CRYP");
1040 else
1041 unpeer(peer);
807#ifdef DEBUG
808 if (debug)
1042#ifdef DEBUG
1043 if (debug)
809 printf("packet: bad autokey %03x\n",
1044 printf("packet: bad exten %x\n", rval);
1045#endif
1046 return;
1047 }
1048
1049 /*
1050 * If TEST10 is lit, the autokey sequence has broken,
1051 * which probably means the server has refreshed its
1052 * private value. We reset the poll interval to the
1053 & minimum and scrub the association clean.
1054 */
1055 if (peer->flash & TEST10 && peer->crypto &
1056 CRYPTO_FLAG_AUTO) {
1057 poll_update(peer, peer->minpoll);
1058#ifdef DEBUG
1059 if (debug)
1060 printf(
1061 "packet: bad auto %03x\n",
810 peer->flash);
811#endif
1062 peer->flash);
1063#endif
1064 if (peer->flags & FLAG_CONFIG)
1065 peer_clear(peer, "AUTO");
1066 else
1067 unpeer(peer);
812 return;
813 }
1068 return;
1069 }
814#endif /* PUBKEY */
815 }
1070 }
816#endif /* AUTOKEY */
1071#endif /* OPENSSL */
817
818 /*
819 * We have survived the gaunt. Forward to the packet routine. If
820 * a symmetric passive association has been mobilized and the
821 * association doesn't deserve to live, it will die in the
1072
1073 /*
1074 * We have survived the gaunt. Forward to the packet routine. If
1075 * a symmetric passive association has been mobilized and the
1076 * association doesn't deserve to live, it will die in the
822 * transmit routine if not reachable after timeout.
1077 * transmit routine if not reachable after timeout. However, if
1078 * either symmetric mode and the crypto code has something
1079 * urgent to say, we expedite the response.
823 */
824 process_packet(peer, pkt, &rbufp->recv_time);
825}
826
827
828/*
829 * process_packet - Packet Procedure, a la Section 3.4.4 of the
830 * specification. Or almost, at least. If we're in here we have a
831 * reasonable expectation that we will be having a long term
832 * relationship with this host.
833 */
834void
835process_packet(
836 register struct peer *peer,
837 register struct pkt *pkt,
1080 */
1081 process_packet(peer, pkt, &rbufp->recv_time);
1082}
1083
1084
1085/*
1086 * process_packet - Packet Procedure, a la Section 3.4.4 of the
1087 * specification. Or almost, at least. If we're in here we have a
1088 * reasonable expectation that we will be having a long term
1089 * relationship with this host.
1090 */
1091void
1092process_packet(
1093 register struct peer *peer,
1094 register struct pkt *pkt,
838 l_fp *recv_ts
1095 l_fp *recv_ts
839 )
840{
1096 )
1097{
841 l_fp t10, t23;
842 double p_offset, p_del, p_disp;
843 double dtemp;
844 l_fp p_rec, p_xmt, p_org, p_reftime;
845 l_fp ci;
846 int pmode, pleap, pstratum;
1098 l_fp t34, t21;
1099 double p_offset, p_del, p_disp;
1100 double dtemp;
1101 l_fp p_rec, p_xmt, p_org, p_reftime;
1102 l_fp ci;
1103 u_char pmode, pleap, pstratum;
847
848 /*
849 * Swap header fields and keep the books. The books amount to
850 * the receive timestamp and poll interval in the header. We
851 * need these even if there are other problems in order to crank
852 * up the state machine.
853 */
854 sys_processed++;
855 peer->processed++;
856 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
857 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
858 NTOHL_FP(&pkt->reftime, &p_reftime);
859 NTOHL_FP(&pkt->rec, &p_rec);
860 NTOHL_FP(&pkt->xmt, &p_xmt);
1104
1105 /*
1106 * Swap header fields and keep the books. The books amount to
1107 * the receive timestamp and poll interval in the header. We
1108 * need these even if there are other problems in order to crank
1109 * up the state machine.
1110 */
1111 sys_processed++;
1112 peer->processed++;
1113 p_del = FPTOD(NTOHS_FP(pkt->rootdelay));
1114 p_disp = FPTOD(NTOHS_FP(pkt->rootdispersion));
1115 NTOHL_FP(&pkt->reftime, &p_reftime);
1116 NTOHL_FP(&pkt->rec, &p_rec);
1117 NTOHL_FP(&pkt->xmt, &p_xmt);
861 if (PKT_MODE(pkt->li_vn_mode) != MODE_BROADCAST)
1118 pmode = PKT_MODE(pkt->li_vn_mode);
1119 pleap = PKT_LEAP(pkt->li_vn_mode);
1120 if (pmode != MODE_BROADCAST)
862 NTOHL_FP(&pkt->org, &p_org);
863 else
864 p_org = peer->rec;
1121 NTOHL_FP(&pkt->org, &p_org);
1122 else
1123 p_org = peer->rec;
1124 pstratum = PKT_TO_STRATUM(pkt->stratum);
865
866 /*
1125
1126 /*
867 * Test for old, duplicate or unsynch packets (tests 1-3).
1127 * Test for unsynchronized server.
868 */
1128 */
869 peer->rec = *recv_ts;
870 pmode = PKT_MODE(pkt->li_vn_mode);
871 pleap = PKT_LEAP(pkt->li_vn_mode);
872 pstratum = PKT_TO_STRATUM(pkt->stratum);
873 if (L_ISHIS(&peer->org, &p_xmt)) /* count old packets */
874 peer->oldpkt++;
1129 if (L_ISHIS(&peer->org, &p_xmt)) /* count old packets */
1130 peer->oldpkt++;
875 if (L_ISEQU(&peer->org, &p_xmt)) /* 1 */
876 peer->flash |= TEST1; /* dupe */
877 if (pmode != MODE_BROADCAST) {
878 if (!L_ISEQU(&peer->xmt, &p_org)) /* 2 */
879 peer->flash |= TEST2; /* bogus */
880 if (L_ISZERO(&p_rec) || L_ISZERO(&p_org)) /* test 3 */
881 peer->flash |= TEST3; /* unsynch */
882 }
883 if (L_ISZERO(&p_xmt)) /* 3 */
1131 if (pmode != MODE_BROADCAST && (L_ISZERO(&p_rec) ||
1132 L_ISZERO(&p_org))) /* test 3 */
884 peer->flash |= TEST3; /* unsynch */
1133 peer->flash |= TEST3; /* unsynch */
885 peer->org = p_xmt;
1134 if (L_ISZERO(&p_xmt)) /* test 3 */
1135 peer->flash |= TEST3; /* unsynch */
886
887 /*
1136
1137 /*
888 * If tests 1-3 fail, the packet is discarded leaving only the
889 * receive and origin timestamps and poll interval, which is
890 * enough to get the protocol started.
1138 * If any tests fail, the packet is discarded leaving only the
1139 * timestamps, which are enough to get the protocol started. The
1140 * originate timestamp is copied from the packet transmit
1141 * timestamp and the receive timestamp is copied from the
1142 * packet receive timestamp. If okay so far, we save the leap,
1143 * stratum and refid for billboards.
891 */
1144 */
1145 peer->org = p_xmt;
1146 peer->rec = *recv_ts;
892 if (peer->flash) {
893#ifdef DEBUG
894 if (debug)
1147 if (peer->flash) {
1148#ifdef DEBUG
1149 if (debug)
895 printf("packet: bad data %03x\n",
896 peer->flash);
1150 printf("packet: bad data %03x from address: %s\n",
1151 peer->flash, stoa(&peer->srcadr));
897#endif
898 return;
899 }
1152#endif
1153 return;
1154 }
1155 peer->leap = pleap;
1156 peer->stratum = pstratum;
1157 peer->refid = pkt->refid;
900
901 /*
1158
1159 /*
902 * A kiss-of-death (kod) packet is returned by a server in case
903 * the client is denied access. It consists of the client
904 * request packet with the leap bits indicating never
905 * synchronized, stratum zero and reference ID field the ASCII
906 * string "DENY". If the packet originate timestamp matches the
907 * association transmit timestamp the kod is legitimate. If the
908 * peer leap bits indicate never synchronized, this must be
909 * access deny and the association is disabled; otherwise this
910 * must be a limit reject. In either case a naughty message is
911 * forced to the system log.
912 */
913 if (pleap == LEAP_NOTINSYNC && pstratum >= STRATUM_UNSPEC &&
914 memcmp(&pkt->refid, "DENY", 4) == 0) {
915 if (peer->leap == LEAP_NOTINSYNC) {
916 peer->stratum = STRATUM_UNSPEC;
917 peer->flash |= TEST4;
918 memcpy(&peer->refid, &pkt->refid, 4);
919 msyslog(LOG_INFO, "access denied");
920 } else {
921 msyslog(LOG_INFO, "limit reject");
922 }
923 return;
924 }
925
926 /*
927 * Test for valid peer data (tests 6-8)
928 */
929 ci = p_xmt;
930 L_SUB(&ci, &p_reftime);
931 LFPTOD(&ci, dtemp);
1160 * Test for valid peer data (tests 6-8)
1161 */
1162 ci = p_xmt;
1163 L_SUB(&ci, &p_reftime);
1164 LFPTOD(&ci, dtemp);
932 if (pleap == LEAP_NOTINSYNC || /* 6 */
1165 if (pleap == LEAP_NOTINSYNC || /* test 6 */
933 pstratum >= STRATUM_UNSPEC || dtemp < 0)
934 peer->flash |= TEST6; /* bad synch */
1166 pstratum >= STRATUM_UNSPEC || dtemp < 0)
1167 peer->flash |= TEST6; /* bad synch */
935 if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* 7 */
936 if (pstratum > sys_stratum && pmode != MODE_ACTIVE) {
1168 if (!(peer->flags & FLAG_CONFIG) && sys_peer != NULL) { /* test 7 */
1169 if (pstratum > sys_stratum && pmode != MODE_ACTIVE)
937 peer->flash |= TEST7; /* bad stratum */
1170 peer->flash |= TEST7; /* bad stratum */
938 sys_badstratum++;
939 }
940 }
1171 }
941 if (p_del < 0 || p_disp < 0 || p_del / /* 8 */
1172 if (p_del < 0 || p_disp < 0 || p_del / /* test 8 */
942 2 + p_disp >= MAXDISPERSE)
1173 2 + p_disp >= MAXDISPERSE)
943 peer->flash |= TEST8; /* bad peer distance */
1174 peer->flash |= TEST8; /* bad peer values */
1175
1176 /*
1177 * If any tests fail at this point, the packet is discarded.
1178 */
944 if (peer->flash) {
945#ifdef DEBUG
946 if (debug)
947 printf("packet: bad header %03x\n",
948 peer->flash);
949#endif
950 return;
951 }
952
953 /*
954 * The header is valid. Capture the remaining header values and
955 * mark as reachable.
956 */
957 record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
958 &p_rec, &p_xmt, &peer->rec);
1179 if (peer->flash) {
1180#ifdef DEBUG
1181 if (debug)
1182 printf("packet: bad header %03x\n",
1183 peer->flash);
1184#endif
1185 return;
1186 }
1187
1188 /*
1189 * The header is valid. Capture the remaining header values and
1190 * mark as reachable.
1191 */
1192 record_raw_stats(&peer->srcadr, &peer->dstadr->sin, &p_org,
1193 &p_rec, &p_xmt, &peer->rec);
959 peer->leap = pleap;
960 peer->pmode = pmode;
1194 peer->pmode = pmode;
961 peer->stratum = pstratum;
962 peer->ppoll = pkt->ppoll;
963 peer->precision = pkt->precision;
964 peer->rootdelay = p_del;
965 peer->rootdispersion = p_disp;
1195 peer->ppoll = pkt->ppoll;
1196 peer->precision = pkt->precision;
1197 peer->rootdelay = p_del;
1198 peer->rootdispersion = p_disp;
966 peer->refid = pkt->refid;
967 peer->reftime = p_reftime;
968 if (!(peer->reach)) {
969 report_event(EVNT_REACH, peer);
970 peer->timereachable = current_time;
971 }
972 peer->reach |= 1;
973 peer->unreach = 0;
1199 peer->reftime = p_reftime;
1200 if (!(peer->reach)) {
1201 report_event(EVNT_REACH, peer);
1202 peer->timereachable = current_time;
1203 }
1204 peer->reach |= 1;
1205 peer->unreach = 0;
974 poll_update(peer, peer->hpoll);
1206 poll_update(peer, 0);
975
976 /*
977 * If running in a client/server association, calculate the
978 * clock offset c, roundtrip delay d and dispersion e. We use
979 * the equations (reordered from those in the spec). Note that,
980 * in a broadcast association, org has been set to the time of
981 * last reception. Note the computation of dispersion includes
982 * the system precision plus that due to the frequency error
983 * since the originate time.
984 *
1207
1208 /*
1209 * If running in a client/server association, calculate the
1210 * clock offset c, roundtrip delay d and dispersion e. We use
1211 * the equations (reordered from those in the spec). Note that,
1212 * in a broadcast association, org has been set to the time of
1213 * last reception. Note the computation of dispersion includes
1214 * the system precision plus that due to the frequency error
1215 * since the originate time.
1216 *
985 * c = ((t2 - t3) + (t1 - t0)) / 2
986 * d = (t2 - t3) - (t1 - t0)
987 * e = (org - rec) (seconds only)
1217 * Let t1 = p_org, t2 = p_rec, t3 = p_xmt, t4 = peer->rec:
988 */
1218 */
989 t10 = p_xmt; /* compute t1 - t0 */
990 L_SUB(&t10, &peer->rec);
991 t23 = p_rec; /* compute t2 - t3 */
992 L_SUB(&t23, &p_org);
993 ci = t10;
994 p_disp = clock_phi * (peer->rec.l_ui - p_org.l_ui);
1219 t34 = p_xmt; /* t3 - t4 */
1220 L_SUB(&t34, &peer->rec);
1221 t21 = p_rec; /* t2 - t1 */
1222 L_SUB(&t21, &p_org);
1223 ci = peer->rec; /* t4 - t1 */
1224 L_SUB(&ci, &p_org);
1225 LFPTOD(&ci, p_disp);
1226 p_disp = clock_phi * max(p_disp, LOGTOD(sys_precision));
995
996 /*
997 * If running in a broadcast association, the clock offset is
998 * (t1 - t0) corrected by the one-way delay, but we can't
999 * measure that directly. Therefore, we start up in MODE_CLIENT
1000 * mode, set FLAG_MCAST and exchange eight messages to determine
1001 * the clock offset. When the last message is sent, we switch to
1002 * MODE_BCLIENT mode. The next broadcast message after that
1003 * computes the broadcast offset and clears FLAG_MCAST.
1004 */
1227
1228 /*
1229 * If running in a broadcast association, the clock offset is
1230 * (t1 - t0) corrected by the one-way delay, but we can't
1231 * measure that directly. Therefore, we start up in MODE_CLIENT
1232 * mode, set FLAG_MCAST and exchange eight messages to determine
1233 * the clock offset. When the last message is sent, we switch to
1234 * MODE_BCLIENT mode. The next broadcast message after that
1235 * computes the broadcast offset and clears FLAG_MCAST.
1236 */
1237 ci = t34;
1005 if (pmode == MODE_BROADCAST) {
1006 if (peer->flags & FLAG_MCAST) {
1007 LFPTOD(&ci, p_offset);
1008 peer->estbdelay = peer->offset - p_offset;
1009 if (peer->hmode == MODE_CLIENT)
1010 return;
1011
1012 peer->flags &= ~FLAG_MCAST;
1013 }
1238 if (pmode == MODE_BROADCAST) {
1239 if (peer->flags & FLAG_MCAST) {
1240 LFPTOD(&ci, p_offset);
1241 peer->estbdelay = peer->offset - p_offset;
1242 if (peer->hmode == MODE_CLIENT)
1243 return;
1244
1245 peer->flags &= ~FLAG_MCAST;
1246 }
1014 DTOLFP(peer->estbdelay, &t10);
1015 L_ADD(&ci, &t10);
1247 DTOLFP(peer->estbdelay, &t34);
1248 L_ADD(&ci, &t34);
1016 p_del = peer->delay;
1017 } else {
1249 p_del = peer->delay;
1250 } else {
1018 L_ADD(&ci, &t23);
1251 L_ADD(&ci, &t21); /* (t2 - t1) + (t3 - t4) */
1019 L_RSHIFT(&ci);
1252 L_RSHIFT(&ci);
1020 L_SUB(&t23, &t10);
1021 LFPTOD(&t23, p_del);
1253 L_SUB(&t21, &t34); /* (t2 - t1) - (t3 - t4) */
1254 LFPTOD(&t21, p_del);
1022 }
1023 p_del = max(p_del, LOGTOD(sys_precision));
1024 LFPTOD(&ci, p_offset);
1025 if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1255 }
1256 p_del = max(p_del, LOGTOD(sys_precision));
1257 LFPTOD(&ci, p_offset);
1258 if ((peer->rootdelay + p_del) / 2. + peer->rootdispersion +
1026 p_disp >= MAXDISPERSE) /* 9 */
1027 peer->flash |= TEST9; /* bad peer distance */
1259 p_disp >= MAXDISPERSE) /* test 9 */
1260 peer->flash |= TEST9; /* bad root distance */
1028
1029 /*
1030 * If any flasher bits remain set at this point, abandon ship.
1031 * Otherwise, forward to the clock filter.
1032 */
1033 if (peer->flash) {
1034#ifdef DEBUG
1035 if (debug)

--- 16 unchanged lines hidden (view full) ---

1052static void
1053clock_update(void)
1054{
1055 u_char oleap;
1056 u_char ostratum;
1057
1058 /*
1059 * Reset/adjust the system clock. Do this only if there is a
1261
1262 /*
1263 * If any flasher bits remain set at this point, abandon ship.
1264 * Otherwise, forward to the clock filter.
1265 */
1266 if (peer->flash) {
1267#ifdef DEBUG
1268 if (debug)

--- 16 unchanged lines hidden (view full) ---

1285static void
1286clock_update(void)
1287{
1288 u_char oleap;
1289 u_char ostratum;
1290
1291 /*
1292 * Reset/adjust the system clock. Do this only if there is a
1060 * system peer and we haven't seen that peer lately. Watch for
1061 * timewarps here.
1293 * system peer and the peer epoch is not older than the last
1294 * update.
1062 */
1063 if (sys_peer == NULL)
1064 return;
1295 */
1296 if (sys_peer == NULL)
1297 return;
1065 if (sys_peer->pollsw == FALSE || sys_peer->burst > 0)
1298 if (sys_peer->epoch <= last_time)
1066 return;
1299 return;
1067 sys_peer->pollsw = FALSE;
1068#ifdef DEBUG
1069 if (debug)
1070 printf("clock_update: at %ld assoc %d \n", current_time,
1071 peer_associations);
1072#endif
1073 oleap = sys_leap;
1074 ostratum = sys_stratum;
1075 switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1076
1077 /*
1078 * Clock is too screwed up. Just exit for now.
1079 */
1080 case -1:
1300#ifdef DEBUG
1301 if (debug)
1302 printf("clock_update: at %ld assoc %d \n", current_time,
1303 peer_associations);
1304#endif
1305 oleap = sys_leap;
1306 ostratum = sys_stratum;
1307 switch (local_clock(sys_peer, sys_offset, sys_syserr)) {
1308
1309 /*
1310 * Clock is too screwed up. Just exit for now.
1311 */
1312 case -1:
1081 report_event(EVNT_SYSFAULT, (struct peer *)0);
1082 exit(1);
1313 report_event(EVNT_SYSFAULT, NULL);
1314 exit (-1);
1083 /*NOTREACHED*/
1084
1085 /*
1086 * Clock was stepped. Flush all time values of all peers.
1087 */
1088 case 1:
1089 clear_all();
1090 sys_peer = NULL;
1091 sys_stratum = STRATUM_UNSPEC;
1315 /*NOTREACHED*/
1316
1317 /*
1318 * Clock was stepped. Flush all time values of all peers.
1319 */
1320 case 1:
1321 clear_all();
1322 sys_peer = NULL;
1323 sys_stratum = STRATUM_UNSPEC;
1324 memcpy(&sys_refid, "STEP", 4);
1092 sys_poll = NTP_MINPOLL;
1325 sys_poll = NTP_MINPOLL;
1093 NLOG(NLOG_SYNCSTATUS)
1094 msyslog(LOG_INFO, "synchronisation lost");
1095 report_event(EVNT_CLOCKRESET, (struct peer *)0);
1326 report_event(EVNT_CLOCKRESET, NULL);
1327#ifdef OPENSSL
1328 if (oleap != LEAP_NOTINSYNC)
1329 expire_all();
1330#endif /* OPENSSL */
1096 break;
1097
1098 /*
1099 * Update the system stratum, leap bits, root delay, root
1100 * dispersion, reference ID and reference time. We also update
1101 * select dispersion and max frequency error. If the leap
1102 * changes, we gotta reroll the keys.
1103 */
1104 default:
1331 break;
1332
1333 /*
1334 * Update the system stratum, leap bits, root delay, root
1335 * dispersion, reference ID and reference time. We also update
1336 * select dispersion and max frequency error. If the leap
1337 * changes, we gotta reroll the keys.
1338 */
1339 default:
1105 sys_stratum = sys_peer->stratum + 1;
1106 if (sys_stratum == 1)
1340 sys_stratum = (u_char) (sys_peer->stratum + 1);
1341 if (sys_stratum == 1 || sys_stratum == STRATUM_UNSPEC)
1107 sys_refid = sys_peer->refid;
1108 else
1342 sys_refid = sys_peer->refid;
1343 else
1109 sys_refid = sys_peer->srcadr.sin_addr.s_addr;
1344 sys_refid = sys_peer_refid;
1110 sys_reftime = sys_peer->rec;
1111 sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1112 sys_leap = leap_consensus;
1345 sys_reftime = sys_peer->rec;
1346 sys_rootdelay = sys_peer->rootdelay + sys_peer->delay;
1347 sys_leap = leap_consensus;
1348 if (oleap == LEAP_NOTINSYNC) {
1349 report_event(EVNT_SYNCCHG, NULL);
1350#ifdef OPENSSL
1351 expire_all();
1352#endif /* OPENSSL */
1353 }
1113 }
1354 }
1114 if (oleap == LEAP_NOTINSYNC) {
1115 report_event(EVNT_SYNCCHG, (struct peer *)0);
1116#ifdef AUTOKEY
1117 expire_all();
1118#endif /* AUTOKEY */
1119 }
1120 if (ostratum != sys_stratum)
1355 if (ostratum != sys_stratum)
1121 report_event(EVNT_PEERSTCHG, (struct peer *)0);
1356 report_event(EVNT_PEERSTCHG, NULL);
1122}
1123
1124
1125/*
1126 * poll_update - update peer poll interval
1127 */
1128void
1129poll_update(
1130 struct peer *peer,
1357}
1358
1359
1360/*
1361 * poll_update - update peer poll interval
1362 */
1363void
1364poll_update(
1365 struct peer *peer,
1131 int hpoll
1366 int hpoll
1132 )
1133{
1367 )
1368{
1134#ifdef AUTOKEY
1135 int oldpoll;
1136#endif /* AUTOKEY */
1369#ifdef OPENSSL
1370 int oldpoll;
1371#endif /* OPENSSL */
1137
1138 /*
1139 * A little foxtrot to determine what controls the poll
1140 * interval. If the peer is reachable, but the last four polls
1141 * have not been answered, use the minimum. If declared
1142 * truechimer, use the system poll interval. This allows each
1143 * association to ramp up the poll interval for useless sources
1144 * and to clamp it to the minimum when first starting up.
1145 */
1372
1373 /*
1374 * A little foxtrot to determine what controls the poll
1375 * interval. If the peer is reachable, but the last four polls
1376 * have not been answered, use the minimum. If declared
1377 * truechimer, use the system poll interval. This allows each
1378 * association to ramp up the poll interval for useless sources
1379 * and to clamp it to the minimum when first starting up.
1380 */
1146#ifdef AUTOKEY
1381#ifdef OPENSSL
1147 oldpoll = peer->kpoll;
1382 oldpoll = peer->kpoll;
1148#endif /* AUTOKEY */
1149 if (hpoll > peer->maxpoll)
1150 peer->hpoll = peer->maxpoll;
1151 else if (hpoll < peer->minpoll)
1152 peer->hpoll = peer->minpoll;
1153 else
1154 peer->hpoll = hpoll;
1383#endif /* OPENSSL */
1384 if (hpoll > 0) {
1385 if (hpoll > peer->maxpoll)
1386 peer->hpoll = peer->maxpoll;
1387 else if (hpoll < peer->minpoll)
1388 peer->hpoll = peer->minpoll;
1389 else
1390 peer->hpoll = (u_char)hpoll;
1391 }
1155
1156 /*
1392
1393 /*
1157 * Bit of adventure here. If during a burst and not timeout,
1158 * just slink away. If timeout, figure what the next timeout
1159 * should be. If IBURST or a reference clock, use one second. If
1160 * not and the dude was reachable during the previous poll
1161 * interval, randomize over 1-4 seconds; otherwise, randomize
1162 * over 15-18 seconds. This is to give time for a modem to
1163 * complete the call, for example. If not during a burst,
1164 * randomize over the poll interval -1 to +2 seconds.
1394 * Bit of adventure here. If during a burst and not a poll, just
1395 * slink away. If a poll, figure what the next poll should be.
1396 * If a burst is pending and a reference clock or a pending
1397 * crypto response, delay for one second. If the first sent in a
1398 * burst, delay ten seconds for the modem to come up. For others
1399 * in the burst, delay two seconds.
1165 *
1166 * In case of manycast server, make the poll interval, which is
1167 * axtually the manycast beacon interval, eight times the system
1168 * poll interval. Normally when the host poll interval settles
1400 *
1401 * In case of manycast server, make the poll interval, which is
1402 * axtually the manycast beacon interval, eight times the system
1403 * poll interval. Normally when the host poll interval settles
1169 * up to 17.1 s, the beacon interval settles up to 2.3 hours.
1404 * up to 1024 s, the beacon interval settles up to 2.3 hours.
1170 */
1405 */
1406#ifdef OPENSSL
1407 if (peer->cmmd != NULL && (sys_leap != LEAP_NOTINSYNC ||
1408 peer->crypto)) {
1409 peer->nextdate = current_time + RESP_DELAY;
1410 } else if (peer->burst > 0) {
1411#else /* OPENSSL */
1171 if (peer->burst > 0) {
1412 if (peer->burst > 0) {
1172 if (peer->nextdate != current_time)
1413#endif /* OPENSSL */
1414 if (hpoll == 0 && peer->nextdate != current_time)
1173 return;
1174#ifdef REFCLOCK
1175 else if (peer->flags & FLAG_REFCLOCK)
1415 return;
1416#ifdef REFCLOCK
1417 else if (peer->flags & FLAG_REFCLOCK)
1176 peer->nextdate++;
1418 peer->nextdate += RESP_DELAY;
1177#endif
1419#endif
1178 else if (peer->reach & 0x1)
1179 peer->nextdate += RANDPOLL(BURST_INTERVAL2);
1420 else if (peer->flags & (FLAG_IBURST | FLAG_BURST) &&
1421 peer->burst == NTP_BURST)
1422 peer->nextdate += sys_calldelay;
1180 else
1423 else
1181 peer->nextdate += RANDPOLL(BURST_INTERVAL1);
1424 peer->nextdate += BURST_DELAY;
1182 } else if (peer->cast_flags & MDF_ACAST) {
1425 } else if (peer->cast_flags & MDF_ACAST) {
1183 if (sys_survivors < NTP_MINCLOCK)
1184 peer->kpoll = peer->hpoll;
1426 if (sys_survivors >= sys_minclock || peer->ttl >=
1427 sys_ttlmax)
1428 peer->kpoll = (u_char) (peer->hpoll + 3);
1185 else
1429 else
1186 peer->kpoll = peer->hpoll + 3;
1430 peer->kpoll = peer->hpoll;
1187 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1188 } else {
1431 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1432 } else {
1189 peer->kpoll = max(min(peer->ppoll, peer->hpoll),
1190 peer->minpoll);
1433 peer->kpoll = (u_char) max(min(peer->ppoll,
1434 peer->hpoll), peer->minpoll);
1191 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1192 }
1193 if (peer->nextdate < current_time)
1194 peer->nextdate = current_time;
1435 peer->nextdate = peer->outdate + RANDPOLL(peer->kpoll);
1436 }
1437 if (peer->nextdate < current_time)
1438 peer->nextdate = current_time;
1195#ifdef AUTOKEY
1439#ifdef OPENSSL
1196 /*
1197 * Bit of crass arrogance at this point. If the poll interval
1198 * has changed and we have a keylist, the lifetimes in the
1199 * keylist are probably bogus. In this case purge the keylist
1200 * and regenerate it later.
1201 */
1202 if (peer->kpoll != oldpoll)
1203 key_expire(peer);
1440 /*
1441 * Bit of crass arrogance at this point. If the poll interval
1442 * has changed and we have a keylist, the lifetimes in the
1443 * keylist are probably bogus. In this case purge the keylist
1444 * and regenerate it later.
1445 */
1446 if (peer->kpoll != oldpoll)
1447 key_expire(peer);
1204#endif /* AUTOKEY */
1448#endif /* OPENSSL */
1205#ifdef DEBUG
1206 if (debug > 1)
1207 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1208 current_time, ntoa(&peer->srcadr), peer->flags,
1209 peer->kpoll, peer->burst, peer->outdate,
1210 peer->nextdate);
1211#endif
1212}
1213
1214
1215/*
1216 * clear - clear peer filter registers. See Section 3.4.8 of the spec.
1217 */
1218void
1219peer_clear(
1449#ifdef DEBUG
1450 if (debug > 1)
1451 printf("poll_update: at %lu %s flags %04x poll %d burst %d last %lu next %lu\n",
1452 current_time, ntoa(&peer->srcadr), peer->flags,
1453 peer->kpoll, peer->burst, peer->outdate,
1454 peer->nextdate);
1455#endif
1456}
1457
1458
1459/*
1460 * clear - clear peer filter registers. See Section 3.4.8 of the spec.
1461 */
1462void
1463peer_clear(
1220 register struct peer *peer
1464 struct peer *peer, /* peer structure */
1465 char *ident /* tally lights */
1221 )
1222{
1466 )
1467{
1223 register int i;
1224 u_long u_rand;
1468 u_char oreach, i;
1225
1226 /*
1227 * If cryptographic credentials have been acquired, toss them to
1228 * Valhalla. Note that autokeys are ephemeral, in that they are
1229 * tossed immediately upon use. Therefore, the keylist can be
1230 * purged anytime without needing to preserve random keys. Note
1231 * that, if the peer is purged, the cryptographic variables are
1232 * purged, too. This makes it much harder to sneak in some
1233 * unauthenticated data in the clock filter.
1234 */
1469
1470 /*
1471 * If cryptographic credentials have been acquired, toss them to
1472 * Valhalla. Note that autokeys are ephemeral, in that they are
1473 * tossed immediately upon use. Therefore, the keylist can be
1474 * purged anytime without needing to preserve random keys. Note
1475 * that, if the peer is purged, the cryptographic variables are
1476 * purged, too. This makes it much harder to sneak in some
1477 * unauthenticated data in the clock filter.
1478 */
1235#ifdef DEBUG
1236 if (debug)
1237 printf("peer_clear: at %ld assoc ID %d\n", current_time,
1238 peer->associd);
1239#endif
1240#ifdef AUTOKEY
1479 oreach = peer->reach;
1480#ifdef OPENSSL
1241 key_expire(peer);
1481 key_expire(peer);
1242#ifdef PUBKEY
1243 if (peer->keystr != NULL)
1244 free(peer->keystr);
1245 if (peer->pubkey.ptr != NULL)
1246 free(peer->pubkey.ptr);
1247 if (peer->certif.ptr != NULL)
1248 free(peer->certif.ptr);
1249#endif /* PUBKEY */
1250#endif /* AUTOKEY */
1251 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1482 if (peer->pkey != NULL)
1483 EVP_PKEY_free(peer->pkey);
1484 if (peer->ident_pkey != NULL)
1485 EVP_PKEY_free(peer->ident_pkey);
1486 if (peer->subject != NULL)
1487 free(peer->subject);
1488 if (peer->issuer != NULL)
1489 free(peer->issuer);
1490 if (peer->iffval != NULL)
1491 BN_free(peer->iffval);
1492 if (peer->grpkey != NULL)
1493 BN_free(peer->grpkey);
1494 if (peer->cmmd != NULL)
1495 free(peer->cmmd);
1496 value_free(&peer->cookval);
1497 value_free(&peer->recval);
1498 value_free(&peer->tai_leap);
1499 value_free(&peer->encrypt);
1500 value_free(&peer->sndval);
1501#endif /* OPENSSL */
1252
1253 /*
1502
1503 /*
1254 * If he dies as a broadcast client, he comes back to life as
1255 * a broadcast client in client mode in order to recover the
1256 * initial autokey values. Note that there is no need to call
1257 * clock_select(), since the perp has already been voted off
1258 * the island at this point.
1504 * Wipe the association clean and initialize the nonzero values.
1259 */
1505 */
1260 if (peer->cast_flags & MDF_BCLNT) {
1261 peer->flags |= FLAG_MCAST;
1262 peer->hmode = MODE_CLIENT;
1263 }
1264 peer->flags &= ~(FLAG_AUTOKEY | FLAG_ASSOC);
1506 memset(CLEAR_TO_ZERO(peer), 0, LEN_CLEAR_TO_ZERO);
1507 if (peer == sys_peer)
1508 sys_peer = NULL;
1265 peer->estbdelay = sys_bdelay;
1266 peer->hpoll = peer->kpoll = peer->minpoll;
1267 peer->ppoll = peer->maxpoll;
1509 peer->estbdelay = sys_bdelay;
1510 peer->hpoll = peer->kpoll = peer->minpoll;
1511 peer->ppoll = peer->maxpoll;
1268 peer->pollsw = FALSE;
1269 peer->jitter = MAXDISPERSE;
1270 peer->epoch = current_time;
1271#ifdef REFCLOCK
1272 if (!(peer->flags & FLAG_REFCLOCK)) {
1273 peer->leap = LEAP_NOTINSYNC;
1274 peer->stratum = STRATUM_UNSPEC;
1512 peer->jitter = MAXDISPERSE;
1513 peer->epoch = current_time;
1514#ifdef REFCLOCK
1515 if (!(peer->flags & FLAG_REFCLOCK)) {
1516 peer->leap = LEAP_NOTINSYNC;
1517 peer->stratum = STRATUM_UNSPEC;
1518 memcpy(&peer->refid, ident, 4);
1275 }
1519 }
1520#else
1521 peer->leap = LEAP_NOTINSYNC;
1522 peer->stratum = STRATUM_UNSPEC;
1523 memcpy(&peer->refid, ident, 4);
1276#endif
1277 for (i = 0; i < NTP_SHIFT; i++) {
1278 peer->filter_order[i] = i;
1279 peer->filter_disp[i] = MAXDISPERSE;
1280 peer->filter_epoch[i] = current_time;
1281 }
1282
1283 /*
1524#endif
1525 for (i = 0; i < NTP_SHIFT; i++) {
1526 peer->filter_order[i] = i;
1527 peer->filter_disp[i] = MAXDISPERSE;
1528 peer->filter_epoch[i] = current_time;
1529 }
1530
1531 /*
1284 * Randomize the first poll over 1-16s to avoid bunching.
1532 * If he dies as a broadcast client, he comes back to life as
1533 * a broadcast client in client mode in order to recover the
1534 * initial autokey values.
1285 */
1535 */
1286 peer->update = peer->outdate = current_time;
1287 u_rand = RANDOM;
1288 peer->nextdate = current_time + (u_rand & ((1 <<
1289 BURST_INTERVAL1) - 1)) + 1;
1536 if (peer->cast_flags & MDF_BCLNT) {
1537 peer->flags |= FLAG_MCAST;
1538 peer->hmode = MODE_CLIENT;
1539 }
1540
1541 /*
1542 * Randomize the first poll to avoid bunching, but only if the
1543 * rascal has never been heard. During initialization use the
1544 * association count to spread out the polls at one-second
1545 * intervals.
1546 */
1547 peer->nextdate = peer->update = peer->outdate = current_time;
1548 peer->burst = 0;
1549 if (oreach)
1550 poll_update(peer, 0);
1551 else if (initializing)
1552 peer->nextdate = current_time + peer_associations;
1553 else
1554 peer->nextdate = current_time + (u_int)RANDOM %
1555 peer_associations;
1556#ifdef DEBUG
1557 if (debug)
1558 printf("peer_clear: at %ld assoc ID %d refid %s\n",
1559 current_time, peer->associd, ident);
1560#endif
1290}
1291
1292
1293/*
1294 * clock_filter - add incoming clock sample to filter register and run
1295 * the filter procedure to find the best sample.
1296 */
1297void
1298clock_filter(
1561}
1562
1563
1564/*
1565 * clock_filter - add incoming clock sample to filter register and run
1566 * the filter procedure to find the best sample.
1567 */
1568void
1569clock_filter(
1299 register struct peer *peer, /* peer structure pointer */
1300 double sample_offset, /* clock offset */
1301 double sample_delay, /* roundtrip delay */
1302 double sample_disp /* dispersion */
1570 struct peer *peer, /* peer structure pointer */
1571 double sample_offset, /* clock offset */
1572 double sample_delay, /* roundtrip delay */
1573 double sample_disp /* dispersion */
1303 )
1304{
1574 )
1575{
1305 double dst[NTP_SHIFT]; /* distance vector */
1306 int ord[NTP_SHIFT]; /* index vector */
1307 register int i, j, k, m;
1308 double dsp, jit, dtemp, etemp;
1576 double dst[NTP_SHIFT]; /* distance vector */
1577 int ord[NTP_SHIFT]; /* index vector */
1578 int i, j, k, m;
1579 double dsp, jit, dtemp, etemp;
1309
1310 /*
1311 * Shift the new sample into the register and discard the oldest
1312 * one. The new offset and delay come directly from the
1313 * timestamp calculations. The dispersion grows from the last
1314 * outbound packet or reference clock update to the present time
1315 * and increased by the sum of the peer precision and the system
1316 * precision. The delay can sometimes swing negative due to
1317 * frequency skew, so it is clamped non-negative.
1318 */
1319 dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1320 sample_disp, MAXDISPERSE);
1321 j = peer->filter_nextpt;
1322 peer->filter_offset[j] = sample_offset;
1323 peer->filter_delay[j] = max(0, sample_delay);
1324 peer->filter_disp[j] = dsp;
1580
1581 /*
1582 * Shift the new sample into the register and discard the oldest
1583 * one. The new offset and delay come directly from the
1584 * timestamp calculations. The dispersion grows from the last
1585 * outbound packet or reference clock update to the present time
1586 * and increased by the sum of the peer precision and the system
1587 * precision. The delay can sometimes swing negative due to
1588 * frequency skew, so it is clamped non-negative.
1589 */
1590 dsp = min(LOGTOD(peer->precision) + LOGTOD(sys_precision) +
1591 sample_disp, MAXDISPERSE);
1592 j = peer->filter_nextpt;
1593 peer->filter_offset[j] = sample_offset;
1594 peer->filter_delay[j] = max(0, sample_delay);
1595 peer->filter_disp[j] = dsp;
1325 peer->filter_epoch[j] = current_time;
1326 j++; j %=NTP_SHIFT;
1327 peer->filter_nextpt = j;
1596 j++; j %= NTP_SHIFT;
1597 peer->filter_nextpt = (u_short) j;
1328
1329 /*
1330 * Update dispersions since the last update and at the same
1331 * time initialize the distance and index lists. The distance
1332 * list uses a compound metric. If the sample is valid and
1333 * younger than the minimum Allan intercept, use delay;
1334 * otherwise, use biased dispersion.
1335 */
1336 dtemp = clock_phi * (current_time - peer->update);
1337 peer->update = current_time;
1338 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1598
1599 /*
1600 * Update dispersions since the last update and at the same
1601 * time initialize the distance and index lists. The distance
1602 * list uses a compound metric. If the sample is valid and
1603 * younger than the minimum Allan intercept, use delay;
1604 * otherwise, use biased dispersion.
1605 */
1606 dtemp = clock_phi * (current_time - peer->update);
1607 peer->update = current_time;
1608 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1339 if (i != 0) {
1609 if (i != 0)
1340 peer->filter_disp[j] += dtemp;
1610 peer->filter_disp[j] += dtemp;
1341 if (peer->filter_disp[j] > MAXDISPERSE)
1342 peer->filter_disp[j] = MAXDISPERSE;
1343 }
1611 if (peer->filter_disp[j] >= MAXDISPERSE)
1612 peer->filter_disp[j] = MAXDISPERSE;
1344 if (peer->filter_disp[j] >= MAXDISPERSE)
1345 dst[i] = MAXDISPERSE;
1346 else if (peer->update - peer->filter_epoch[j] >
1347 allan_xpt)
1348 dst[i] = MAXDISTANCE + peer->filter_disp[j];
1349 else
1613 if (peer->filter_disp[j] >= MAXDISPERSE)
1614 dst[i] = MAXDISPERSE;
1615 else if (peer->update - peer->filter_epoch[j] >
1616 allan_xpt)
1617 dst[i] = MAXDISTANCE + peer->filter_disp[j];
1618 else
1350 dst[i] = peer->filter_delay[j];
1619 dst[i] = peer->filter_delay[j];
1351 ord[i] = j;
1352 j++; j %= NTP_SHIFT;
1353 }
1620 ord[i] = j;
1621 j++; j %= NTP_SHIFT;
1622 }
1623 peer->filter_epoch[j] = current_time;
1354
1355 /*
1356 * Sort the samples in both lists by distance.
1357 */
1358 for (i = 1; i < NTP_SHIFT; i++) {
1359 for (j = 0; j < i; j++) {
1360 if (dst[j] > dst[i]) {
1361 k = ord[j];

--- 9 unchanged lines hidden (view full) ---

1371 /*
1372 * Copy the index list to the association structure so ntpq
1373 * can see it later. Prune the distance list to samples less
1374 * than MAXDISTANCE, but keep at least two valid samples for
1375 * jitter calculation.
1376 */
1377 m = 0;
1378 for (i = 0; i < NTP_SHIFT; i++) {
1624
1625 /*
1626 * Sort the samples in both lists by distance.
1627 */
1628 for (i = 1; i < NTP_SHIFT; i++) {
1629 for (j = 0; j < i; j++) {
1630 if (dst[j] > dst[i]) {
1631 k = ord[j];

--- 9 unchanged lines hidden (view full) ---

1641 /*
1642 * Copy the index list to the association structure so ntpq
1643 * can see it later. Prune the distance list to samples less
1644 * than MAXDISTANCE, but keep at least two valid samples for
1645 * jitter calculation.
1646 */
1647 m = 0;
1648 for (i = 0; i < NTP_SHIFT; i++) {
1379 peer->filter_order[i] = ord[i];
1649 peer->filter_order[i] = (u_char) ord[i];
1380 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1381 MAXDISTANCE))
1382 continue;
1383 m++;
1384 }
1385
1386 /*
1387 * Compute the dispersion and jitter squares. The dispersion
1388 * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1389 * normalized close to 1.0. The jitter is the mean of the square
1390 * differences relative to the lowest delay sample. If no
1391 * acceptable samples remain in the shift register, quietly
1650 if (dst[i] >= MAXDISPERSE || (m >= 2 && dst[i] >=
1651 MAXDISTANCE))
1652 continue;
1653 m++;
1654 }
1655
1656 /*
1657 * Compute the dispersion and jitter squares. The dispersion
1658 * is weighted exponentially by NTP_FWEIGHT (0.5) so it is
1659 * normalized close to 1.0. The jitter is the mean of the square
1660 * differences relative to the lowest delay sample. If no
1661 * acceptable samples remain in the shift register, quietly
1392 * tiptoe home leaving only the
1393 * dispersion.
1662 * tiptoe home leaving only the dispersion.
1394 */
1395 jit = 0;
1396 peer->disp = 0;
1397 k = ord[0];
1398 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1399
1400 j = ord[i];
1401 peer->disp = NTP_FWEIGHT * (peer->disp +

--- 6 unchanged lines hidden (view full) ---

1408 /*
1409 * If no acceptable samples remain in the shift register,
1410 * quietly tiptoe home leaving only the dispersion. Otherwise,
1411 * save the offset, delay and jitter average. Note the jitter
1412 * must not be less than the system precision.
1413 */
1414 if (m == 0)
1415 return;
1663 */
1664 jit = 0;
1665 peer->disp = 0;
1666 k = ord[0];
1667 for (i = NTP_SHIFT - 1; i >= 0; i--) {
1668
1669 j = ord[i];
1670 peer->disp = NTP_FWEIGHT * (peer->disp +

--- 6 unchanged lines hidden (view full) ---

1677 /*
1678 * If no acceptable samples remain in the shift register,
1679 * quietly tiptoe home leaving only the dispersion. Otherwise,
1680 * save the offset, delay and jitter average. Note the jitter
1681 * must not be less than the system precision.
1682 */
1683 if (m == 0)
1684 return;
1416 etemp = peer->offset;
1685 etemp = fabs(peer->offset - peer->filter_offset[k]);
1686 dtemp = sqrt(peer->jitter);
1417 peer->offset = peer->filter_offset[k];
1418 peer->delay = peer->filter_delay[k];
1419 if (m > 1)
1420 jit /= m - 1;
1421 peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1422
1423 /*
1424 * A new sample is useful only if it is younger than the last
1687 peer->offset = peer->filter_offset[k];
1688 peer->delay = peer->filter_delay[k];
1689 if (m > 1)
1690 jit /= m - 1;
1691 peer->jitter = max(jit, SQUARE(LOGTOD(sys_precision)));
1692
1693 /*
1694 * A new sample is useful only if it is younger than the last
1425 * one used.
1695 * one used, but only if the sucker has been synchronized.
1426 */
1696 */
1427 if (peer->filter_epoch[k] <= peer->epoch) {
1697 if (peer->filter_epoch[k] <= peer->epoch && sys_leap !=
1698 LEAP_NOTINSYNC) {
1428#ifdef DEBUG
1429 if (debug)
1430 printf("clock_filter: discard %lu\n",
1431 peer->epoch - peer->filter_epoch[k]);
1432#endif
1433 return;
1434 }
1435
1436 /*
1437 * If the difference between the last offset and the current one
1699#ifdef DEBUG
1700 if (debug)
1701 printf("clock_filter: discard %lu\n",
1702 peer->epoch - peer->filter_epoch[k]);
1703#endif
1704 return;
1705 }
1706
1707 /*
1708 * If the difference between the last offset and the current one
1438 * exceeds the jitter by CLOCK_SGATE (4) and the interval since
1439 * the last update is less than twice the system poll interval,
1709 * exceeds the jitter by CLOCK_SGATE and the interval since the
1710 * last update is less than twice the system poll interval,
1440 * consider the update a popcorn spike and ignore it.
1441 */
1711 * consider the update a popcorn spike and ignore it.
1712 */
1442 if (m > 1 && fabs(peer->offset - etemp) > SQRT(peer->jitter) *
1443 CLOCK_SGATE && peer->filter_epoch[k] - peer->epoch <
1444 (1 << (sys_poll + 1))) {
1713 if (m > 1 && etemp > CLOCK_SGATE * dtemp &&
1714 (long)(peer->filter_epoch[k] - peer->epoch) < (1 << (sys_poll +
1715 1))) {
1445#ifdef DEBUG
1446 if (debug)
1716#ifdef DEBUG
1717 if (debug)
1447 printf("clock_filter: n %d popcorn spike %.6f jitter %.6f\n",
1448 m, peer->offset, SQRT(peer->jitter));
1718 printf("clock_filter: popcorn %.6f %.6f\n",
1719 etemp, dtemp);
1449#endif
1450 return;
1451 }
1452
1453 /*
1454 * The mitigated sample statistics are saved for later
1720#endif
1721 return;
1722 }
1723
1724 /*
1725 * The mitigated sample statistics are saved for later
1455 * processing, but can be processed only once.
1726 * processing.
1456 */
1457 peer->epoch = peer->filter_epoch[k];
1727 */
1728 peer->epoch = peer->filter_epoch[k];
1458 peer->pollsw = TRUE;
1459#ifdef DEBUG
1460 if (debug)
1461 printf(
1462 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1463 m, peer->offset, peer->delay, peer->disp,
1464 SQRT(peer->jitter), peer->update - peer->epoch);
1465#endif
1466}
1467
1468
1469/*
1470 * clock_select - find the pick-of-the-litter clock
1729#ifdef DEBUG
1730 if (debug)
1731 printf(
1732 "clock_filter: n %d off %.6f del %.6f dsp %.6f jit %.6f, age %lu\n",
1733 m, peer->offset, peer->delay, peer->disp,
1734 SQRT(peer->jitter), peer->update - peer->epoch);
1735#endif
1736}
1737
1738
1739/*
1740 * clock_select - find the pick-of-the-litter clock
1741 *
1742 * LOCKCLOCK: If the local clock is the prefer peer, it will always be
1743 * enabled, even if declared falseticker, (2) only the prefer peer can
1744 * be selected as the system peer, (3) if the external source is down,
1745 * the system leap bits are set to 11 and the stratum set to infinity.
1471 */
1472void
1473clock_select(void)
1474{
1746 */
1747void
1748clock_select(void)
1749{
1475 register struct peer *peer;
1476 int i, j, k, n;
1477 int nreach, nlist, nl3;
1478 double d, e, f;
1479 int allow, found, sw;
1480 double high, low;
1481 double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1750 struct peer *peer;
1751 int i, j, k, n;
1752 int nlist, nl3;
1753
1754 double d, e, f;
1755 int allow, sw, osurv;
1756 double high, low;
1757 double synch[NTP_MAXCLOCK], error[NTP_MAXCLOCK];
1482 struct peer *osys_peer;
1483 struct peer *typeacts = NULL;
1484 struct peer *typelocal = NULL;
1485 struct peer *typepps = NULL;
1486 struct peer *typesystem = NULL;
1487
1488 static int list_alloc = 0;
1489 static struct endpoint *endpoint = NULL;

--- 4 unchanged lines hidden (view full) ---

1494 static u_int peer_list_size = 0;
1495
1496 /*
1497 * Initialize and create endpoint, index and peer lists big
1498 * enough to handle all associations.
1499 */
1500 osys_peer = sys_peer;
1501 sys_peer = NULL;
1758 struct peer *osys_peer;
1759 struct peer *typeacts = NULL;
1760 struct peer *typelocal = NULL;
1761 struct peer *typepps = NULL;
1762 struct peer *typesystem = NULL;
1763
1764 static int list_alloc = 0;
1765 static struct endpoint *endpoint = NULL;

--- 4 unchanged lines hidden (view full) ---

1770 static u_int peer_list_size = 0;
1771
1772 /*
1773 * Initialize and create endpoint, index and peer lists big
1774 * enough to handle all associations.
1775 */
1776 osys_peer = sys_peer;
1777 sys_peer = NULL;
1778 osurv = sys_survivors;
1779 sys_survivors = 0;
1502 sys_prefer = NULL;
1780 sys_prefer = NULL;
1503 nreach = nlist = 0;
1504 low = 1e9;
1505 high = -1e9;
1781#ifdef LOCKCLOCK
1782 sys_leap = LEAP_NOTINSYNC;
1783 sys_stratum = STRATUM_UNSPEC;
1784 memcpy(&sys_refid, "DOWN", 4);
1785#endif /* LOCKCLOCK */
1786 nlist = 0;
1506 for (n = 0; n < HASH_SIZE; n++)
1507 nlist += peer_hash_count[n];
1508 if (nlist > list_alloc) {
1509 if (list_alloc > 0) {
1510 free(endpoint);
1511 free(indx);
1512 free(peer_list);
1513 }
1514 while (list_alloc < nlist) {
1515 list_alloc += 5;
1516 endpoint_size += 5 * 3 * sizeof(*endpoint);
1517 indx_size += 5 * 3 * sizeof(*indx);
1518 peer_list_size += 5 * sizeof(*peer_list);
1519 }
1787 for (n = 0; n < HASH_SIZE; n++)
1788 nlist += peer_hash_count[n];
1789 if (nlist > list_alloc) {
1790 if (list_alloc > 0) {
1791 free(endpoint);
1792 free(indx);
1793 free(peer_list);
1794 }
1795 while (list_alloc < nlist) {
1796 list_alloc += 5;
1797 endpoint_size += 5 * 3 * sizeof(*endpoint);
1798 indx_size += 5 * 3 * sizeof(*indx);
1799 peer_list_size += 5 * sizeof(*peer_list);
1800 }
1520 endpoint = (struct endpoint *)emalloc(endpoint_size);
1521 indx = (int *)emalloc(indx_size);
1522 peer_list = (struct peer **)emalloc(peer_list_size);
1801 endpoint = emalloc(endpoint_size);
1802 indx = emalloc(indx_size);
1803 peer_list = emalloc(peer_list_size);
1523 }
1524
1525 /*
1526 * Initially, we populate the island with all the rifraff peers
1527 * that happen to be lying around. Those with seriously
1528 * defective clocks are immediately booted off the island. Then,
1529 * the falsetickers are culled and put to sea. The truechimers
1530 * remaining are subject to repeated rounds where the most
1531 * unpopular at each round is kicked off. When the population
1804 }
1805
1806 /*
1807 * Initially, we populate the island with all the rifraff peers
1808 * that happen to be lying around. Those with seriously
1809 * defective clocks are immediately booted off the island. Then,
1810 * the falsetickers are culled and put to sea. The truechimers
1811 * remaining are subject to repeated rounds where the most
1812 * unpopular at each round is kicked off. When the population
1532 * has dwindled to NTP_MINCLOCK (3), the survivors split a
1533 * million bucks and collectively crank the chimes.
1813 * has dwindled to sys_minclock, the survivors split a million
1814 * bucks and collectively crank the chimes.
1534 */
1535 nlist = nl3 = 0; /* none yet */
1536 for (n = 0; n < HASH_SIZE; n++) {
1537 for (peer = peer_hash[n]; peer != NULL; peer =
1538 peer->next) {
1539 peer->flags &= ~FLAG_SYSPEER;
1540 peer->status = CTL_PST_SEL_REJECT;
1541
1542 /*
1815 */
1816 nlist = nl3 = 0; /* none yet */
1817 for (n = 0; n < HASH_SIZE; n++) {
1818 for (peer = peer_hash[n]; peer != NULL; peer =
1819 peer->next) {
1820 peer->flags &= ~FLAG_SYSPEER;
1821 peer->status = CTL_PST_SEL_REJECT;
1822
1823 /*
1543 * A peer leaves the island immediately if
1544 * unreachable, synchronized to us or suffers
1545 * excessive root distance. Careful with the
1546 * root distance, since the poll interval can
1547 * increase to a day and a half.
1548 */
1549 if (!peer->reach || (peer->stratum > 1 &&
1550 peer->refid ==
1551 peer->dstadr->sin.sin_addr.s_addr) ||
1552 peer->stratum >= STRATUM_UNSPEC ||
1553 (root_distance(peer) >= MAXDISTANCE + 2 *
1554 clock_phi * ULOGTOD(sys_poll)))
1824 * Leave the island immediately if the peer is
1825 * unfit to synchronize.
1826 */
1827 if (peer_unfit(peer))
1555 continue;
1556
1557 /*
1558 * Don't allow the local clock or modem drivers
1559 * in the kitchen at this point, unless the
1560 * prefer peer. Do that later, but only if
1561 * nobody else is around. These guys are all
1562 * configured, so we never throw them away.
1563 */
1564 if (peer->refclktype == REFCLK_LOCALCLOCK
1565#if defined(VMS) && defined(VMS_LOCALUNIT)
1828 continue;
1829
1830 /*
1831 * Don't allow the local clock or modem drivers
1832 * in the kitchen at this point, unless the
1833 * prefer peer. Do that later, but only if
1834 * nobody else is around. These guys are all
1835 * configured, so we never throw them away.
1836 */
1837 if (peer->refclktype == REFCLK_LOCALCLOCK
1838#if defined(VMS) && defined(VMS_LOCALUNIT)
1566 /* wjm: local unit VMS_LOCALUNIT taken seriously */
1567 && REFCLOCKUNIT(&peer->srcadr) != VMS_LOCALUNIT
1839 /* wjm: VMS_LOCALUNIT taken seriously */
1840 && REFCLOCKUNIT(&peer->srcadr) !=
1841 VMS_LOCALUNIT
1568#endif /* VMS && VMS_LOCALUNIT */
1569 ) {
1570 typelocal = peer;
1571 if (!(peer->flags & FLAG_PREFER))
1572 continue; /* no local clock */
1842#endif /* VMS && VMS_LOCALUNIT */
1843 ) {
1844 typelocal = peer;
1845 if (!(peer->flags & FLAG_PREFER))
1846 continue; /* no local clock */
1847#ifdef LOCKCLOCK
1848 else
1849 sys_prefer = peer;
1850#endif /* LOCKCLOCK */
1573 }
1574 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1575 typeacts = peer;
1576 if (!(peer->flags & FLAG_PREFER))
1577 continue; /* no acts */
1578 }
1579
1580 /*
1581 * If we get this far, the peer can stay on the
1582 * island, but does not yet have the immunity
1583 * idol.
1584 */
1851 }
1852 if (peer->sstclktype == CTL_SST_TS_TELEPHONE) {
1853 typeacts = peer;
1854 if (!(peer->flags & FLAG_PREFER))
1855 continue; /* no acts */
1856 }
1857
1858 /*
1859 * If we get this far, the peer can stay on the
1860 * island, but does not yet have the immunity
1861 * idol.
1862 */
1585 nreach++;
1586 peer->status = CTL_PST_SEL_SANE;
1587 peer_list[nlist++] = peer;
1588
1589 /*
1590 * Insert each interval endpoint on the sorted
1591 * list.
1592 */
1593 e = peer->offset; /* Upper end */

--- 4 unchanged lines hidden (view full) ---

1598 break;
1599 indx[i + 3] = indx[i];
1600 }
1601 indx[i + 3] = nl3;
1602 endpoint[nl3].type = 1;
1603 endpoint[nl3++].val = e;
1604
1605 e = e - f; /* Center point */
1863 peer->status = CTL_PST_SEL_SANE;
1864 peer_list[nlist++] = peer;
1865
1866 /*
1867 * Insert each interval endpoint on the sorted
1868 * list.
1869 */
1870 e = peer->offset; /* Upper end */

--- 4 unchanged lines hidden (view full) ---

1875 break;
1876 indx[i + 3] = indx[i];
1877 }
1878 indx[i + 3] = nl3;
1879 endpoint[nl3].type = 1;
1880 endpoint[nl3++].val = e;
1881
1882 e = e - f; /* Center point */
1606 for ( ; i >= 0; i--) {
1883 for (; i >= 0; i--) {
1607 if (e >= endpoint[indx[i]].val)
1608 break;
1609 indx[i + 2] = indx[i];
1610 }
1611 indx[i + 2] = nl3;
1612 endpoint[nl3].type = 0;
1613 endpoint[nl3++].val = e;
1614
1615 e = e - f; /* Lower end */
1884 if (e >= endpoint[indx[i]].val)
1885 break;
1886 indx[i + 2] = indx[i];
1887 }
1888 indx[i + 2] = nl3;
1889 endpoint[nl3].type = 0;
1890 endpoint[nl3++].val = e;
1891
1892 e = e - f; /* Lower end */
1616 for ( ; i >= 0; i--) {
1893 for (; i >= 0; i--) {
1617 if (e >= endpoint[indx[i]].val)
1618 break;
1619 indx[i + 1] = indx[i];
1620 }
1621 indx[i + 1] = nl3;
1622 endpoint[nl3].type = -1;
1623 endpoint[nl3++].val = e;
1624 }
1625 }
1626#ifdef DEBUG
1627 if (debug > 2)
1628 for (i = 0; i < nl3; i++)
1629 printf("select: endpoint %2d %.6f\n",
1630 endpoint[indx[i]].type,
1631 endpoint[indx[i]].val);
1632#endif
1894 if (e >= endpoint[indx[i]].val)
1895 break;
1896 indx[i + 1] = indx[i];
1897 }
1898 indx[i + 1] = nl3;
1899 endpoint[nl3].type = -1;
1900 endpoint[nl3++].val = e;
1901 }
1902 }
1903#ifdef DEBUG
1904 if (debug > 2)
1905 for (i = 0; i < nl3; i++)
1906 printf("select: endpoint %2d %.6f\n",
1907 endpoint[indx[i]].type,
1908 endpoint[indx[i]].val);
1909#endif
1633 i = 0;
1634 j = nl3 - 1;
1635 allow = nlist; /* falsetickers assumed */
1636 found = 0;
1637 while (allow > 0) {
1638 allow--;
1639 for (n = 0; i <= j; i++) {
1640 n += endpoint[indx[i]].type;
1641 if (n < 0)
1910 /*
1911 * This is the actual algorithm that cleaves the truechimers
1912 * from the falsetickers. The original algorithm was described
1913 * in Keith Marzullo's dissertation, but has been modified for
1914 * better accuracy.
1915 *
1916 * Briefly put, we first assume there are no falsetickers, then
1917 * scan the candidate list first from the low end upwards and
1918 * then from the high end downwards. The scans stop when the
1919 * number of intersections equals the number of candidates less
1920 * the number of falsetickers. If this doesn't happen for a
1921 * given number of falsetickers, we bump the number of
1922 * falsetickers and try again. If the number of falsetickers
1923 * becomes equal to or greater than half the number of
1924 * candidates, the Albanians have won the Byzantine wars and
1925 * correct synchronization is not possible.
1926 *
1927 * Here, nlist is the number of candidates and allow is the
1928 * number of falsetickers.
1929 */
1930 low = 1e9;
1931 high = -1e9;
1932 for (allow = 0; 2 * allow < nlist; allow++) {
1933 int found;
1934
1935 /*
1936 * Bound the interval (low, high) as the largest
1937 * interval containing points from presumed truechimers.
1938 */
1939 found = 0;
1940 n = 0;
1941 for (i = 0; i < nl3; i++) {
1942 low = endpoint[indx[i]].val;
1943 n -= endpoint[indx[i]].type;
1944 if (n >= nlist - allow)
1642 break;
1643 if (endpoint[indx[i]].type == 0)
1644 found++;
1645 }
1945 break;
1946 if (endpoint[indx[i]].type == 0)
1947 found++;
1948 }
1646 for (n = 0; i <= j; j--) {
1949 n = 0;
1950 for (j = nl3 - 1; j >= 0; j--) {
1951 high = endpoint[indx[j]].val;
1647 n += endpoint[indx[j]].type;
1952 n += endpoint[indx[j]].type;
1648 if (n > 0)
1953 if (n >= nlist - allow)
1649 break;
1650 if (endpoint[indx[j]].type == 0)
1651 found++;
1652 }
1954 break;
1955 if (endpoint[indx[j]].type == 0)
1956 found++;
1957 }
1958
1959 /*
1960 * If the number of candidates found outside the
1961 * interval is greater than the number of falsetickers,
1962 * then at least one truechimer is outside the interval,
1963 * so go around again. This is what makes this algorithm
1964 * different than Marzullo's.
1965 */
1653 if (found > allow)
1966 if (found > allow)
1967 continue;
1968
1969 /*
1970 * If an interval containing truechimers is found, stop.
1971 * If not, increase the number of falsetickers and go
1972 * around again.
1973 */
1974 if (high > low)
1654 break;
1975 break;
1655 low = endpoint[indx[i++]].val;
1656 high = endpoint[indx[j--]].val;
1657 }
1658
1659 /*
1660 * If no survivors remain at this point, check if the local
1661 * clock or modem drivers have been found. If so, nominate one
1976 }
1977
1978 /*
1979 * If no survivors remain at this point, check if the local
1980 * clock or modem drivers have been found. If so, nominate one
1662 * of them as the only survivor. Otherwise, give up and declare
1663 * us unsynchronized.
1981 * of them as the only survivor. Otherwise, give up and leave
1982 * the island to the rats.
1664 */
1983 */
1665 if ((allow << 1) >= nlist) {
1984 if (high <= low) {
1666 if (typeacts != 0) {
1667 typeacts->status = CTL_PST_SEL_SANE;
1668 peer_list[0] = typeacts;
1669 nlist = 1;
1670 } else if (typelocal != 0) {
1671 typelocal->status = CTL_PST_SEL_SANE;
1672 peer_list[0] = typelocal;
1673 nlist = 1;
1674 } else {
1675 if (osys_peer != NULL) {
1676 sys_poll = NTP_MINPOLL;
1677 NLOG(NLOG_SYNCSTATUS)
1678 msyslog(LOG_INFO,
1985 if (typeacts != 0) {
1986 typeacts->status = CTL_PST_SEL_SANE;
1987 peer_list[0] = typeacts;
1988 nlist = 1;
1989 } else if (typelocal != 0) {
1990 typelocal->status = CTL_PST_SEL_SANE;
1991 peer_list[0] = typelocal;
1992 nlist = 1;
1993 } else {
1994 if (osys_peer != NULL) {
1995 sys_poll = NTP_MINPOLL;
1996 NLOG(NLOG_SYNCSTATUS)
1997 msyslog(LOG_INFO,
1679 "synchronisation lost");
1680 report_event(EVNT_PEERSTCHG,
1681 (struct peer *)0);
1998 "no servers reachable");
1999 report_event(EVNT_PEERSTCHG, NULL);
1682 }
2000 }
1683 sys_survivors = 0;
1684#ifdef AUTOKEY
1685 resetmanycast();
1686#endif /* AUTOKEY */
2001 if (osurv > 0)
2002 resetmanycast();
1687 return;
1688 }
1689 }
2003 return;
2004 }
2005 }
1690#ifdef DEBUG
1691 if (debug > 2)
1692 printf("select: low %.6f high %.6f\n", low, high);
1693#endif
1694
1695 /*
2006
2007 /*
2008 * We can only trust the survivors if the number of candidates
2009 * sys_minsane is at least the number required to detect and
2010 * cast out one falsticker. For the Byzantine agreement
2011 * algorithm used here, that number is 4; however, the default
2012 * sys_minsane is 1 to speed initial synchronization. Careful
2013 * operators will tinker the value to 4 and use at least that
2014 * number of synchronization sources.
2015 */
2016 if (nlist < sys_minsane)
2017 return;
2018
2019 /*
1696 * Clustering algorithm. Construct candidate list in order first
2020 * Clustering algorithm. Construct candidate list in order first
1697 * by stratum then by root distance. If we have more than
1698 * MAXCLOCK peers, keep only the best MAXCLOCK of them. Scan the
1699 * list to find falsetickers, who leave the island immediately.
1700 * If a falseticker is not configured, his association raft is
1701 * drowned as well. We must leave at least one peer to collect
1702 * the million bucks.
2021 * by stratum then by root distance, but keep only the best
2022 * NTP_MAXCLOCK of them. Scan the list to find falsetickers, who
2023 * leave the island immediately. If a falseticker is not
2024 * configured, his association raft is drowned as well, but only
2025 * if at at least eight poll intervals have gone. We must leave
2026 * at least one peer to collect the million bucks.
2027 *
2028 * Note the hysteresis gimmick that increases the effective
2029 * distance for those rascals that have not made the final cut.
2030 * This is to discourage clockhopping. Note also the prejudice
2031 * against lower stratum peers if the floor is elevated.
1703 */
1704 j = 0;
1705 for (i = 0; i < nlist; i++) {
1706 peer = peer_list[i];
2032 */
2033 j = 0;
2034 for (i = 0; i < nlist; i++) {
2035 peer = peer_list[i];
1707 if (nlist > 1 && (low >= peer->offset || peer->offset >=
2036 if (nlist > 1 && (peer->offset <= low || peer->offset >=
1708 high)) {
1709 if (!(peer->flags & FLAG_CONFIG))
1710 unpeer(peer);
1711 continue;
1712 }
1713 peer->status = CTL_PST_SEL_DISTSYSPEER;
2037 high)) {
2038 if (!(peer->flags & FLAG_CONFIG))
2039 unpeer(peer);
2040 continue;
2041 }
2042 peer->status = CTL_PST_SEL_DISTSYSPEER;
1714 d = root_distance(peer) + peer->stratum * MAXDISPERSE;
2043 d = peer->stratum;
2044 if (d < sys_floor)
2045 d += sys_floor;
2046 if (d > sys_ceiling)
2047 d = STRATUM_UNSPEC;
2048 d = root_distance(peer) + d * MAXDISTANCE;
2049 d *= 1. - peer->hyst;
1715 if (j >= NTP_MAXCLOCK) {
1716 if (d >= synch[j - 1])
1717 continue;
1718 else
1719 j--;
1720 }
1721 for (k = j; k > 0; k--) {
1722 if (d >= synch[k - 1])
1723 break;
1724 peer_list[k] = peer_list[k - 1];
1725 error[k] = error[k - 1];
1726 synch[k] = synch[k - 1];
1727 }
1728 peer_list[k] = peer;
1729 error[k] = peer->jitter;
1730 synch[k] = d;
1731 j++;
1732 }
1733 nlist = j;
2050 if (j >= NTP_MAXCLOCK) {
2051 if (d >= synch[j - 1])
2052 continue;
2053 else
2054 j--;
2055 }
2056 for (k = j; k > 0; k--) {
2057 if (d >= synch[k - 1])
2058 break;
2059 peer_list[k] = peer_list[k - 1];
2060 error[k] = error[k - 1];
2061 synch[k] = synch[k - 1];
2062 }
2063 peer_list[k] = peer;
2064 error[k] = peer->jitter;
2065 synch[k] = d;
2066 j++;
2067 }
2068 nlist = j;
2069 if (nlist == 0) {
2070#ifdef DEBUG
2071 if (debug)
2072 printf("clock_select: empty intersection interval\n");
2073#endif
2074 return;
2075 }
1734 for (i = 0; i < nlist; i++) {
1735 peer_list[i]->status = CTL_PST_SEL_SELCAND;
1736
1737#ifdef DEBUG
1738 if (debug > 2)
2076 for (i = 0; i < nlist; i++) {
2077 peer_list[i]->status = CTL_PST_SEL_SELCAND;
2078
2079#ifdef DEBUG
2080 if (debug > 2)
1739 printf("select: %s distance %.6f\n",
1740 ntoa(&peer_list[i]->srcadr), synch[i]);
2081 printf("select: %s distance %.6f jitter %.6f\n",
2082 ntoa(&peer_list[i]->srcadr), synch[i],
2083 SQRT(error[i]));
1741#endif
1742 }
1743
1744 /*
1745 * Now, vote outlyers off the island by select jitter weighted
1746 * by root dispersion. Continue voting as long as there are more
2084#endif
2085 }
2086
2087 /*
2088 * Now, vote outlyers off the island by select jitter weighted
2089 * by root dispersion. Continue voting as long as there are more
1747 * than NTP_MINCLOCK survivors and the minimum select jitter
2090 * than sys_minclock survivors and the minimum select jitter
1748 * squared is greater than the maximum peer jitter squared. Stop
1749 * if we are about to discard a prefer peer, who of course has
1750 * the immunity idol.
1751 */
1752 while (1) {
1753 d = 1e9;
1754 e = -1e9;
1755 k = 0;
1756 for (i = 0; i < nlist; i++) {
2091 * squared is greater than the maximum peer jitter squared. Stop
2092 * if we are about to discard a prefer peer, who of course has
2093 * the immunity idol.
2094 */
2095 while (1) {
2096 d = 1e9;
2097 e = -1e9;
2098 k = 0;
2099 for (i = 0; i < nlist; i++) {
1757
1758 if (error[i] < d)
1759 d = error[i];
1760 f = 0;
1761 if (nlist > 1) {
1762 for (j = 0; j < nlist; j++)
1763 f += DIFF(peer_list[j]->offset,
1764 peer_list[i]->offset);
1765 f /= nlist - 1;
1766 }
2100 if (error[i] < d)
2101 d = error[i];
2102 f = 0;
2103 if (nlist > 1) {
2104 for (j = 0; j < nlist; j++)
2105 f += DIFF(peer_list[j]->offset,
2106 peer_list[i]->offset);
2107 f /= nlist - 1;
2108 }
1767 f = max(f, SQUARE(LOGTOD(sys_precision)));
1768 if (f * synch[i] > e) {
1769 sys_selerr = f;
1770 e = f * synch[i];
1771 k = i;
1772 }
1773 }
2109 if (f * synch[i] > e) {
2110 sys_selerr = f;
2111 e = f * synch[i];
2112 k = i;
2113 }
2114 }
1774
2115 f = max(sys_selerr, SQUARE(LOGTOD(sys_precision)));
2116 if (nlist <= sys_minclock || f <= d ||
2117 peer_list[k]->flags & FLAG_PREFER)
2118 break;
1775#ifdef DEBUG
1776 if (debug > 2)
1777 printf(
2119#ifdef DEBUG
2120 if (debug > 2)
2121 printf(
1778 "select: survivors %d select %.6f peer %.6f\n",
1779 k, SQRT(sys_selerr), SQRT(d));
2122 "select: drop %s select %.6f jitter %.6f\n",
2123 ntoa(&peer_list[k]->srcadr),
2124 SQRT(sys_selerr), SQRT(d));
1780#endif
2125#endif
1781 if (nlist <= NTP_MINCLOCK || sys_selerr <= d ||
1782 peer_list[k]->flags & FLAG_PREFER)
1783 break;
1784 if (!(peer_list[k]->flags & FLAG_CONFIG))
2126 if (!(peer_list[k]->flags & FLAG_CONFIG) &&
2127 peer_list[k]->hmode == MODE_CLIENT)
1785 unpeer(peer_list[k]);
1786 for (j = k + 1; j < nlist; j++) {
1787 peer_list[j - 1] = peer_list[j];
1788 error[j - 1] = error[j];
1789 }
1790 nlist--;
1791 }
1792
2128 unpeer(peer_list[k]);
2129 for (j = k + 1; j < nlist; j++) {
2130 peer_list[j - 1] = peer_list[j];
2131 error[j - 1] = error[j];
2132 }
2133 nlist--;
2134 }
2135
1793#ifdef AUTOKEY
1794 /*
2136 /*
1795 * In manycast client mode we may have spooked a sizeable number
1796 * of servers that we don't need. If there are at least
1797 * NTP_MINCLOCK of them, the manycast message will be turned
1798 * off. By the time we get here we nay be ready to prune some of
1799 * them back, but we want to make sure all the candicates have
1800 * had a chance. If they didn't pass the sanity and intersection
1801 * tests, they have already been voted off the island.
1802 */
1803 if (sys_survivors >= NTP_MINCLOCK && nlist < NTP_MINCLOCK)
1804 resetmanycast();
1805#endif /* AUTOKEY */
1806 sys_survivors = nlist;
1807
1808#ifdef DEBUG
1809 if (debug > 2) {
1810 for (i = 0; i < nlist; i++)
1811 printf(
1812 "select: %s offset %.6f, distance %.6f poll %d\n",
1813 ntoa(&peer_list[i]->srcadr),
1814 peer_list[i]->offset, synch[i],
1815 peer_list[i]->pollsw);
1816 }
1817#endif
1818
1819 /*
1820 * What remains is a list of not greater than NTP_MINCLOCK
2137 * What remains is a list usually not greater than sys_minclock
1821 * peers. We want only a peer at the lowest stratum to become
1822 * the system peer, although all survivors are eligible for the
1823 * combining algorithm. First record their order, diddle the
2138 * peers. We want only a peer at the lowest stratum to become
2139 * the system peer, although all survivors are eligible for the
2140 * combining algorithm. First record their order, diddle the
1824 * flags and clamp the poll intervals. Then, consider the peers
1825 * at the lowest stratum. Of these, OR the leap bits on the
1826 * assumption that, if some of them honk nonzero bits, they must
1827 * know what they are doing. Also, check for prefer and pps
1828 * peers. If a prefer peer is found within clock_max, update the
1829 * pps switch. Of the other peers not at the lowest stratum,
1830 * check if the system peer is among them and, if found, zap
1831 * him. We note that the head of the list is at the lowest
2141 * flags and clamp the poll intervals. Then, consider each peer
2142 * in turn and OR the leap bits on the assumption that, if some
2143 * of them honk nonzero bits, they must know what they are
2144 * doing. Check for prefer and pps peers at any stratum. Check
2145 * if the old system peer is among the peers at the lowest
2146 * stratum. Note that the head of the list is at the lowest
1832 * stratum and that unsynchronized peers cannot survive this
1833 * far.
1834 *
2147 * stratum and that unsynchronized peers cannot survive this
2148 * far.
2149 *
1835 * Note that we go no further, unless the number of survivors is
1836 * a majority of the suckers that have been found reachable and
1837 * no prior source is available. This avoids the transient when
1838 * one of a flock of sources is out to lunch and just happens
1839 * to be the first survivor.
2150 * Fiddle for hysteresis. Pump it up for a peer only if the peer
2151 * stratum is at least the floor and there are enough survivors.
2152 * This minimizes the pain when tossing out rascals beneath the
2153 * floorboard. Don't count peers with stratum above the ceiling.
2154 * Manycast is sooo complicated.
1840 */
2155 */
1841 if (osys_peer == NULL && 2 * nlist < min(nreach, NTP_MINCLOCK))
1842 return;
1843 leap_consensus = 0;
1844 for (i = nlist - 1; i >= 0; i--) {
1845 peer = peer_list[i];
2156 leap_consensus = 0;
2157 for (i = nlist - 1; i >= 0; i--) {
2158 peer = peer_list[i];
2159 leap_consensus |= peer->leap;
1846 peer->status = CTL_PST_SEL_SYNCCAND;
2160 peer->status = CTL_PST_SEL_SYNCCAND;
2161 peer->rank++;
1847 peer->flags |= FLAG_SYSPEER;
2162 peer->flags |= FLAG_SYSPEER;
1848 poll_update(peer, peer->hpoll);
1849 if (peer->stratum == peer_list[0]->stratum) {
1850 leap_consensus |= peer->leap;
1851 if (peer->refclktype == REFCLK_ATOM_PPS &&
1852 peer->stratum < STRATUM_UNSPEC)
1853 typepps = peer;
1854 if (peer == osys_peer)
1855 typesystem = peer;
1856 if (peer->flags & FLAG_PREFER)
1857 sys_prefer = peer;
1858 }
2163 if (peer->stratum >= sys_floor && osurv >= sys_minclock)
2164 peer->hyst = HYST;
2165 else
2166 peer->hyst = 0;
2167 if (peer->stratum <= sys_ceiling)
2168 sys_survivors++;
2169 if (peer->flags & FLAG_PREFER)
2170 sys_prefer = peer;
2171 if (peer->refclktype == REFCLK_ATOM_PPS &&
2172 peer->stratum < STRATUM_UNSPEC)
2173 typepps = peer;
2174 if (peer->stratum == peer_list[0]->stratum && peer ==
2175 osys_peer)
2176 typesystem = peer;
1859 }
1860
1861 /*
2177 }
2178
2179 /*
2180 * In manycast client mode we may have spooked a sizeable number
2181 * of peers that we don't need. If there are at least
2182 * sys_minclock of them, the manycast message will be turned
2183 * off. By the time we get here we nay be ready to prune some of
2184 * them back, but we want to make sure all the candicates have
2185 * had a chance. If they didn't pass the sanity and intersection
2186 * tests, they have already been voted off the island.
2187 */
2188 if (sys_survivors < sys_minclock && osurv >= sys_minclock)
2189 resetmanycast();
2190
2191 /*
1862 * Mitigation rules of the game. There are several types of
1863 * peers that make a difference here: (1) prefer local peers
1864 * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
1865 * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
1866 * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
1867 * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
1868 * the head of the survivor list. Note that only one peer can be
1869 * declared prefer. The order of preference is in the order

--- 11 unchanged lines hidden (view full) ---

1881 sys_peer->status = CTL_PST_SEL_SYSPEER;
1882 sys_offset = sys_peer->offset;
1883 sys_syserr = sys_peer->jitter;
1884#ifdef DEBUG
1885 if (debug > 1)
1886 printf("select: prefer offset %.6f\n",
1887 sys_offset);
1888#endif
2192 * Mitigation rules of the game. There are several types of
2193 * peers that make a difference here: (1) prefer local peers
2194 * (type REFCLK_LOCALCLOCK with FLAG_PREFER) or prefer modem
2195 * peers (type REFCLK_NIST_ATOM etc with FLAG_PREFER), (2) pps
2196 * peers (type REFCLK_ATOM_PPS), (3) remaining prefer peers
2197 * (flag FLAG_PREFER), (4) the existing system peer, if any, (5)
2198 * the head of the survivor list. Note that only one peer can be
2199 * declared prefer. The order of preference is in the order

--- 11 unchanged lines hidden (view full) ---

2211 sys_peer->status = CTL_PST_SEL_SYSPEER;
2212 sys_offset = sys_peer->offset;
2213 sys_syserr = sys_peer->jitter;
2214#ifdef DEBUG
2215 if (debug > 1)
2216 printf("select: prefer offset %.6f\n",
2217 sys_offset);
2218#endif
1889 } else if (typepps) {
2219 }
2220#ifndef LOCKCLOCK
2221 else if (typepps) {
1890 sys_peer = typepps;
1891 sys_peer->status = CTL_PST_SEL_PPS;
1892 sys_offset = sys_peer->offset;
1893 sys_syserr = sys_peer->jitter;
1894 if (!pps_control)
1895 NLOG(NLOG_SYSEVENT)
2222 sys_peer = typepps;
2223 sys_peer->status = CTL_PST_SEL_PPS;
2224 sys_offset = sys_peer->offset;
2225 sys_syserr = sys_peer->jitter;
2226 if (!pps_control)
2227 NLOG(NLOG_SYSEVENT)
1896 msyslog(LOG_INFO,
1897 "pps sync enabled");
2228 msyslog(LOG_INFO, "pps sync enabled");
1898 pps_control = current_time;
1899#ifdef DEBUG
1900 if (debug > 1)
1901 printf("select: pps offset %.6f\n",
1902 sys_offset);
1903#endif
1904 } else {
1905 if (typesystem)
1906 sys_peer = osys_peer;
1907 else
1908 sys_peer = peer_list[0];
1909 sys_peer->status = CTL_PST_SEL_SYSPEER;
2229 pps_control = current_time;
2230#ifdef DEBUG
2231 if (debug > 1)
2232 printf("select: pps offset %.6f\n",
2233 sys_offset);
2234#endif
2235 } else {
2236 if (typesystem)
2237 sys_peer = osys_peer;
2238 else
2239 sys_peer = peer_list[0];
2240 sys_peer->status = CTL_PST_SEL_SYSPEER;
2241 sys_peer->rank++;
1910 sys_offset = clock_combine(peer_list, nlist);
1911 sys_syserr = sys_peer->jitter + sys_selerr;
1912#ifdef DEBUG
1913 if (debug > 1)
1914 printf("select: combine offset %.6f\n",
1915 sys_offset);
1916#endif
1917 }
2242 sys_offset = clock_combine(peer_list, nlist);
2243 sys_syserr = sys_peer->jitter + sys_selerr;
2244#ifdef DEBUG
2245 if (debug > 1)
2246 printf("select: combine offset %.6f\n",
2247 sys_offset);
2248#endif
2249 }
1918 if (osys_peer != sys_peer)
1919 report_event(EVNT_PEERSTCHG, (struct peer *)0);
2250#endif /* LOCKCLOCK */
2251 if (osys_peer != sys_peer) {
2252 char *src;
2253
2254 if (sys_peer == NULL)
2255 sys_peer_refid = 0;
2256 else
2257 sys_peer_refid = addr2refid(&sys_peer->srcadr);
2258 report_event(EVNT_PEERSTCHG, NULL);
2259
2260#ifdef REFCLOCK
2261 if (ISREFCLOCKADR(&sys_peer->srcadr))
2262 src = refnumtoa(&sys_peer->srcadr);
2263 else
2264#endif
2265 src = ntoa(&sys_peer->srcadr);
2266 NLOG(NLOG_SYNCSTATUS)
2267 msyslog(LOG_INFO, "synchronized to %s, stratum=%d", src,
2268 sys_peer->stratum);
2269 }
1920 clock_update();
1921}
1922
1923/*
1924 * clock_combine - combine offsets from selected peers
1925 */
1926static double
1927clock_combine(
1928 struct peer **peers,
2270 clock_update();
2271}
2272
2273/*
2274 * clock_combine - combine offsets from selected peers
2275 */
2276static double
2277clock_combine(
2278 struct peer **peers,
1929 int npeers
2279 int npeers
1930 )
1931{
2280 )
2281{
1932 int i;
1933 double x, y, z;
2282 int i;
2283 double x, y, z;
2284
1934 y = z = 0;
1935 for (i = 0; i < npeers; i++) {
1936 x = root_distance(peers[i]);
1937 y += 1. / x;
1938 z += peers[i]->offset / x;
1939 }
1940 return (z / y);
1941}

--- 20 unchanged lines hidden (view full) ---

1962 * peer_xmit - send packet for persistent association.
1963 */
1964static void
1965peer_xmit(
1966 struct peer *peer /* peer structure pointer */
1967 )
1968{
1969 struct pkt xpkt; /* transmit packet */
2285 y = z = 0;
2286 for (i = 0; i < npeers; i++) {
2287 x = root_distance(peers[i]);
2288 y += 1. / x;
2289 z += peers[i]->offset / x;
2290 }
2291 return (z / y);
2292}

--- 20 unchanged lines hidden (view full) ---

2313 * peer_xmit - send packet for persistent association.
2314 */
2315static void
2316peer_xmit(
2317 struct peer *peer /* peer structure pointer */
2318 )
2319{
2320 struct pkt xpkt; /* transmit packet */
1970 int sendlen, authlen;
1971 keyid_t xkeyid; /* transmit key ID */
1972 l_fp xmt_tx;
2321 int sendlen, authlen;
2322 keyid_t xkeyid = 0; /* transmit key ID */
2323 l_fp xmt_tx;
1973
1974 /*
1975 * Initialize transmit packet header fields.
1976 */
1977 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
1978 peer->hmode);
1979 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
1980 xpkt.ppoll = peer->hpoll;

--- 14 unchanged lines hidden (view full) ---

1995 * until after receiving a packet and setting the right
1996 * interface. So, the first packet goes out unauthenticated.
1997 * That's why the really icky test next is here.
1998 */
1999 sendlen = LEN_PKT_NOMAC;
2000 if (!(peer->flags & FLAG_AUTHENABLE)) {
2001 get_systime(&peer->xmt);
2002 HTONL_FP(&peer->xmt, &xpkt.xmt);
2324
2325 /*
2326 * Initialize transmit packet header fields.
2327 */
2328 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap, peer->version,
2329 peer->hmode);
2330 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2331 xpkt.ppoll = peer->hpoll;

--- 14 unchanged lines hidden (view full) ---

2346 * until after receiving a packet and setting the right
2347 * interface. So, the first packet goes out unauthenticated.
2348 * That's why the really icky test next is here.
2349 */
2350 sendlen = LEN_PKT_NOMAC;
2351 if (!(peer->flags & FLAG_AUTHENABLE)) {
2352 get_systime(&peer->xmt);
2353 HTONL_FP(&peer->xmt, &xpkt.xmt);
2003 sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt,
2004 sendlen);
2354 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl],
2355 &xpkt, sendlen);
2005 peer->sent++;
2006#ifdef DEBUG
2007 if (debug)
2008 printf("transmit: at %ld %s->%s mode %d\n",
2356 peer->sent++;
2357#ifdef DEBUG
2358 if (debug)
2359 printf("transmit: at %ld %s->%s mode %d\n",
2009 current_time, ntoa(&peer->dstadr->sin),
2010 ntoa(&peer->srcadr), peer->hmode);
2360 current_time, stoa(&peer->dstadr->sin),
2361 stoa(&peer->srcadr), peer->hmode);
2011#endif
2012 return;
2013 }
2014
2015 /*
2016 * The received packet contains a MAC, so the transmitted packet
2017 * must be authenticated. If autokey is enabled, fuss with the
2018 * various modes; otherwise, private key cryptography is used.
2019 */
2362#endif
2363 return;
2364 }
2365
2366 /*
2367 * The received packet contains a MAC, so the transmitted packet
2368 * must be authenticated. If autokey is enabled, fuss with the
2369 * various modes; otherwise, private key cryptography is used.
2370 */
2020#ifdef AUTOKEY
2021 if ((peer->flags & FLAG_SKEY)) {
2022 u_int cmmd;
2371#ifdef OPENSSL
2372 if (crypto_flags && (peer->flags & FLAG_SKEY)) {
2373 struct exten *exten; /* extension field */
2374 u_int opcode;
2023
2024 /*
2025 * The Public Key Dance (PKD): Cryptographic credentials
2026 * are contained in extension fields, each including a
2027 * 4-octet length/code word followed by a 4-octet
2028 * association ID and optional additional data. Optional
2029 * data includes a 4-octet data length field followed by
2030 * the data itself. Request messages are sent from a

--- 43 unchanged lines hidden (view full) ---

2074 break;
2075 else
2076 key_expire(peer);
2077 }
2078 peer->keyid = xkeyid;
2079 switch (peer->hmode) {
2080
2081 /*
2375
2376 /*
2377 * The Public Key Dance (PKD): Cryptographic credentials
2378 * are contained in extension fields, each including a
2379 * 4-octet length/code word followed by a 4-octet
2380 * association ID and optional additional data. Optional
2381 * data includes a 4-octet data length field followed by
2382 * the data itself. Request messages are sent from a

--- 43 unchanged lines hidden (view full) ---

2426 break;
2427 else
2428 key_expire(peer);
2429 }
2430 peer->keyid = xkeyid;
2431 switch (peer->hmode) {
2432
2433 /*
2082 * In broadcast mode the autokey values are required.
2083 * Send them when a new keylist is generated; otherwise,
2084 * send the association ID so the client can request
2085 * them at other times.
2434 * In broadcast server mode the autokey values are
2435 * required by the broadcast clients. Push them when a
2436 * new keylist is generated; otherwise, push the
2437 * association message so the client can request them at
2438 * other times.
2086 */
2087 case MODE_BROADCAST:
2088 if (peer->flags & FLAG_ASSOC)
2439 */
2440 case MODE_BROADCAST:
2441 if (peer->flags & FLAG_ASSOC)
2089 cmmd = CRYPTO_AUTO | CRYPTO_RESP;
2442 exten = crypto_args(peer, CRYPTO_AUTO |
2443 CRYPTO_RESP, NULL);
2090 else
2444 else
2091 cmmd = CRYPTO_ASSOC | CRYPTO_RESP;
2092 sendlen += crypto_xmit((u_int32 *)&xpkt,
2093 sendlen, cmmd, 0, peer->associd);
2445 exten = crypto_args(peer, CRYPTO_ASSOC |
2446 CRYPTO_RESP, NULL);
2447 sendlen += crypto_xmit(&xpkt, &peer->srcadr,
2448 sendlen, exten, 0);
2449 free(exten);
2094 break;
2095
2096 /*
2450 break;
2451
2452 /*
2097 * In symmetric modes the public key, leapsecond table,
2098 * agreement parameters and autokey values are required.
2099 *
2100 * 1. If a response is pending, always send it first.
2101 *
2102 * 2. Don't send anything except a public-key request
2103 * until the public key has been stored.
2104 *
2105 * 3. Once the public key has been stored, don't send
2106 * anything except an agreement parameter request
2107 * until the agreement parameters have been stored.
2108 *
2109 * 4. Once the argeement parameters have been stored,
2110 * don't send anything except a public value request
2111 * until the agreed key has been stored.
2112 *
2113 * 5. When the agreed key has been stored and the key
2114 * list is regenerated, send the autokey values
2115 * gratis unless they have already been sent.
2453 * In symmetric modes the digest, certificate, agreement
2454 * parameters, cookie and autokey values are required.
2455 * The leapsecond table is optional. But, a passive peer
2456 * will not believe the active peer until the latter has
2457 * synchronized, so the agreement must be postponed
2458 * until then. In any case, if a new keylist is
2459 * generated, the autokey values are pushed.
2116 */
2117 case MODE_ACTIVE:
2118 case MODE_PASSIVE:
2460 */
2461 case MODE_ACTIVE:
2462 case MODE_PASSIVE:
2119#ifdef PUBKEY
2120 if (peer->cmmd != 0)
2121 sendlen += crypto_xmit((u_int32 *)&xpkt,
2122 sendlen, (peer->cmmd >> 16) |
2123 CRYPTO_RESP, peer->hcookie,
2124 peer->associd);
2463 if (peer->cmmd != NULL) {
2464 peer->cmmd->associd =
2465 htonl(peer->associd);
2466 sendlen += crypto_xmit(&xpkt,
2467 &peer->srcadr, sendlen, peer->cmmd,
2468 0);
2469 free(peer->cmmd);
2470 peer->cmmd = NULL;
2471 }
2472 exten = NULL;
2125 if (!peer->crypto)
2473 if (!peer->crypto)
2126 sendlen += crypto_xmit((u_int32 *)&xpkt,
2127 sendlen, CRYPTO_ASSOC,
2128 peer->hcookie, peer->assoc);
2129 else if (!crypto_flags &&
2130 peer->pcookie.tstamp == 0 && sys_leap !=
2131 LEAP_NOTINSYNC)
2132 sendlen += crypto_xmit((u_int32 *)&xpkt,
2133 sendlen, CRYPTO_PRIV, peer->hcookie,
2134 peer->assoc);
2135 else if (crypto_flags && peer->pubkey.ptr ==
2136 NULL)
2137 sendlen += crypto_xmit((u_int32 *)&xpkt,
2138 sendlen, CRYPTO_NAME, peer->hcookie,
2139 peer->assoc);
2140 else if (peer->crypto & CRYPTO_FLAG_CERT)
2141 sendlen += crypto_xmit((u_int32 *)&xpkt,
2142 sendlen, CRYPTO_CERT, peer->hcookie,
2143 peer->assoc);
2144 else if (crypto_flags && peer->crypto &
2145 CRYPTO_FLAG_DH && sys_leap !=
2146 LEAP_NOTINSYNC)
2147 sendlen += crypto_xmit((u_int32 *)&xpkt,
2148 sendlen, CRYPTO_DHPAR,
2149 peer->hcookie, peer->assoc);
2150 else if (crypto_flags && peer->pcookie.tstamp ==
2151 0 && sys_leap != LEAP_NOTINSYNC)
2152 sendlen += crypto_xmit((u_int32 *)&xpkt,
2153 sendlen, CRYPTO_DH, peer->hcookie,
2154 peer->assoc);
2155#else
2156 if (peer->cmmd != 0)
2157 sendlen += crypto_xmit((u_int32 *)&xpkt,
2158 sendlen, (peer->cmmd >> 16) |
2159 CRYPTO_RESP, peer->hcookie,
2160 peer->associd);
2161 if (peer->pcookie.tstamp == 0 && sys_leap !=
2162 LEAP_NOTINSYNC)
2163 sendlen += crypto_xmit((u_int32 *)&xpkt,
2164 sendlen, CRYPTO_PRIV, peer->hcookie,
2165 peer->assoc);
2166#endif /* PUBKEY */
2167 else if (!(peer->flags & FLAG_AUTOKEY))
2168 sendlen += crypto_xmit((u_int32 *)&xpkt,
2169 sendlen, CRYPTO_AUTO, peer->hcookie,
2170 peer->assoc);
2171 else if ((peer->flags & FLAG_ASSOC) &&
2172 (peer->cmmd >> 16) != CRYPTO_AUTO)
2173 sendlen += crypto_xmit((u_int32 *)&xpkt,
2174 sendlen, CRYPTO_AUTO | CRYPTO_RESP,
2175 peer->hcookie, peer->associd);
2176#ifdef PUBKEY
2177 else if (peer->crypto & CRYPTO_FLAG_TAI)
2178 sendlen += crypto_xmit((u_int32 *)&xpkt,
2179 sendlen, CRYPTO_TAI, peer->hcookie,
2180 peer->assoc);
2181#endif /* PUBKEY */
2182 peer->cmmd = 0;
2474 exten = crypto_args(peer, CRYPTO_ASSOC,
2475 sys_hostname);
2476 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2477 exten = crypto_args(peer, CRYPTO_CERT,
2478 peer->issuer);
2479
2480 /*
2481 * Identity. Note we have to sign the
2482 * certificate before the cookie to avoid a
2483 * deadlock when the passive peer is walking the
2484 * certificate trail. Awesome.
2485 */
2486 else if ((opcode = crypto_ident(peer)) != 0)
2487 exten = crypto_args(peer, opcode, NULL);
2488 else if (sys_leap != LEAP_NOTINSYNC &&
2489 !(peer->crypto & CRYPTO_FLAG_SIGN))
2490 exten = crypto_args(peer, CRYPTO_SIGN,
2491 sys_hostname);
2492
2493 /*
2494 * Autokey. We request the cookie only when the
2495 * server and client are synchronized and
2496 * signatures work both ways. On the other hand,
2497 * the active peer needs the autokey values
2498 * before then and when the passive peer is
2499 * waiting for the active peer to synchronize.
2500 * Any time we regenerate the key list, we offer
2501 * the autokey values without being asked.
2502 */
2503 else if (sys_leap != LEAP_NOTINSYNC &&
2504 peer->leap != LEAP_NOTINSYNC &&
2505 !(peer->crypto & CRYPTO_FLAG_AGREE))
2506 exten = crypto_args(peer, CRYPTO_COOK,
2507 NULL);
2508 else if (peer->flags & FLAG_ASSOC)
2509 exten = crypto_args(peer, CRYPTO_AUTO |
2510 CRYPTO_RESP, NULL);
2511 else if (!(peer->crypto & CRYPTO_FLAG_AUTO))
2512 exten = crypto_args(peer, CRYPTO_AUTO,
2513 NULL);
2514
2515 /*
2516 * Postamble. We trade leapseconds only when the
2517 * server and client are synchronized.
2518 */
2519 else if (sys_leap != LEAP_NOTINSYNC &&
2520 peer->leap != LEAP_NOTINSYNC &&
2521 peer->crypto & CRYPTO_FLAG_TAI &&
2522 !(peer->crypto & CRYPTO_FLAG_LEAP))
2523 exten = crypto_args(peer, CRYPTO_TAI,
2524 NULL);
2525 if (exten != NULL) {
2526 sendlen += crypto_xmit(&xpkt,
2527 &peer->srcadr, sendlen, exten, 0);
2528 free(exten);
2529 }
2183 break;
2184
2185 /*
2530 break;
2531
2532 /*
2186 * In client mode, the public key, host cookie and
2187 * autokey values are required. In broadcast client
2188 * mode, these values must be acquired during the
2533 * In client mode the digest, certificate, agreement
2534 * parameters and cookie are required. The leapsecond
2535 * table is optional. If broadcast client mode, the
2536 * autokey values are required as well. In broadcast
2537 * client mode, these values must be acquired during the
2189 * client/server exchange to avoid having to wait until
2190 * the next key list regeneration. Otherwise, the poor
2191 * dude may die a lingering death until becoming
2538 * client/server exchange to avoid having to wait until
2539 * the next key list regeneration. Otherwise, the poor
2540 * dude may die a lingering death until becoming
2192 * unreachable and attempting rebirth. Note that we ask
2193 * for the cookie at each key list regeneration anyway.
2541 * unreachable and attempting rebirth.
2542 *
2543 * If neither the server or client have the agreement
2544 * parameters, the protocol transmits the cookie in the
2545 * clear. If the server has the parameters, the client
2546 * requests them and the protocol blinds it using the
2547 * agreed key. It is a protocol error if the client has
2548 * the parameters but the server does not.
2194 */
2195 case MODE_CLIENT:
2549 */
2550 case MODE_CLIENT:
2196 if (peer->cmmd != 0)
2197 sendlen += crypto_xmit((u_int32 *)&xpkt,
2198 sendlen, (peer->cmmd >> 16) |
2199 CRYPTO_RESP, peer->hcookie,
2200 peer->associd);
2551 if (peer->cmmd != NULL) {
2552 peer->cmmd->associd =
2553 htonl(peer->associd);
2554 sendlen += crypto_xmit(&xpkt,
2555 &peer->srcadr, sendlen, peer->cmmd,
2556 0);
2557 free(peer->cmmd);
2558 peer->cmmd = NULL;
2559 }
2560 exten = NULL;
2201 if (!peer->crypto)
2561 if (!peer->crypto)
2202 sendlen += crypto_xmit((u_int32 *)&xpkt,
2203 sendlen, CRYPTO_ASSOC,
2204 peer->hcookie, peer->assoc);
2205#ifdef PUBKEY
2206 else if (crypto_flags && peer->pubkey.ptr ==
2207 NULL)
2208 sendlen += crypto_xmit((u_int32 *)&xpkt,
2209 sendlen, CRYPTO_NAME, peer->hcookie,
2210 peer->assoc);
2211 else if (peer->crypto & CRYPTO_FLAG_CERT)
2212 sendlen += crypto_xmit((u_int32 *)&xpkt,
2213 sendlen, CRYPTO_CERT, peer->hcookie,
2214 peer->assoc);
2215#endif /* PUBKEY */
2216 else if (peer->pcookie.tstamp == 0)
2217 sendlen += crypto_xmit((u_int32 *)&xpkt,
2218 sendlen, CRYPTO_PRIV, peer->hcookie,
2219 peer->assoc);
2220 else if (!(peer->flags & FLAG_AUTOKEY) &&
2562 exten = crypto_args(peer, CRYPTO_ASSOC,
2563 sys_hostname);
2564 else if (!(peer->crypto & CRYPTO_FLAG_VALID))
2565 exten = crypto_args(peer, CRYPTO_CERT,
2566 peer->issuer);
2567
2568 /*
2569 * Identity.
2570 */
2571 else if ((opcode = crypto_ident(peer)) != 0)
2572 exten = crypto_args(peer, opcode, NULL);
2573
2574 /*
2575 * Autokey
2576 */
2577 else if (!(peer->crypto & CRYPTO_FLAG_AGREE))
2578 exten = crypto_args(peer, CRYPTO_COOK,
2579 NULL);
2580 else if (!(peer->crypto & CRYPTO_FLAG_AUTO) &&
2221 (peer->cast_flags & MDF_BCLNT))
2581 (peer->cast_flags & MDF_BCLNT))
2222 sendlen += crypto_xmit((u_int32 *)&xpkt,
2223 sendlen, CRYPTO_AUTO, peer->hcookie,
2224 peer->assoc);
2225#ifdef PUBKEY
2226 else if (peer->crypto & CRYPTO_FLAG_TAI)
2227 sendlen += crypto_xmit((u_int32 *)&xpkt,
2228 sendlen, CRYPTO_TAI, peer->hcookie,
2229 peer->assoc);
2230#endif /* PUBKEY */
2231 peer->cmmd = 0;
2582 exten = crypto_args(peer, CRYPTO_AUTO,
2583 NULL);
2584
2585 /*
2586 * Postamble. We can sign the certificate here,
2587 * since there is no chance of deadlock.
2588 */
2589 else if (sys_leap != LEAP_NOTINSYNC &&
2590 !(peer->crypto & CRYPTO_FLAG_SIGN))
2591 exten = crypto_args(peer, CRYPTO_SIGN,
2592 sys_hostname);
2593 else if (sys_leap != LEAP_NOTINSYNC &&
2594 peer->crypto & CRYPTO_FLAG_TAI &&
2595 !(peer->crypto & CRYPTO_FLAG_LEAP))
2596 exten = crypto_args(peer, CRYPTO_TAI,
2597 NULL);
2598 if (exten != NULL) {
2599 sendlen += crypto_xmit(&xpkt,
2600 &peer->srcadr, sendlen, exten, 0);
2601 free(exten);
2602 }
2232 break;
2233 }
2234
2235 /*
2236 * If extension fields are present, we must use a
2603 break;
2604 }
2605
2606 /*
2607 * If extension fields are present, we must use a
2237 * private value of zero and force min poll interval.
2608 * private value of zero and force min poll interval.
2238 * Most intricate.
2239 */
2240 if (sendlen > LEN_PKT_NOMAC)
2241 session_key(&peer->dstadr->sin, &peer->srcadr,
2242 xkeyid, 0, 2);
2243 }
2609 * Most intricate.
2610 */
2611 if (sendlen > LEN_PKT_NOMAC)
2612 session_key(&peer->dstadr->sin, &peer->srcadr,
2613 xkeyid, 0, 2);
2614 }
2244#endif /* AUTOKEY */
2615#endif /* OPENSSL */
2245 xkeyid = peer->keyid;
2246 get_systime(&peer->xmt);
2247 L_ADD(&peer->xmt, &sys_authdelay);
2248 HTONL_FP(&peer->xmt, &xpkt.xmt);
2249 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2250 if (authlen == 0) {
2616 xkeyid = peer->keyid;
2617 get_systime(&peer->xmt);
2618 L_ADD(&peer->xmt, &sys_authdelay);
2619 HTONL_FP(&peer->xmt, &xpkt.xmt);
2620 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2621 if (authlen == 0) {
2251 msyslog(LOG_NOTICE,
2252 "transmit: no encryption key found");
2253 peer->flash |= TEST4 | TEST5;
2622 msyslog(LOG_INFO,
2623 "transmit: encryption key %d not found", xkeyid);
2624 if (peer->flags & FLAG_CONFIG)
2625 peer_clear(peer, "NKEY");
2626 else
2627 unpeer(peer);
2254 return;
2255 }
2256 sendlen += authlen;
2628 return;
2629 }
2630 sendlen += authlen;
2257#ifdef AUTOKEY
2631#ifdef OPENSSL
2258 if (xkeyid > NTP_MAXKEY)
2259 authtrust(xkeyid, 0);
2632 if (xkeyid > NTP_MAXKEY)
2633 authtrust(xkeyid, 0);
2260#endif /* AUTOKEY */
2634#endif /* OPENSSL */
2261 get_systime(&xmt_tx);
2262 if (sendlen > sizeof(xpkt)) {
2263 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2635 get_systime(&xmt_tx);
2636 if (sendlen > sizeof(xpkt)) {
2637 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2264 exit(-1);
2638 exit (-1);
2265 }
2639 }
2266 sendpkt(&peer->srcadr, peer->dstadr, peer->ttl, &xpkt, sendlen);
2640 sendpkt(&peer->srcadr, peer->dstadr, sys_ttl[peer->ttl], &xpkt,
2641 sendlen);
2267
2268 /*
2269 * Calculate the encryption delay. Keep the minimum over
2270 * the latest two samples.
2271 */
2272 L_SUB(&xmt_tx, &peer->xmt);
2273 L_ADD(&xmt_tx, &sys_authdelay);
2274 sys_authdly[1] = sys_authdly[0];
2275 sys_authdly[0] = xmt_tx.l_uf;
2276 if (sys_authdly[0] < sys_authdly[1])
2277 sys_authdelay.l_uf = sys_authdly[0];
2278 else
2279 sys_authdelay.l_uf = sys_authdly[1];
2280 peer->sent++;
2642
2643 /*
2644 * Calculate the encryption delay. Keep the minimum over
2645 * the latest two samples.
2646 */
2647 L_SUB(&xmt_tx, &peer->xmt);
2648 L_ADD(&xmt_tx, &sys_authdelay);
2649 sys_authdly[1] = sys_authdly[0];
2650 sys_authdly[0] = xmt_tx.l_uf;
2651 if (sys_authdly[0] < sys_authdly[1])
2652 sys_authdelay.l_uf = sys_authdly[0];
2653 else
2654 sys_authdelay.l_uf = sys_authdly[1];
2655 peer->sent++;
2281#ifdef AUTOKEY
2656#ifdef OPENSSL
2282#ifdef DEBUG
2283 if (debug)
2284 printf(
2285 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2286 current_time, ntoa(&peer->dstadr->sin),
2657#ifdef DEBUG
2658 if (debug)
2659 printf(
2660 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d index %d\n",
2661 current_time, ntoa(&peer->dstadr->sin),
2287 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2288 authlen, peer->keynumber);
2662 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2663 authlen, authlen, peer->keynumber);
2289#endif
2290#else
2291#ifdef DEBUG
2292 if (debug)
2293 printf(
2294 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2295 current_time, ntoa(&peer->dstadr->sin),
2664#endif
2665#else
2666#ifdef DEBUG
2667 if (debug)
2668 printf(
2669 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2670 current_time, ntoa(&peer->dstadr->sin),
2296 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen,
2297 authlen);
2671 ntoa(&peer->srcadr), peer->hmode, xkeyid, sendlen -
2672 authlen, authlen);
2298#endif
2673#endif
2299#endif /* AUTOKEY */
2674#endif /* OPENSSL */
2300}
2301
2302
2303/*
2304 * fast_xmit - Send packet for nonpersistent association. Note that
2305 * neither the source or destination can be a broadcast address.
2306 */
2307static void
2308fast_xmit(
2309 struct recvbuf *rbufp, /* receive packet pointer */
2675}
2676
2677
2678/*
2679 * fast_xmit - Send packet for nonpersistent association. Note that
2680 * neither the source or destination can be a broadcast address.
2681 */
2682static void
2683fast_xmit(
2684 struct recvbuf *rbufp, /* receive packet pointer */
2310 int xmode, /* transmit mode */
2311 keyid_t xkeyid, /* transmit key ID */
2312 int mask /* restrict mask */
2685 int xmode, /* transmit mode */
2686 keyid_t xkeyid, /* transmit key ID */
2687 int mask /* restrict mask */
2313 )
2314{
2688 )
2689{
2315 struct pkt xpkt; /* transmit packet structure */
2316 struct pkt *rpkt; /* receive packet structure */
2317 l_fp xmt_ts; /* transmit timestamp */
2318 l_fp xmt_tx; /* transmit timestamp after authent */
2319 int sendlen, authlen;
2690 struct pkt xpkt; /* transmit packet structure */
2691 struct pkt *rpkt; /* receive packet structure */
2692 l_fp xmt_ts; /* timestamp */
2693 l_fp xmt_tx; /* timestamp after authent */
2694 int sendlen, authlen;
2695#ifdef OPENSSL
2696 u_int32 temp32;
2697#endif
2320
2321 /*
2322 * Initialize transmit packet header fields from the receive
2323 * buffer provided. We leave some fields intact as received. If
2324 * the gazinta was from a multicast address, the gazouta must go
2325 * out another way.
2326 */
2327 rpkt = &rbufp->recv_pkt;
2328 if (rbufp->dstadr->flags & INT_MULTICAST)
2329 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2330
2331 /*
2698
2699 /*
2700 * Initialize transmit packet header fields from the receive
2701 * buffer provided. We leave some fields intact as received. If
2702 * the gazinta was from a multicast address, the gazouta must go
2703 * out another way.
2704 */
2705 rpkt = &rbufp->recv_pkt;
2706 if (rbufp->dstadr->flags & INT_MULTICAST)
2707 rbufp->dstadr = findinterface(&rbufp->recv_srcadr);
2708
2709 /*
2332 * If the caller is restricted, return a kiss-of-death packet;
2333 * otherwise, smooch politely.
2710 * If the packet has picked up a restriction due to either
2711 * access denied or rate exceeded, decide what to do with it.
2334 */
2712 */
2335 if (mask & (RES_DONTSERVE | RES_LIMITED)) {
2336 if (!(mask & RES_DEMOBILIZE)) {
2337 return;
2338 } else {
2339 xpkt.li_vn_mode =
2340 PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2341 PKT_VERSION(rpkt->li_vn_mode), xmode);
2342 xpkt.stratum = STRATUM_UNSPEC;
2343 memcpy(&xpkt.refid, "DENY", 4);
2713 if (mask & (RES_DONTTRUST | RES_LIMITED)) {
2714 char *code = "????";
2715
2716 if (mask & RES_LIMITED) {
2717 sys_limitrejected++;
2718 code = "RATE";
2719 } else if (mask & RES_DONTTRUST) {
2720 sys_restricted++;
2721 code = "DENY";
2344 }
2722 }
2723
2724 /*
2725 * Here we light up a kiss-of-death packet. Note the
2726 * rate limit on these packets. Once a second initialize
2727 * a bucket counter. Every packet sent decrements the
2728 * counter until reaching zero. If the counter is zero,
2729 * drop the kod.
2730 */
2731 if (sys_kod == 0 || !(mask & RES_DEMOBILIZE))
2732 return;
2733
2734 sys_kod--;
2735 memcpy(&xpkt.refid, code, 4);
2736 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
2737 PKT_VERSION(rpkt->li_vn_mode), xmode);
2738 xpkt.stratum = STRATUM_UNSPEC;
2345 } else {
2346 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2347 PKT_VERSION(rpkt->li_vn_mode), xmode);
2348 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2349 xpkt.refid = sys_refid;
2350 }
2351 xpkt.ppoll = rpkt->ppoll;
2352 xpkt.precision = sys_precision;

--- 13 unchanged lines hidden (view full) ---

2366 if (rbufp->recv_length == sendlen) {
2367 get_systime(&xmt_ts);
2368 HTONL_FP(&xmt_ts, &xpkt.xmt);
2369 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2370 sendlen);
2371#ifdef DEBUG
2372 if (debug)
2373 printf("transmit: at %ld %s->%s mode %d\n",
2739 } else {
2740 xpkt.li_vn_mode = PKT_LI_VN_MODE(sys_leap,
2741 PKT_VERSION(rpkt->li_vn_mode), xmode);
2742 xpkt.stratum = STRATUM_TO_PKT(sys_stratum);
2743 xpkt.refid = sys_refid;
2744 }
2745 xpkt.ppoll = rpkt->ppoll;
2746 xpkt.precision = sys_precision;

--- 13 unchanged lines hidden (view full) ---

2760 if (rbufp->recv_length == sendlen) {
2761 get_systime(&xmt_ts);
2762 HTONL_FP(&xmt_ts, &xpkt.xmt);
2763 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt,
2764 sendlen);
2765#ifdef DEBUG
2766 if (debug)
2767 printf("transmit: at %ld %s->%s mode %d\n",
2374 current_time, ntoa(&rbufp->dstadr->sin),
2375 ntoa(&rbufp->recv_srcadr), xmode);
2768 current_time, stoa(&rbufp->dstadr->sin),
2769 stoa(&rbufp->recv_srcadr), xmode);
2376#endif
2377 return;
2378 }
2379
2380 /*
2381 * The received packet contains a MAC, so the transmitted packet
2382 * must be authenticated. For private-key cryptography, use the
2383 * predefined private keys to generate the cryptosum. For
2384 * autokey cryptography, use the server private value to
2385 * generate the cookie, which is unique for every source-
2386 * destination-key ID combination.
2387 */
2770#endif
2771 return;
2772 }
2773
2774 /*
2775 * The received packet contains a MAC, so the transmitted packet
2776 * must be authenticated. For private-key cryptography, use the
2777 * predefined private keys to generate the cryptosum. For
2778 * autokey cryptography, use the server private value to
2779 * generate the cookie, which is unique for every source-
2780 * destination-key ID combination.
2781 */
2388#ifdef AUTOKEY
2782#ifdef OPENSSL
2389 if (xkeyid > NTP_MAXKEY) {
2390 keyid_t cookie;
2783 if (xkeyid > NTP_MAXKEY) {
2784 keyid_t cookie;
2391 u_int code, associd;
2392
2393 /*
2394 * The only way to get here is a reply to a legitimate
2395 * client request message, so the mode must be
2396 * MODE_SERVER. If an extension field is present, there
2397 * can be only one and that must be a command. Do what
2398 * needs, but with private value of zero so the poor
2399 * jerk can decode it. If no extension field is present,
2400 * use the cookie to generate the session key.
2401 */
2785
2786 /*
2787 * The only way to get here is a reply to a legitimate
2788 * client request message, so the mode must be
2789 * MODE_SERVER. If an extension field is present, there
2790 * can be only one and that must be a command. Do what
2791 * needs, but with private value of zero so the poor
2792 * jerk can decode it. If no extension field is present,
2793 * use the cookie to generate the session key.
2794 */
2402 code = (htonl(rpkt->exten[0]) >> 16) | CRYPTO_RESP;
2403 cookie = session_key(&rbufp->recv_srcadr,
2404 &rbufp->dstadr->sin, 0, sys_private, 0);
2795 cookie = session_key(&rbufp->recv_srcadr,
2796 &rbufp->dstadr->sin, 0, sys_private, 0);
2405 associd = htonl(rpkt->exten[1]);
2406 if (rbufp->recv_length >= sendlen + MAX_MAC_LEN + 2 *
2407 sizeof(u_int32)) {
2797 if (rbufp->recv_length >= (int)(sendlen + MAX_MAC_LEN + 2 *
2798 sizeof(u_int32))) {
2408 session_key(&rbufp->dstadr->sin,
2409 &rbufp->recv_srcadr, xkeyid, 0, 2);
2799 session_key(&rbufp->dstadr->sin,
2800 &rbufp->recv_srcadr, xkeyid, 0, 2);
2410 sendlen += crypto_xmit((u_int32 *)&xpkt,
2411 sendlen, code, cookie, associd);
2801 temp32 = CRYPTO_RESP;
2802 rpkt->exten[0] |= htonl(temp32);
2803 sendlen += crypto_xmit(&xpkt,
2804 &rbufp->recv_srcadr, sendlen,
2805 (struct exten *)rpkt->exten, cookie);
2412 } else {
2413 session_key(&rbufp->dstadr->sin,
2414 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2415 }
2416 }
2806 } else {
2807 session_key(&rbufp->dstadr->sin,
2808 &rbufp->recv_srcadr, xkeyid, cookie, 2);
2809 }
2810 }
2417#endif /* AUTOKEY */
2811#endif /* OPENSSL */
2418 get_systime(&xmt_ts);
2419 L_ADD(&xmt_ts, &sys_authdelay);
2420 HTONL_FP(&xmt_ts, &xpkt.xmt);
2421 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2422 sendlen += authlen;
2812 get_systime(&xmt_ts);
2813 L_ADD(&xmt_ts, &sys_authdelay);
2814 HTONL_FP(&xmt_ts, &xpkt.xmt);
2815 authlen = authencrypt(xkeyid, (u_int32 *)&xpkt, sendlen);
2816 sendlen += authlen;
2423#ifdef AUTOKEY
2817#ifdef OPENSSL
2424 if (xkeyid > NTP_MAXKEY)
2425 authtrust(xkeyid, 0);
2818 if (xkeyid > NTP_MAXKEY)
2819 authtrust(xkeyid, 0);
2426#endif /* AUTOKEY */
2820#endif /* OPENSSL */
2427 get_systime(&xmt_tx);
2428 if (sendlen > sizeof(xpkt)) {
2429 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2821 get_systime(&xmt_tx);
2822 if (sendlen > sizeof(xpkt)) {
2823 msyslog(LOG_ERR, "buffer overflow %u", sendlen);
2430 exit(-1);
2824 exit (-1);
2431 }
2432 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2433
2434 /*
2435 * Calculate the encryption delay. Keep the minimum over the
2436 * latest two samples.
2437 */
2438 L_SUB(&xmt_tx, &xmt_ts);

--- 4 unchanged lines hidden (view full) ---

2443 sys_authdelay.l_uf = sys_authdly[0];
2444 else
2445 sys_authdelay.l_uf = sys_authdly[1];
2446#ifdef DEBUG
2447 if (debug)
2448 printf(
2449 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2450 current_time, ntoa(&rbufp->dstadr->sin),
2825 }
2826 sendpkt(&rbufp->recv_srcadr, rbufp->dstadr, 0, &xpkt, sendlen);
2827
2828 /*
2829 * Calculate the encryption delay. Keep the minimum over the
2830 * latest two samples.
2831 */
2832 L_SUB(&xmt_tx, &xmt_ts);

--- 4 unchanged lines hidden (view full) ---

2837 sys_authdelay.l_uf = sys_authdly[0];
2838 else
2839 sys_authdelay.l_uf = sys_authdly[1];
2840#ifdef DEBUG
2841 if (debug)
2842 printf(
2843 "transmit: at %ld %s->%s mode %d keyid %08x len %d mac %d\n",
2844 current_time, ntoa(&rbufp->dstadr->sin),
2451 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen,
2452 authlen);
2845 ntoa(&rbufp->recv_srcadr), xmode, xkeyid, sendlen -
2846 authlen, authlen);
2453#endif
2454}
2455
2456
2847#endif
2848}
2849
2850
2457#ifdef AUTOKEY
2851#ifdef OPENSSL
2458/*
2459 * key_expire - purge the key list
2460 */
2461void
2462key_expire(
2463 struct peer *peer /* peer structure pointer */
2464 )
2465{
2466 int i;
2467
2852/*
2853 * key_expire - purge the key list
2854 */
2855void
2856key_expire(
2857 struct peer *peer /* peer structure pointer */
2858 )
2859{
2860 int i;
2861
2468 if (peer->keylist != NULL) {
2862 if (peer->keylist != NULL) {
2469 for (i = 0; i <= peer->keynumber; i++)
2470 authtrust(peer->keylist[i], 0);
2471 free(peer->keylist);
2472 peer->keylist = NULL;
2473 }
2863 for (i = 0; i <= peer->keynumber; i++)
2864 authtrust(peer->keylist[i], 0);
2865 free(peer->keylist);
2866 peer->keylist = NULL;
2867 }
2474 peer->keynumber = peer->sndauto.seq = 0;
2868 value_free(&peer->sndval);
2869 peer->keynumber = 0;
2475#ifdef DEBUG
2476 if (debug)
2477 printf("key_expire: at %lu\n", current_time);
2478#endif
2479}
2870#ifdef DEBUG
2871 if (debug)
2872 printf("key_expire: at %lu\n", current_time);
2873#endif
2874}
2480#endif /* AUTOKEY */
2875#endif /* OPENSSL */
2481
2876
2877
2482/*
2878/*
2879 * Determine if the peer is unfit for synchronization
2880 *
2881 * A peer is unfit for synchronization if
2882 * > not reachable
2883 * > a synchronization loop would form
2884 * > never been synchronized
2885 * > stratum undefined or too high
2886 * > too long without synchronization
2887 * > designated noselect
2888 */
2889static int /* 0 if no, 1 if yes */
2890peer_unfit(
2891 struct peer *peer /* peer structure pointer */
2892 )
2893{
2894 return (!peer->reach || (peer->stratum > 1 && peer->refid ==
2895 peer->dstadr->addr_refid) || peer->leap == LEAP_NOTINSYNC ||
2896 peer->stratum >= STRATUM_UNSPEC || root_distance(peer) >=
2897 MAXDISTANCE + 2. * clock_phi * ULOGTOD(sys_poll) ||
2898 peer->flags & FLAG_NOSELECT );
2899}
2900
2901
2902/*
2483 * Find the precision of this particular machine
2484 */
2903 * Find the precision of this particular machine
2904 */
2485#define DUSECS 1000000 /* us in a s */
2486#define HUSECS (1 << 20) /* approx DUSECS for shifting etc */
2487#define MINSTEP 5 /* minimum clock increment (us) */
2488#define MAXSTEP 20000 /* maximum clock increment (us) */
2489#define MINLOOPS 5 /* minimum number of step samples */
2905#define MINSTEP 100e-9 /* minimum clock increment (s) */
2906#define MAXSTEP 20e-3 /* maximum clock increment (s) */
2907#define MINLOOPS 5 /* minimum number of step samples */
2490
2491/*
2908
2909/*
2492 * This routine calculates the differences between successive calls to
2493 * gettimeofday(). If a difference is less than zero, the us field
2494 * has rolled over to the next second, so we add a second in us. If
2495 * the difference is greater than zero and less than MINSTEP, the
2496 * clock has been advanced by a small amount to avoid standing still.
2497 * If the clock has advanced by a greater amount, then a timer interrupt
2498 * has occurred and this amount represents the precision of the clock.
2499 * In order to guard against spurious values, which could occur if we
2500 * happen to hit a fat interrupt, we do this for MINLOOPS times and
2501 * keep the minimum value obtained.
2910 * This routine calculates the system precision, defined as the minimum
2911 * of a sequency of differences between successive readings of the
2912 * system clock. However, if the system clock can be read more than once
2913 * during a tick interval, the difference can be zero or one LSB unit,
2914 * where the LSB corresponds to one nanosecond or one microsecond.
2915 * Conceivably, if some other process preempts this one and reads the
2916 * clock, the difference can be more than one LSB unit.
2917 *
2918 * For hardware clock frequencies of 10 MHz or less, we assume the
2919 * logical clock advances only at the hardware clock tick. For higher
2920 * frequencies, we assume the logical clock can advance no more than 100
2921 * nanoseconds between ticks.
2502 */
2503int
2504default_get_precision(void)
2505{
2922 */
2923int
2924default_get_precision(void)
2925{
2506 struct timeval tp;
2507#if !defined(SYS_WINNT) && !defined(VMS) && !defined(_SEQUENT_) && \
2508 !defined(MPE)
2509 struct timezone tzp;
2510#elif defined(VMS) || defined(_SEQUENT_)
2511 struct timezone {
2512 int tz_minuteswest;
2513 int tz_dsttime;
2514 } tzp;
2515#endif /* defined(VMS) || defined(_SEQUENT_) */
2516 long last;
2517 int i;
2518 long diff;
2519 long val;
2520 long usec;
2521#ifdef HAVE_GETCLOCK
2522 struct timespec ts;
2523#endif
2524#if defined(__FreeBSD__) && __FreeBSD__ >= 3
2525 u_long freq;
2526 size_t j;
2926 l_fp val; /* current seconds fraction */
2927 l_fp last; /* last seconds fraction */
2928 l_fp diff; /* difference */
2929 double tick; /* computed tick value */
2930 double dtemp; /* scratch */
2931 int i; /* log2 precision */
2527
2932
2528 /* Try to see if we can find the frequency of of the counter
2529 * which drives our timekeeping
2933 /*
2934 * Loop to find tick value in nanoseconds. Toss out outlyer
2935 * values less than the minimun tick value. In wacky cases, use
2936 * the default maximum value.
2530 */
2937 */
2531 j = sizeof freq;
2532 i = sysctlbyname("kern.timecounter.frequency", &freq, &j , 0,
2533 0);
2534 if (i)
2535 i = sysctlbyname("machdep.tsc_freq", &freq, &j , 0, 0);
2536 if (i)
2537 i = sysctlbyname("machdep.i586_freq", &freq, &j , 0, 0);
2538 if (i)
2539 i = sysctlbyname("machdep.i8254_freq", &freq, &j , 0,
2540 0);
2541 if (!i) {
2542 for (i = 1; freq ; i--)
2543 freq >>= 1;
2544 return (i);
2938 get_systime(&last);
2939 tick = MAXSTEP;
2940 for (i = 0; i < MINLOOPS;) {
2941 get_systime(&val);
2942 diff = val;
2943 L_SUB(&diff, &last);
2944 last = val;
2945 LFPTOD(&diff, dtemp);
2946 if (dtemp < MINSTEP)
2947 continue;
2948 i++;
2949 if (dtemp < tick)
2950 tick = dtemp;
2545 }
2951 }
2546#endif
2547 usec = 0;
2548 val = MAXSTEP;
2549#ifdef HAVE_GETCLOCK
2550 (void) getclock(TIMEOFDAY, &ts);
2551 tp.tv_sec = ts.tv_sec;
2552 tp.tv_usec = ts.tv_nsec / 1000;
2553#else /* not HAVE_GETCLOCK */
2554 GETTIMEOFDAY(&tp, &tzp);
2555#endif /* not HAVE_GETCLOCK */
2556 last = tp.tv_usec;
2557 for (i = 0; i < MINLOOPS && usec < HUSECS;) {
2558#ifdef HAVE_GETCLOCK
2559 (void) getclock(TIMEOFDAY, &ts);
2560 tp.tv_sec = ts.tv_sec;
2561 tp.tv_usec = ts.tv_nsec / 1000;
2562#else /* not HAVE_GETCLOCK */
2563 GETTIMEOFDAY(&tp, &tzp);
2564#endif /* not HAVE_GETCLOCK */
2565 diff = tp.tv_usec - last;
2566 last = tp.tv_usec;
2567 if (diff < 0)
2568 diff += DUSECS;
2569 usec += diff;
2570 if (diff > MINSTEP) {
2571 i++;
2572 if (diff < val)
2573 val = diff;
2574 }
2575 }
2576 NLOG(NLOG_SYSINFO)
2577 msyslog(LOG_INFO, "precision = %ld usec", val);
2578 if (usec >= HUSECS)
2579 val = MINSTEP; /* val <= MINSTEP; fast machine */
2580 diff = HUSECS;
2581 for (i = 0; diff > val; i--)
2582 diff >>= 1;
2583 return (i);
2952
2953 /*
2954 * Find the nearest power of two.
2955 */
2956 NLOG(NLOG_SYSEVENT)
2957 msyslog(LOG_INFO, "precision = %.3f usec", tick * 1e6);
2958 for (i = 0; tick <= 1; i++)
2959 tick *= 2;
2960 if (tick - 1. > 1. - tick / 2)
2961 i--;
2962 return (-i);
2584}
2585
2963}
2964
2965
2586/*
2966/*
2967 * kod_proto - called once per second to limit kiss-of-death packets
2968 */
2969void
2970kod_proto(void)
2971{
2972 sys_kod = sys_kod_rate;
2973}
2974
2975
2976/*
2587 * init_proto - initialize the protocol module's data
2588 */
2589void
2590init_proto(void)
2591{
2977 * init_proto - initialize the protocol module's data
2978 */
2979void
2980init_proto(void)
2981{
2592 l_fp dummy;
2982 l_fp dummy;
2983 int i;
2593
2594 /*
2595 * Fill in the sys_* stuff. Default is don't listen to
2596 * broadcasting, authenticate.
2597 */
2598 sys_leap = LEAP_NOTINSYNC;
2599 sys_stratum = STRATUM_UNSPEC;
2984
2985 /*
2986 * Fill in the sys_* stuff. Default is don't listen to
2987 * broadcasting, authenticate.
2988 */
2989 sys_leap = LEAP_NOTINSYNC;
2990 sys_stratum = STRATUM_UNSPEC;
2991 memcpy(&sys_refid, "INIT", 4);
2600 sys_precision = (s_char)default_get_precision();
2601 sys_jitter = LOGTOD(sys_precision);
2602 sys_rootdelay = 0;
2603 sys_rootdispersion = 0;
2992 sys_precision = (s_char)default_get_precision();
2993 sys_jitter = LOGTOD(sys_precision);
2994 sys_rootdelay = 0;
2995 sys_rootdispersion = 0;
2604 sys_refid = 0;
2605 L_CLR(&sys_reftime);
2606 sys_peer = NULL;
2607 sys_survivors = 0;
2608 get_systime(&dummy);
2996 L_CLR(&sys_reftime);
2997 sys_peer = NULL;
2998 sys_survivors = 0;
2999 get_systime(&dummy);
3000 sys_manycastserver = 0;
2609 sys_bclient = 0;
2610 sys_bdelay = DEFBROADDELAY;
3001 sys_bclient = 0;
3002 sys_bdelay = DEFBROADDELAY;
3003 sys_calldelay = BURST_DELAY;
2611 sys_authenticate = 1;
2612 L_CLR(&sys_authdelay);
2613 sys_authdly[0] = sys_authdly[1] = 0;
2614 sys_stattime = 0;
3004 sys_authenticate = 1;
3005 L_CLR(&sys_authdelay);
3006 sys_authdly[0] = sys_authdly[1] = 0;
3007 sys_stattime = 0;
2615 sys_badstratum = 0;
2616 sys_oldversionpkt = 0;
2617 sys_newversionpkt = 0;
2618 sys_badlength = 0;
2619 sys_unknownversion = 0;
2620 sys_processed = 0;
2621 sys_badauth = 0;
2622 sys_manycastserver = 0;
2623#ifdef AUTOKEY
3008 proto_clr_stats();
3009 for (i = 0; i < MAX_TTL; i++) {
3010 sys_ttl[i] = (u_char)((i * 256) / MAX_TTL);
3011 sys_ttlmax = i;
3012 }
3013#ifdef OPENSSL
2624 sys_automax = 1 << NTP_AUTOMAX;
3014 sys_automax = 1 << NTP_AUTOMAX;
2625#endif /* AUTOKEY */
3015#endif /* OPENSSL */
2626
2627 /*
2628 * Default these to enable
2629 */
2630 ntp_enable = 1;
2631#ifndef KERNEL_FLL_BUG
2632 kern_enable = 1;
2633#endif
2634 pps_enable = 0;
2635 stats_control = 1;
3016
3017 /*
3018 * Default these to enable
3019 */
3020 ntp_enable = 1;
3021#ifndef KERNEL_FLL_BUG
3022 kern_enable = 1;
3023#endif
3024 pps_enable = 0;
3025 stats_control = 1;
2636
2637 /*
2638 * Some system clocks should only be adjusted in 10ms
2639 * increments.
2640 */
2641#if defined RELIANTUNIX_CLOCK
2642 systime_10ms_ticks = 1; /* Reliant UNIX */
2643#elif defined SCO5_CLOCK
2644 if (sys_precision >= (s_char)-10) /* pre-SCO OpenServer 5.0.6 */
2645 systime_10ms_ticks = 1;
2646#endif
2647 if (systime_10ms_ticks)
2648 msyslog(LOG_INFO, "using 10ms tick adjustments");
2649}
2650
2651
2652/*
2653 * proto_config - configure the protocol module
2654 */
2655void
2656proto_config(
3026}
3027
3028
3029/*
3030 * proto_config - configure the protocol module
3031 */
3032void
3033proto_config(
2657 int item,
2658 u_long value,
2659 double dvalue
3034 int item,
3035 u_long value,
3036 double dvalue,
3037 struct sockaddr_storage* svalue
2660 )
2661{
2662 /*
2663 * Figure out what he wants to change, then do it
2664 */
2665 switch (item) {
3038 )
3039{
3040 /*
3041 * Figure out what he wants to change, then do it
3042 */
3043 switch (item) {
2666 case PROTO_KERNEL:
2667
3044
2668 /*
2669 * Turn on/off kernel discipline
2670 */
3045 /*
3046 * Turn on/off kernel discipline.
3047 */
3048 case PROTO_KERNEL:
2671 kern_enable = (int)value;
2672 break;
2673
3049 kern_enable = (int)value;
3050 break;
3051
3052 /*
3053 * Turn on/off clock discipline.
3054 */
2674 case PROTO_NTP:
3055 case PROTO_NTP:
2675
2676 /*
2677 * Turn on/off clock discipline
2678 */
2679 ntp_enable = (int)value;
2680 break;
2681
3056 ntp_enable = (int)value;
3057 break;
3058
3059 /*
3060 * Turn on/off monitoring.
3061 */
2682 case PROTO_MONITOR:
3062 case PROTO_MONITOR:
2683
2684 /*
2685 * Turn on/off monitoring
2686 */
2687 if (value)
2688 mon_start(MON_ON);
2689 else
2690 mon_stop(MON_ON);
2691 break;
2692
3063 if (value)
3064 mon_start(MON_ON);
3065 else
3066 mon_stop(MON_ON);
3067 break;
3068
3069 /*
3070 * Turn on/off statistics.
3071 */
2693 case PROTO_FILEGEN:
3072 case PROTO_FILEGEN:
2694
2695 /*
2696 * Turn on/off statistics
2697 */
2698 stats_control = (int)value;
2699 break;
2700
3073 stats_control = (int)value;
3074 break;
3075
3076 /*
3077 * Turn on/off facility to listen to broadcasts.
3078 */
2701 case PROTO_BROADCLIENT:
3079 case PROTO_BROADCLIENT:
2702
2703 /*
2704 * Turn on/off facility to listen to broadcasts
2705 */
2706 sys_bclient = (int)value;
2707 if (value)
2708 io_setbclient();
2709 else
2710 io_unsetbclient();
2711 break;
2712
3080 sys_bclient = (int)value;
3081 if (value)
3082 io_setbclient();
3083 else
3084 io_unsetbclient();
3085 break;
3086
3087 /*
3088 * Add muliticast group address.
3089 */
2713 case PROTO_MULTICAST_ADD:
3090 case PROTO_MULTICAST_ADD:
2714
2715 /*
2716 * Add muliticast group address
2717 */
2718 io_multicast_add(value);
3091 if (svalue)
3092 io_multicast_add(*svalue);
2719 break;
2720
3093 break;
3094
3095 /*
3096 * Delete multicast group address.
3097 */
2721 case PROTO_MULTICAST_DEL:
3098 case PROTO_MULTICAST_DEL:
2722
2723 /*
2724 * Delete multicast group address
2725 */
2726 io_multicast_del(value);
3099 if (svalue)
3100 io_multicast_del(*svalue);
2727 break;
2728
3101 break;
3102
3103 /*
3104 * Set default broadcast delay.
3105 */
2729 case PROTO_BROADDELAY:
3106 case PROTO_BROADDELAY:
2730
2731 /*
2732 * Set default broadcast delay
2733 */
2734 sys_bdelay = dvalue;
2735 break;
2736
3107 sys_bdelay = dvalue;
3108 break;
3109
2737 case PROTO_AUTHENTICATE:
3110 /*
3111 * Set modem call delay.
3112 */
3113 case PROTO_CALLDELAY:
3114 sys_calldelay = (int)value;
3115 break;
2738
3116
2739 /*
2740 * Specify the use of authenticated data
2741 */
3117 /*
3118 * Require authentication to mobilize ephemeral associations.
3119 */
3120 case PROTO_AUTHENTICATE:
2742 sys_authenticate = (int)value;
2743 break;
2744
3121 sys_authenticate = (int)value;
3122 break;
3123
3124 /*
3125 * Turn on/off PPS discipline.
3126 */
2745 case PROTO_PPS:
3127 case PROTO_PPS:
2746
2747 /*
2748 * Turn on/off PPS discipline
2749 */
2750 pps_enable = (int)value;
2751 break;
2752
3128 pps_enable = (int)value;
3129 break;
3130
3131 /*
3132 * Set the minimum number of survivors.
3133 */
3134 case PROTO_MINCLOCK:
3135 sys_minclock = (int)dvalue;
3136 break;
3137
3138 /*
3139 * Set the minimum number of candidates.
3140 */
3141 case PROTO_MINSANE:
3142 sys_minsane = (int)dvalue;
3143 break;
3144
3145 /*
3146 * Set the stratum floor.
3147 */
3148 case PROTO_FLOOR:
3149 sys_floor = (int)dvalue;
3150 break;
3151
3152 /*
3153 * Set the stratum ceiling.
3154 */
3155 case PROTO_CEILING:
3156 sys_ceiling = (int)dvalue;
3157 break;
3158
3159 /*
3160 * Set the cohort switch.
3161 */
3162 case PROTO_COHORT:
3163 sys_cohort= (int)dvalue;
3164 break;
3165 /*
3166 * Set the adjtime() resolution (s).
3167 */
3168 case PROTO_ADJ:
3169 sys_tick = dvalue;
3170 break;
3171
2753#ifdef REFCLOCK
3172#ifdef REFCLOCK
3173 /*
3174 * Turn on/off refclock calibrate
3175 */
2754 case PROTO_CAL:
3176 case PROTO_CAL:
2755
2756 /*
2757 * Turn on/off refclock calibrate
2758 */
2759 cal_enable = (int)value;
2760 break;
2761#endif
3177 cal_enable = (int)value;
3178 break;
3179#endif
2762
2763 default:
2764
2765 /*
3180 default:
3181
3182 /*
2766 * Log this error
3183 * Log this error.
2767 */
3184 */
2768 msyslog(LOG_ERR,
2769 "proto_config: illegal item %d, value %ld",
3185 msyslog(LOG_INFO,
3186 "proto_config: illegal item %d, value %ld",
2770 item, value);
3187 item, value);
2771 break;
2772 }
2773}
2774
2775
2776/*
2777 * proto_clr_stats - clear protocol stat counters
2778 */
2779void
2780proto_clr_stats(void)
2781{
3188 }
3189}
3190
3191
3192/*
3193 * proto_clr_stats - clear protocol stat counters
3194 */
3195void
3196proto_clr_stats(void)
3197{
2782 sys_badstratum = 0;
2783 sys_oldversionpkt = 0;
3198 sys_stattime = current_time;
3199 sys_received = 0;
3200 sys_processed = 0;
2784 sys_newversionpkt = 0;
3201 sys_newversionpkt = 0;
3202 sys_oldversionpkt = 0;
2785 sys_unknownversion = 0;
3203 sys_unknownversion = 0;
3204 sys_restricted = 0;
2786 sys_badlength = 0;
3205 sys_badlength = 0;
2787 sys_processed = 0;
2788 sys_badauth = 0;
3206 sys_badauth = 0;
2789 sys_stattime = current_time;
2790 sys_limitrejected = 0;
2791}
3207 sys_limitrejected = 0;
3208}