]> git.ipfire.org Git - thirdparty/chrony.git/blob - ntp_core.c
cmdmon: save NTS cookies and server keys on dump command
[thirdparty/chrony.git] / ntp_core.c
1 /*
2 chronyd/chronyc - Programs for keeping computer clocks accurate.
3
4 **********************************************************************
5 * Copyright (C) Richard P. Curnow 1997-2003
6 * Copyright (C) Miroslav Lichvar 2009-2018
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of version 2 of the GNU General Public License as
10 * published by the Free Software Foundation.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 *
21 **********************************************************************
22
23 =======================================================================
24
25 Core NTP protocol engine
26 */
27
28 #include "config.h"
29
30 #include "sysincl.h"
31
32 #include "array.h"
33 #include "ntp_auth.h"
34 #include "ntp_core.h"
35 #include "ntp_io.h"
36 #include "memory.h"
37 #include "sched.h"
38 #include "reference.h"
39 #include "local.h"
40 #include "samplefilt.h"
41 #include "smooth.h"
42 #include "sources.h"
43 #include "util.h"
44 #include "conf.h"
45 #include "logging.h"
46 #include "addrfilt.h"
47 #include "clientlog.h"
48
49 /* ================================================== */
50
51 static LOG_FileID logfileid;
52 static int log_raw_measurements;
53
54 /* ================================================== */
55 /* Enumeration used for remembering the operating mode of one of the
56 sources */
57
58 typedef enum {
59 MD_OFFLINE, /* No sampling at all */
60 MD_ONLINE, /* Normal sampling based on sampling interval */
61 MD_BURST_WAS_OFFLINE, /* Burst sampling, return to offline afterwards */
62 MD_BURST_WAS_ONLINE, /* Burst sampling, return to online afterwards */
63 } OperatingMode;
64
65 /* ================================================== */
66 /* Structure used for holding a single peer/server's
67 protocol machine */
68
69 struct NCR_Instance_Record {
70 NTP_Remote_Address remote_addr; /* Needed for routing transmit packets */
71 NTP_Local_Address local_addr; /* Local address/socket used to send packets */
72 NTP_Mode mode; /* The source's NTP mode
73 (client/server or symmetric active peer) */
74 int interleaved; /* Boolean enabling interleaved NTP mode */
75 OperatingMode opmode; /* Whether we are sampling this source
76 or not and in what way */
77 SCH_TimeoutID rx_timeout_id; /* Timeout ID for latest received response */
78 SCH_TimeoutID tx_timeout_id; /* Timeout ID for next transmission */
79 int tx_suspended; /* Boolean indicating we can't transmit yet */
80
81 int auto_burst; /* If 1, initiate a burst on each poll */
82 int auto_offline; /* If 1, automatically go offline when requests
83 cannot be sent */
84
85 int local_poll; /* Log2 of polling interval at our end */
86 int remote_poll; /* Log2 of server/peer's polling interval (recovered
87 from received packets) */
88 int remote_stratum; /* Stratum of the server/peer (recovered from
89 received packets) */
90
91 int presend_minpoll; /* If the current polling interval is
92 at least this, an extra client packet
93 will be send some time before normal
94 transmit. This ensures that both
95 us and the server/peer have an ARP
96 entry for each other ready, which
97 means our measurement is not
98 botched by an ARP round-trip on one
99 side or the other. */
100
101 int presend_done; /* The presend packet has been sent */
102
103 int minpoll; /* Log2 of minimum defined polling interval */
104 int maxpoll; /* Log2 of maximum defined polling interval */
105
106 int min_stratum; /* Increase stratum in received packets to the
107 minimum */
108
109 int poll_target; /* Target number of sourcestats samples */
110
111 int version; /* Version set in packets for server/peer */
112
113 double poll_score; /* Score of current local poll */
114
115 double max_delay; /* Maximum round-trip delay to the
116 peer that we can tolerate and still
117 use the sample for generating
118 statistics from */
119
120 double max_delay_ratio; /* Largest ratio of delay /
121 min_delay_in_register that we can
122 tolerate. */
123
124 double max_delay_dev_ratio; /* Maximum ratio of increase in delay / stddev */
125
126 double offset_correction; /* Correction applied to measured offset
127 (e.g. for asymmetry in network delay) */
128
129 NAU_Instance auth; /* Authentication */
130
131 /* Count of transmitted packets since last valid response */
132 unsigned int tx_count;
133
134 /* Flag indicating a valid response was received since last request */
135 int valid_rx;
136
137 /* Flag indicating the timestamps below are from a valid packet and may
138 be used for synchronisation */
139 int valid_timestamps;
140
141 /* Receive and transmit timestamps from the last valid response */
142 NTP_int64 remote_ntp_rx;
143 NTP_int64 remote_ntp_tx;
144
145 /* Local timestamp when the last valid response was received from the
146 source. We have to be prepared to tinker with this if the local
147 clock has its frequency adjusted before we repond. The value we
148 store here is what our own local time was when the same arrived.
149 Before replying, we have to correct this to fit with the
150 parameters for the current reference. (It must be stored
151 relative to local time to permit frequency and offset adjustments
152 to be made when we trim the local clock). */
153 NTP_int64 local_ntp_rx;
154 NTP_Local_Timestamp local_rx;
155
156 /* Local timestamp when we last transmitted a packet to the source.
157 We store two versions. The first is in NTP format, and is used
158 to validate the next received packet from the source.
159 Additionally, this is corrected to bring it into line with the
160 current reference. The second is in timespec format, and is kept
161 relative to the local clock. We modify this in accordance with
162 local clock frequency/offset changes, and use this for computing
163 statistics about the source when a return packet arrives. */
164 NTP_int64 local_ntp_tx;
165 NTP_Local_Timestamp local_tx;
166
167 /* Previous values of some variables needed in interleaved mode */
168 NTP_Local_Timestamp prev_local_tx;
169 int prev_local_poll;
170 unsigned int prev_tx_count;
171
172 /* Flag indicating the two timestamps below were updated since the
173 last transmission */
174 int updated_init_timestamps;
175
176 /* Timestamps used for (re)starting the symmetric protocol, when we
177 need to respond to a packet which is not a valid response */
178 NTP_int64 init_remote_ntp_tx;
179 NTP_Local_Timestamp init_local_rx;
180
181 /* The instance record in the main source management module. This
182 performs the statistical analysis on the samples we generate */
183
184 SRC_Instance source;
185
186 /* Optional median filter for NTP measurements */
187 SPF_Instance filter;
188
189 int burst_good_samples_to_go;
190 int burst_total_samples_to_go;
191
192 /* Report from last valid response */
193 RPT_NTPReport report;
194 };
195
196 typedef struct {
197 NTP_Remote_Address addr;
198 NTP_Local_Address local_addr;
199 NAU_Instance auth;
200 int interval;
201 } BroadcastDestination;
202
203 /* Array of BroadcastDestination */
204 static ARR_Instance broadcasts;
205
206 /* ================================================== */
207 /* Initial delay period before first packet is transmitted (in seconds) */
208 #define INITIAL_DELAY 0.2
209
210 /* Spacing required between samples for any two servers/peers (to
211 minimise risk of network collisions) (in seconds) */
212 #define MIN_SAMPLING_SEPARATION 0.002
213 #define MAX_SAMPLING_SEPARATION 0.2
214
215 /* Randomness added to spacing between samples for one server/peer */
216 #define SAMPLING_RANDOMNESS 0.02
217
218 /* Adjustment of the peer polling interval */
219 #define PEER_SAMPLING_ADJ 1.1
220
221 /* Maximum spacing between samples in the burst mode as an absolute
222 value and ratio to the normal polling interval */
223 #define MAX_BURST_INTERVAL 2.0
224 #define MAX_BURST_POLL_RATIO 0.25
225
226 /* Number of samples in initial burst */
227 #define IBURST_GOOD_SAMPLES 4
228 #define IBURST_TOTAL_SAMPLES SOURCE_REACH_BITS
229
230 /* Number of samples in automatic burst */
231 #define BURST_GOOD_SAMPLES 1
232 #define MAX_BURST_TOTAL_SAMPLES 4
233
234 /* Time to wait after sending packet to 'warm up' link */
235 #define WARM_UP_DELAY 2.0
236
237 /* Compatible NTP protocol versions */
238 #define NTP_MAX_COMPAT_VERSION NTP_VERSION
239 #define NTP_MIN_COMPAT_VERSION 1
240
241 /* Maximum allowed dispersion - as defined in RFC 5905 (16 seconds) */
242 #define NTP_MAX_DISPERSION 16.0
243
244 /* Maximum allowed time for server to process client packet */
245 #define MAX_SERVER_INTERVAL 4.0
246
247 /* Maximum acceptable delay in transmission for timestamp correction */
248 #define MAX_TX_DELAY 1.0
249
250 /* Maximum allowed values of maxdelay parameters */
251 #define MAX_MAXDELAY 1.0e3
252 #define MAX_MAXDELAYRATIO 1.0e6
253 #define MAX_MAXDELAYDEVRATIO 1.0e6
254
255 /* Minimum and maximum allowed poll interval */
256 #define MIN_POLL -6
257 #define MAX_POLL 24
258
259 /* Enable sub-second polling intervals only when the peer delay is not
260 longer than 10 milliseconds to restrict them to local networks */
261 #define MIN_NONLAN_POLL 0
262 #define MAX_LAN_PEER_DELAY 0.01
263
264 /* Kiss-o'-Death codes */
265 #define KOD_RATE 0x52415445UL /* RATE */
266
267 /* Maximum poll interval set by KoD RATE */
268 #define MAX_KOD_RATE_POLL SRC_DEFAULT_MAXPOLL
269
270 /* Maximum number of missed responses to accept samples using old timestamps
271 in the interleaved client/server mode */
272 #define MAX_CLIENT_INTERLEAVED_TX 4
273
274 /* Maximum ratio of local intervals in the timestamp selection of the
275 interleaved mode to prefer a sample using previous timestamps */
276 #define MAX_INTERLEAVED_L2L_RATIO 0.1
277
278 /* Invalid socket, different from the one in ntp_io.c */
279 #define INVALID_SOCK_FD -2
280
281 /* ================================================== */
282
283 /* Server IPv4/IPv6 sockets */
284 static int server_sock_fd4;
285 static int server_sock_fd6;
286
287 static ADF_AuthTable access_auth_table;
288
289 /* Characters for printing synchronisation status and timestamping source */
290 static const char leap_chars[4] = {'N', '+', '-', '?'};
291 static const char tss_chars[3] = {'D', 'K', 'H'};
292
293 /* ================================================== */
294 /* Forward prototypes */
295
296 static void transmit_timeout(void *arg);
297 static double get_transmit_delay(NCR_Instance inst, int on_tx, double last_tx);
298 static double get_separation(int poll);
299 static int parse_packet(NTP_Packet *packet, int length, NTP_PacketInfo *info);
300
301 /* ================================================== */
302
303 static void
304 do_size_checks(void)
305 {
306 /* Assertions to check the sizes of certain data types
307 and the positions of certain record fields */
308
309 /* Check that certain invariants are true */
310 assert(sizeof(NTP_int32) == 4);
311 assert(sizeof(NTP_int64) == 8);
312
313 /* Check offsets of all fields in the NTP packet format */
314 assert(offsetof(NTP_Packet, lvm) == 0);
315 assert(offsetof(NTP_Packet, stratum) == 1);
316 assert(offsetof(NTP_Packet, poll) == 2);
317 assert(offsetof(NTP_Packet, precision) == 3);
318 assert(offsetof(NTP_Packet, root_delay) == 4);
319 assert(offsetof(NTP_Packet, root_dispersion) == 8);
320 assert(offsetof(NTP_Packet, reference_id) == 12);
321 assert(offsetof(NTP_Packet, reference_ts) == 16);
322 assert(offsetof(NTP_Packet, originate_ts) == 24);
323 assert(offsetof(NTP_Packet, receive_ts) == 32);
324 assert(offsetof(NTP_Packet, transmit_ts) == 40);
325 }
326
327 /* ================================================== */
328
329 static void
330 do_time_checks(void)
331 {
332 struct timespec now;
333 time_t warning_advance = 3600 * 24 * 365 * 10; /* 10 years */
334
335 #ifdef HAVE_LONG_TIME_T
336 /* Check that time before NTP_ERA_SPLIT underflows correctly */
337
338 struct timespec ts1 = {NTP_ERA_SPLIT, 1}, ts2 = {NTP_ERA_SPLIT - 1, 1};
339 NTP_int64 nts1, nts2;
340 int r;
341
342 UTI_TimespecToNtp64(&ts1, &nts1, NULL);
343 UTI_TimespecToNtp64(&ts2, &nts2, NULL);
344 UTI_Ntp64ToTimespec(&nts1, &ts1);
345 UTI_Ntp64ToTimespec(&nts2, &ts2);
346
347 r = ts1.tv_sec == NTP_ERA_SPLIT &&
348 ts1.tv_sec + (1ULL << 32) - 1 == ts2.tv_sec;
349
350 assert(r);
351
352 LCL_ReadRawTime(&now);
353 if (ts2.tv_sec - now.tv_sec < warning_advance)
354 LOG(LOGS_WARN, "Assumed NTP time ends at %s!", UTI_TimeToLogForm(ts2.tv_sec));
355 #else
356 LCL_ReadRawTime(&now);
357 if (now.tv_sec > 0x7fffffff - warning_advance)
358 LOG(LOGS_WARN, "System time ends at %s!", UTI_TimeToLogForm(0x7fffffff));
359 #endif
360 }
361
362 /* ================================================== */
363
364 static void
365 zero_local_timestamp(NTP_Local_Timestamp *ts)
366 {
367 UTI_ZeroTimespec(&ts->ts);
368 ts->err = 0.0;
369 ts->source = NTP_TS_DAEMON;
370 }
371
372 /* ================================================== */
373
374 void
375 NCR_Initialise(void)
376 {
377 do_size_checks();
378 do_time_checks();
379
380 logfileid = CNF_GetLogMeasurements(&log_raw_measurements) ? LOG_FileOpen("measurements",
381 " Date (UTC) Time IP Address L St 123 567 ABCD LP RP Score Offset Peer del. Peer disp. Root del. Root disp. Refid MTxRx")
382 : -1;
383
384 access_auth_table = ADF_CreateTable();
385 broadcasts = ARR_CreateInstance(sizeof (BroadcastDestination));
386
387 /* Server socket will be opened when access is allowed */
388 server_sock_fd4 = INVALID_SOCK_FD;
389 server_sock_fd6 = INVALID_SOCK_FD;
390 }
391
392 /* ================================================== */
393
394 void
395 NCR_Finalise(void)
396 {
397 unsigned int i;
398
399 if (server_sock_fd4 != INVALID_SOCK_FD)
400 NIO_CloseServerSocket(server_sock_fd4);
401 if (server_sock_fd6 != INVALID_SOCK_FD)
402 NIO_CloseServerSocket(server_sock_fd6);
403
404 for (i = 0; i < ARR_GetSize(broadcasts); i++) {
405 NIO_CloseServerSocket(((BroadcastDestination *)ARR_GetElement(broadcasts, i))->local_addr.sock_fd);
406 NAU_DestroyInstance(((BroadcastDestination *)ARR_GetElement(broadcasts, i))->auth);
407 }
408
409 ARR_DestroyInstance(broadcasts);
410 ADF_DestroyTable(access_auth_table);
411 }
412
413 /* ================================================== */
414
415 static void
416 restart_timeout(NCR_Instance inst, double delay)
417 {
418 /* Check if we can transmit */
419 if (inst->tx_suspended) {
420 assert(!inst->tx_timeout_id);
421 return;
422 }
423
424 /* Stop both rx and tx timers if running */
425 SCH_RemoveTimeout(inst->rx_timeout_id);
426 inst->rx_timeout_id = 0;
427 SCH_RemoveTimeout(inst->tx_timeout_id);
428
429 /* Start new timer for transmission */
430 inst->tx_timeout_id = SCH_AddTimeoutInClass(delay, get_separation(inst->local_poll),
431 SAMPLING_RANDOMNESS,
432 inst->mode == MODE_CLIENT ?
433 SCH_NtpClientClass : SCH_NtpPeerClass,
434 transmit_timeout, (void *)inst);
435 }
436
437 /* ================================================== */
438
439 static void
440 start_initial_timeout(NCR_Instance inst)
441 {
442 double delay, last_tx;
443 struct timespec now;
444
445 if (!inst->tx_timeout_id) {
446 /* This will be the first transmission after mode change */
447
448 /* Mark source active */
449 SRC_SetActive(inst->source);
450 }
451
452 /* In case the offline period was too short, adjust the delay to keep
453 the interval between packets at least as long as the current polling
454 interval */
455 SCH_GetLastEventTime(&now, NULL, NULL);
456 last_tx = UTI_DiffTimespecsToDouble(&now, &inst->local_tx.ts);
457 if (last_tx < 0.0)
458 last_tx = 0.0;
459 delay = get_transmit_delay(inst, 0, 0.0) - last_tx;
460 if (delay < INITIAL_DELAY)
461 delay = INITIAL_DELAY;
462
463 restart_timeout(inst, delay);
464 }
465
466 /* ================================================== */
467
468 static void
469 close_client_socket(NCR_Instance inst)
470 {
471 if (inst->mode == MODE_CLIENT && inst->local_addr.sock_fd != INVALID_SOCK_FD) {
472 NIO_CloseClientSocket(inst->local_addr.sock_fd);
473 inst->local_addr.sock_fd = INVALID_SOCK_FD;
474 }
475
476 SCH_RemoveTimeout(inst->rx_timeout_id);
477 inst->rx_timeout_id = 0;
478 }
479
480 /* ================================================== */
481
482 static void
483 take_offline(NCR_Instance inst)
484 {
485 inst->opmode = MD_OFFLINE;
486
487 SCH_RemoveTimeout(inst->tx_timeout_id);
488 inst->tx_timeout_id = 0;
489
490 /* Mark source unreachable */
491 SRC_ResetReachability(inst->source);
492
493 /* And inactive */
494 SRC_UnsetActive(inst->source);
495
496 close_client_socket(inst);
497
498 NCR_ResetInstance(inst);
499 }
500
501 /* ================================================== */
502
503 NCR_Instance
504 NCR_CreateInstance(NTP_Remote_Address *remote_addr, NTP_Source_Type type,
505 SourceParameters *params, const char *name)
506 {
507 NCR_Instance result;
508
509 result = MallocNew(struct NCR_Instance_Record);
510
511 result->remote_addr = *remote_addr;
512 result->local_addr.ip_addr.family = IPADDR_UNSPEC;
513 result->local_addr.if_index = INVALID_IF_INDEX;
514
515 switch (type) {
516 case NTP_SERVER:
517 /* Client socket will be obtained when sending request */
518 result->local_addr.sock_fd = INVALID_SOCK_FD;
519 result->mode = MODE_CLIENT;
520 break;
521 case NTP_PEER:
522 result->local_addr.sock_fd = NIO_OpenServerSocket(remote_addr);
523 result->mode = MODE_ACTIVE;
524 break;
525 default:
526 assert(0);
527 }
528
529 result->interleaved = params->interleaved;
530
531 result->minpoll = params->minpoll;
532 if (result->minpoll < MIN_POLL)
533 result->minpoll = SRC_DEFAULT_MINPOLL;
534 else if (result->minpoll > MAX_POLL)
535 result->minpoll = MAX_POLL;
536
537 result->maxpoll = params->maxpoll;
538 if (result->maxpoll < MIN_POLL)
539 result->maxpoll = SRC_DEFAULT_MAXPOLL;
540 else if (result->maxpoll > MAX_POLL)
541 result->maxpoll = MAX_POLL;
542 if (result->maxpoll < result->minpoll)
543 result->maxpoll = result->minpoll;
544
545 result->min_stratum = params->min_stratum;
546 if (result->min_stratum >= NTP_MAX_STRATUM)
547 result->min_stratum = NTP_MAX_STRATUM - 1;
548
549 /* Presend doesn't work in symmetric mode */
550 result->presend_minpoll = params->presend_minpoll;
551 if (result->presend_minpoll <= MAX_POLL && result->mode != MODE_CLIENT)
552 result->presend_minpoll = MAX_POLL + 1;
553
554 result->max_delay = CLAMP(0.0, params->max_delay, MAX_MAXDELAY);
555 result->max_delay_ratio = CLAMP(0.0, params->max_delay_ratio, MAX_MAXDELAYRATIO);
556 result->max_delay_dev_ratio = CLAMP(0.0, params->max_delay_dev_ratio, MAX_MAXDELAYDEVRATIO);
557 result->offset_correction = params->offset;
558 result->auto_burst = params->burst;
559 result->auto_offline = params->auto_offline;
560 result->poll_target = params->poll_target;
561
562 if (params->nts) {
563 IPSockAddr nts_address;
564
565 if (result->mode == MODE_ACTIVE)
566 LOG(LOGS_WARN, "NTS not supported with peers");
567
568 nts_address.ip_addr = remote_addr->ip_addr;
569 nts_address.port = params->nts_port;
570
571 result->auth = NAU_CreateNtsInstance(&nts_address, name, &result->remote_addr);
572 } else if (params->authkey != INACTIVE_AUTHKEY) {
573 result->auth = NAU_CreateSymmetricInstance(params->authkey);
574 } else {
575 result->auth = NAU_CreateNoneInstance();
576 }
577
578 result->version = NAU_GetSuggestedNtpVersion(result->auth);
579
580 if (params->version)
581 result->version = CLAMP(NTP_MIN_COMPAT_VERSION, params->version, NTP_VERSION);
582
583 /* Create a source instance for this NTP source */
584 result->source = SRC_CreateNewInstance(UTI_IPToRefid(&remote_addr->ip_addr),
585 SRC_NTP, params->sel_options,
586 &result->remote_addr.ip_addr,
587 params->min_samples, params->max_samples,
588 params->min_delay, params->asymmetry);
589
590 if (params->filter_length >= 1)
591 result->filter = SPF_CreateInstance(params->filter_length, params->filter_length,
592 NTP_MAX_DISPERSION, 0.0);
593 else
594 result->filter = NULL;
595
596 result->rx_timeout_id = 0;
597 result->tx_timeout_id = 0;
598 result->tx_suspended = 1;
599 result->opmode = params->connectivity == SRC_ONLINE ||
600 (params->connectivity == SRC_MAYBE_ONLINE &&
601 NIO_IsServerConnectable(remote_addr)) ? MD_ONLINE : MD_OFFLINE;
602 result->local_poll = result->minpoll;
603 result->poll_score = 0.0;
604 zero_local_timestamp(&result->local_tx);
605 result->burst_good_samples_to_go = 0;
606 result->burst_total_samples_to_go = 0;
607 memset(&result->report, 0, sizeof (result->report));
608
609 NCR_ResetInstance(result);
610
611 if (params->iburst) {
612 NCR_InitiateSampleBurst(result, IBURST_GOOD_SAMPLES, IBURST_TOTAL_SAMPLES);
613 }
614
615 return result;
616 }
617
618 /* ================================================== */
619
620 /* Destroy an instance */
621 void
622 NCR_DestroyInstance(NCR_Instance instance)
623 {
624 if (instance->opmode != MD_OFFLINE)
625 take_offline(instance);
626
627 if (instance->mode == MODE_ACTIVE)
628 NIO_CloseServerSocket(instance->local_addr.sock_fd);
629
630 if (instance->filter)
631 SPF_DestroyInstance(instance->filter);
632
633 NAU_DestroyInstance(instance->auth);
634
635 /* This will destroy the source instance inside the
636 structure, which will cause reselection if this was the
637 synchronising source etc. */
638 SRC_DestroyInstance(instance->source);
639
640 /* Free the data structure */
641 Free(instance);
642 }
643
644 /* ================================================== */
645
646 void
647 NCR_StartInstance(NCR_Instance instance)
648 {
649 instance->tx_suspended = 0;
650 if (instance->opmode != MD_OFFLINE)
651 start_initial_timeout(instance);
652 }
653
654 /* ================================================== */
655
656 void
657 NCR_ResetInstance(NCR_Instance instance)
658 {
659 instance->tx_count = 0;
660 instance->presend_done = 0;
661
662 instance->remote_poll = 0;
663 instance->remote_stratum = 0;
664
665 instance->valid_rx = 0;
666 instance->valid_timestamps = 0;
667 UTI_ZeroNtp64(&instance->remote_ntp_rx);
668 UTI_ZeroNtp64(&instance->remote_ntp_tx);
669 UTI_ZeroNtp64(&instance->local_ntp_rx);
670 UTI_ZeroNtp64(&instance->local_ntp_tx);
671 zero_local_timestamp(&instance->local_rx);
672
673 zero_local_timestamp(&instance->prev_local_tx);
674 instance->prev_local_poll = 0;
675 instance->prev_tx_count = 0;
676
677 instance->updated_init_timestamps = 0;
678 UTI_ZeroNtp64(&instance->init_remote_ntp_tx);
679 zero_local_timestamp(&instance->init_local_rx);
680
681 if (instance->filter)
682 SPF_DropSamples(instance->filter);
683 }
684
685 /* ================================================== */
686
687 void
688 NCR_ResetPoll(NCR_Instance instance)
689 {
690 if (instance->local_poll != instance->minpoll) {
691 instance->local_poll = instance->minpoll;
692
693 /* The timer was set with a longer poll interval, restart it */
694 if (instance->tx_timeout_id)
695 restart_timeout(instance, get_transmit_delay(instance, 0, 0.0));
696 }
697 }
698
699 /* ================================================== */
700
701 void
702 NCR_ChangeRemoteAddress(NCR_Instance inst, NTP_Remote_Address *remote_addr, int ntp_only)
703 {
704 memset(&inst->report, 0, sizeof (inst->report));
705 NCR_ResetInstance(inst);
706
707 /* Update the authentication-specific address before NTP address */
708 if (!ntp_only)
709 NAU_ChangeAddress(inst->auth, &remote_addr->ip_addr);
710
711 inst->remote_addr = *remote_addr;
712
713 if (inst->mode == MODE_CLIENT)
714 close_client_socket(inst);
715 else {
716 NIO_CloseServerSocket(inst->local_addr.sock_fd);
717 inst->local_addr.ip_addr.family = IPADDR_UNSPEC;
718 inst->local_addr.if_index = INVALID_IF_INDEX;
719 inst->local_addr.sock_fd = NIO_OpenServerSocket(remote_addr);
720 }
721
722 /* Update the reference ID and reset the source/sourcestats instances */
723 SRC_SetRefid(inst->source, UTI_IPToRefid(&remote_addr->ip_addr),
724 &inst->remote_addr.ip_addr);
725 SRC_ResetInstance(inst->source);
726 }
727
728 /* ================================================== */
729
730 static void
731 adjust_poll(NCR_Instance inst, double adj)
732 {
733 inst->poll_score += adj;
734
735 if (inst->poll_score >= 1.0) {
736 inst->local_poll += (int)inst->poll_score;
737 inst->poll_score -= (int)inst->poll_score;
738 }
739
740 if (inst->poll_score < 0.0) {
741 inst->local_poll += (int)(inst->poll_score - 1.0);
742 inst->poll_score -= (int)(inst->poll_score - 1.0);
743 }
744
745 /* Clamp polling interval to defined range */
746 if (inst->local_poll < inst->minpoll) {
747 inst->local_poll = inst->minpoll;
748 inst->poll_score = 0;
749 } else if (inst->local_poll > inst->maxpoll) {
750 inst->local_poll = inst->maxpoll;
751 inst->poll_score = 1.0;
752 }
753
754 /* Don't allow a sub-second polling interval if the source is not reachable
755 or it is not in a local network according to the measured delay */
756 if (inst->local_poll < MIN_NONLAN_POLL &&
757 (!SRC_IsReachable(inst->source) ||
758 SST_MinRoundTripDelay(SRC_GetSourcestats(inst->source)) > MAX_LAN_PEER_DELAY))
759 inst->local_poll = MIN_NONLAN_POLL;
760 }
761
762 /* ================================================== */
763
764 static double
765 get_poll_adj(NCR_Instance inst, double error_in_estimate, double peer_distance)
766 {
767 double poll_adj;
768 int samples;
769
770 if (error_in_estimate > peer_distance) {
771 /* If the prediction is not even within +/- the peer distance of the peer,
772 we are clearly not tracking the peer at all well, so we back off the
773 sampling rate depending on just how bad the situation is */
774 poll_adj = -log(error_in_estimate / peer_distance) / log(2.0);
775 } else {
776 samples = SST_Samples(SRC_GetSourcestats(inst->source));
777
778 /* Adjust polling interval so that the number of sourcestats samples
779 remains close to the target value */
780 poll_adj = ((double)samples / inst->poll_target - 1.0) / inst->poll_target;
781
782 /* Make interval shortening quicker */
783 if (samples < inst->poll_target) {
784 poll_adj *= 2.0;
785 }
786 }
787
788 return poll_adj;
789 }
790
791 /* ================================================== */
792
793 static int
794 get_transmit_poll(NCR_Instance inst)
795 {
796 int poll;
797
798 poll = inst->local_poll;
799
800 /* In symmetric mode, if the peer is responding, use shorter of the local
801 and remote poll interval, but not shorter than the minimum */
802 if (inst->mode == MODE_ACTIVE && poll > inst->remote_poll &&
803 SRC_IsReachable(inst->source))
804 poll = MAX(inst->remote_poll, inst->minpoll);
805
806 return poll;
807 }
808
809 /* ================================================== */
810
811 static double
812 get_transmit_delay(NCR_Instance inst, int on_tx, double last_tx)
813 {
814 int poll_to_use, stratum_diff;
815 double delay_time;
816
817 /* If we're in burst mode, queue for immediate dispatch.
818
819 If we're operating in client/server mode, queue the timeout for
820 the poll interval hence. The fact that a timeout has been queued
821 in the transmit handler is immaterial - that is only done so that
822 we at least send something, if no reply is heard.
823
824 If we're in symmetric mode, we have to take account of the peer's
825 wishes, otherwise his sampling regime will fall to pieces. If
826 we're in client/server mode, we don't care what poll interval the
827 server responded with last time. */
828
829 poll_to_use = get_transmit_poll(inst);
830 delay_time = UTI_Log2ToDouble(poll_to_use);
831
832 switch (inst->opmode) {
833 case MD_OFFLINE:
834 assert(0);
835 break;
836 case MD_ONLINE:
837 switch(inst->mode) {
838 case MODE_CLIENT:
839 if (inst->presend_done)
840 delay_time = WARM_UP_DELAY;
841 break;
842
843 case MODE_ACTIVE:
844 /* If the remote stratum is higher than ours, wait a bit for the next
845 packet before responding in order to minimize the delay of the
846 measurement and its error for the peer which has higher stratum.
847 If the remote stratum is equal to ours, try to interleave packets
848 evenly with the peer. */
849 stratum_diff = inst->remote_stratum - REF_GetOurStratum();
850 if ((stratum_diff > 0 && last_tx * PEER_SAMPLING_ADJ < delay_time) ||
851 (!on_tx && !stratum_diff &&
852 last_tx / delay_time > PEER_SAMPLING_ADJ - 0.5))
853 delay_time *= PEER_SAMPLING_ADJ;
854
855 /* Substract the already spend time */
856 if (last_tx > 0.0)
857 delay_time -= last_tx;
858 if (delay_time < 0.0)
859 delay_time = 0.0;
860
861 break;
862 default:
863 assert(0);
864 break;
865 }
866 break;
867
868 case MD_BURST_WAS_ONLINE:
869 case MD_BURST_WAS_OFFLINE:
870 /* Burst modes */
871 delay_time = MIN(MAX_BURST_INTERVAL, MAX_BURST_POLL_RATIO * delay_time);
872 break;
873 default:
874 assert(0);
875 break;
876 }
877
878 return delay_time;
879 }
880
881 /* ================================================== */
882 /* Calculate sampling separation for given polling interval */
883
884 static double
885 get_separation(int poll)
886 {
887 double separation;
888
889 assert(poll >= MIN_POLL && poll <= MAX_POLL);
890
891 /* Allow up to 8 sources using the same short interval to not be limited
892 by the separation */
893 separation = UTI_Log2ToDouble(poll - 3);
894
895 return CLAMP(MIN_SAMPLING_SEPARATION, separation, MAX_SAMPLING_SEPARATION);
896 }
897
898 /* ================================================== */
899 /* Timeout handler for closing the client socket when no acceptable
900 reply can be received from the server */
901
902 static void
903 receive_timeout(void *arg)
904 {
905 NCR_Instance inst = (NCR_Instance)arg;
906
907 DEBUG_LOG("Receive timeout for %s", UTI_IPSockAddrToString(&inst->remote_addr));
908
909 inst->rx_timeout_id = 0;
910 close_client_socket(inst);
911 }
912
913 /* ================================================== */
914
915 static int
916 transmit_packet(NTP_Mode my_mode, /* The mode this machine wants to be */
917 int interleaved, /* Flag enabling interleaved mode */
918 int my_poll, /* The log2 of the local poll interval */
919 int version, /* The NTP version to be set in the packet */
920 uint32_t kod, /* KoD code - 0 disabled */
921 NAU_Instance auth, /* The authentication to be used for the packet */
922 NTP_int64 *remote_ntp_rx, /* The receive timestamp from received packet */
923 NTP_int64 *remote_ntp_tx, /* The transmit timestamp from received packet */
924 NTP_Local_Timestamp *local_rx, /* The RX time of the received packet */
925 NTP_Local_Timestamp *local_tx, /* The TX time of the previous packet
926 RESULT : TX time of this packet */
927 NTP_int64 *local_ntp_rx, /* The receive timestamp from the previous packet
928 RESULT : receive timestamp from this packet */
929 NTP_int64 *local_ntp_tx, /* The transmit timestamp from the previous packet
930 RESULT : transmit timestamp from this packet */
931 NTP_Remote_Address *where_to, /* Where to address the reponse to */
932 NTP_Local_Address *from, /* From what address to send it */
933 NTP_Packet *request, /* The received packet if responding */
934 NTP_PacketInfo *request_info /* and its info */
935 )
936 {
937 NTP_PacketInfo info;
938 NTP_Packet message;
939 struct timespec local_receive, local_transmit;
940 double smooth_offset, local_transmit_err;
941 int ret, precision;
942 NTP_int64 ts_fuzz;
943
944 /* Parameters read from reference module */
945 int are_we_synchronised, our_stratum, smooth_time;
946 NTP_Leap leap_status;
947 uint32_t our_ref_id;
948 struct timespec our_ref_time;
949 double our_root_delay, our_root_dispersion;
950
951 assert(auth || (request && request_info));
952
953 /* Don't reply with version higher than ours */
954 if (version > NTP_VERSION) {
955 version = NTP_VERSION;
956 }
957
958 /* Check if the packet can be formed in the interleaved mode */
959 if (interleaved && (!remote_ntp_rx || !local_tx || UTI_IsZeroTimespec(&local_tx->ts)))
960 interleaved = 0;
961
962 smooth_time = 0;
963 smooth_offset = 0.0;
964
965 if (my_mode == MODE_CLIENT) {
966 /* Don't reveal local time or state of the clock in client packets */
967 precision = 32;
968 leap_status = our_stratum = our_ref_id = 0;
969 our_root_delay = our_root_dispersion = 0.0;
970 UTI_ZeroTimespec(&our_ref_time);
971 } else {
972 /* This is accurate enough and cheaper than calling LCL_ReadCookedTime.
973 A more accurate timestamp will be taken later in this function. */
974 SCH_GetLastEventTime(&local_transmit, NULL, NULL);
975
976 REF_GetReferenceParams(&local_transmit,
977 &are_we_synchronised, &leap_status,
978 &our_stratum,
979 &our_ref_id, &our_ref_time,
980 &our_root_delay, &our_root_dispersion);
981
982 /* Get current smoothing offset when sending packet to a client */
983 if (SMT_IsEnabled() && (my_mode == MODE_SERVER || my_mode == MODE_BROADCAST)) {
984 smooth_offset = SMT_GetOffset(&local_transmit);
985 smooth_time = fabs(smooth_offset) > LCL_GetSysPrecisionAsQuantum();
986
987 /* Suppress leap second when smoothing and slew mode are enabled */
988 if (REF_GetLeapMode() == REF_LeapModeSlew &&
989 (leap_status == LEAP_InsertSecond || leap_status == LEAP_DeleteSecond))
990 leap_status = LEAP_Normal;
991 }
992
993 precision = LCL_GetSysPrecisionAsLog();
994 }
995
996 if (smooth_time && !UTI_IsZeroTimespec(&local_rx->ts)) {
997 our_ref_id = NTP_REFID_SMOOTH;
998 UTI_AddDoubleToTimespec(&our_ref_time, smooth_offset, &our_ref_time);
999 UTI_AddDoubleToTimespec(&local_rx->ts, smooth_offset, &local_receive);
1000 } else {
1001 local_receive = local_rx->ts;
1002 }
1003
1004 if (kod != 0) {
1005 leap_status = LEAP_Unsynchronised;
1006 our_stratum = NTP_INVALID_STRATUM;
1007 our_ref_id = kod;
1008 }
1009
1010 /* Generate transmit packet */
1011 message.lvm = NTP_LVM(leap_status, version, my_mode);
1012 /* Stratum 16 and larger are invalid */
1013 if (our_stratum < NTP_MAX_STRATUM) {
1014 message.stratum = our_stratum;
1015 } else {
1016 message.stratum = NTP_INVALID_STRATUM;
1017 }
1018
1019 message.poll = my_poll;
1020 message.precision = precision;
1021
1022 /* If we're sending a client mode packet and we aren't synchronized yet,
1023 we might have to set up artificial values for some of these parameters */
1024 message.root_delay = UTI_DoubleToNtp32(our_root_delay);
1025 message.root_dispersion = UTI_DoubleToNtp32(our_root_dispersion);
1026
1027 message.reference_id = htonl(our_ref_id);
1028
1029 /* Now fill in timestamps */
1030
1031 UTI_TimespecToNtp64(&our_ref_time, &message.reference_ts, NULL);
1032
1033 /* Don't reveal timestamps which are not necessary for the protocol */
1034
1035 if (my_mode != MODE_CLIENT || interleaved) {
1036 /* Originate - this comes from the last packet the source sent us */
1037 message.originate_ts = interleaved ? *remote_ntp_rx : *remote_ntp_tx;
1038
1039 do {
1040 /* Prepare random bits which will be added to the receive timestamp */
1041 UTI_GetNtp64Fuzz(&ts_fuzz, precision);
1042
1043 /* Receive - this is when we received the last packet from the source.
1044 This timestamp will have been adjusted so that it will now look to
1045 the source like we have been running on our latest estimate of
1046 frequency all along */
1047 UTI_TimespecToNtp64(&local_receive, &message.receive_ts, &ts_fuzz);
1048
1049 /* Do not send a packet with a non-zero receive timestamp equal to the
1050 originate timestamp or previous receive timestamp */
1051 } while (!UTI_IsZeroNtp64(&message.receive_ts) &&
1052 UTI_IsEqualAnyNtp64(&message.receive_ts, &message.originate_ts,
1053 local_ntp_rx, NULL));
1054 } else {
1055 UTI_ZeroNtp64(&message.originate_ts);
1056 UTI_ZeroNtp64(&message.receive_ts);
1057 }
1058
1059 do {
1060 if (!parse_packet(&message, NTP_HEADER_LENGTH, &info))
1061 return 0;
1062
1063 /* Prepare random bits which will be added to the transmit timestamp */
1064 UTI_GetNtp64Fuzz(&ts_fuzz, precision);
1065
1066 /* Transmit - this our local time right now! Also, we might need to
1067 store this for our own use later, next time we receive a message
1068 from the source we're sending to now. */
1069 LCL_ReadCookedTime(&local_transmit, &local_transmit_err);
1070
1071 if (smooth_time)
1072 UTI_AddDoubleToTimespec(&local_transmit, smooth_offset, &local_transmit);
1073
1074 /* Pre-compensate the transmit time by approximately how long it will take
1075 to generate the authentication data */
1076 if (auth)
1077 NAU_AdjustRequestTimestamp(auth, &local_transmit);
1078 else
1079 NAU_AdjustResponseTimestamp(request, request_info, &local_transmit);
1080
1081 UTI_TimespecToNtp64(interleaved ? &local_tx->ts : &local_transmit,
1082 &message.transmit_ts, &ts_fuzz);
1083
1084 /* Generate the authentication data */
1085 if (auth) {
1086 if (!NAU_GenerateRequestAuth(auth, &message, &info)) {
1087 DEBUG_LOG("Could not generate request auth");
1088 return 0;
1089 }
1090 } else {
1091 if (!NAU_GenerateResponseAuth(request, request_info, &message, &info,
1092 where_to, from, kod)) {
1093 DEBUG_LOG("Could not generate response auth");
1094 return 0;
1095 }
1096 }
1097
1098 /* Do not send a packet with a non-zero transmit timestamp which is
1099 equal to any of the following timestamps:
1100 - receive (to allow reliable detection of the interleaved mode)
1101 - originate (to prevent the packet from being its own valid response
1102 in the symmetric mode)
1103 - previous transmit (to invalidate responses to the previous packet)
1104 (the precision must be at least -30 to prevent an infinite loop!) */
1105 } while (!UTI_IsZeroNtp64(&message.transmit_ts) &&
1106 UTI_IsEqualAnyNtp64(&message.transmit_ts, &message.receive_ts,
1107 &message.originate_ts, local_ntp_tx));
1108
1109 if (request_info && request_info->length < info.length) {
1110 DEBUG_LOG("Response longer than request req_len=%d res_len=%d",
1111 request_info->length, info.length);
1112 return 0;
1113 }
1114
1115 ret = NIO_SendPacket(&message, where_to, from, info.length, local_tx != NULL);
1116
1117 if (local_tx) {
1118 local_tx->ts = local_transmit;
1119 local_tx->err = local_transmit_err;
1120 local_tx->source = NTP_TS_DAEMON;
1121 }
1122
1123 if (local_ntp_rx)
1124 *local_ntp_rx = message.receive_ts;
1125 if (local_ntp_tx)
1126 *local_ntp_tx = message.transmit_ts;
1127
1128 return ret;
1129 }
1130
1131 /* ================================================== */
1132 /* Timeout handler for transmitting to a source. */
1133
1134 static void
1135 transmit_timeout(void *arg)
1136 {
1137 NCR_Instance inst = (NCR_Instance) arg;
1138 NTP_Local_Address local_addr;
1139 int interleaved, initial, sent;
1140
1141 inst->tx_timeout_id = 0;
1142
1143 switch (inst->opmode) {
1144 case MD_BURST_WAS_ONLINE:
1145 /* With online burst switch to online before last packet */
1146 if (inst->burst_total_samples_to_go <= 1)
1147 inst->opmode = MD_ONLINE;
1148 break;
1149 case MD_BURST_WAS_OFFLINE:
1150 if (inst->burst_total_samples_to_go <= 0)
1151 take_offline(inst);
1152 break;
1153 case MD_ONLINE:
1154 /* Start a new burst if the burst option is enabled and the average
1155 polling interval including the burst will not fall below the
1156 minimum polling interval */
1157 if (inst->auto_burst && inst->local_poll > inst->minpoll)
1158 NCR_InitiateSampleBurst(inst, BURST_GOOD_SAMPLES,
1159 MIN(1 << (inst->local_poll - inst->minpoll),
1160 MAX_BURST_TOTAL_SAMPLES));
1161 break;
1162 default:
1163 break;
1164 }
1165
1166 if (inst->opmode == MD_OFFLINE) {
1167 return;
1168 }
1169
1170 DEBUG_LOG("Transmit timeout for %s", UTI_IPSockAddrToString(&inst->remote_addr));
1171
1172 /* Prepare authentication */
1173 if (!NAU_PrepareRequestAuth(inst->auth)) {
1174 if (inst->burst_total_samples_to_go > 0)
1175 inst->burst_total_samples_to_go--;
1176 adjust_poll(inst, 0.25);
1177 SRC_UpdateReachability(inst->source, 0);
1178 restart_timeout(inst, get_transmit_delay(inst, 1, 0.0));
1179 return;
1180 }
1181
1182 /* Open new client socket */
1183 if (inst->mode == MODE_CLIENT) {
1184 close_client_socket(inst);
1185 assert(inst->local_addr.sock_fd == INVALID_SOCK_FD);
1186 inst->local_addr.sock_fd = NIO_OpenClientSocket(&inst->remote_addr);
1187 }
1188
1189 /* Don't require the packet to be sent from the same address as before */
1190 local_addr.ip_addr.family = IPADDR_UNSPEC;
1191 local_addr.if_index = INVALID_IF_INDEX;
1192 local_addr.sock_fd = inst->local_addr.sock_fd;
1193
1194 /* In symmetric mode, don't send a packet in interleaved mode unless it
1195 is the first response to the last valid request received from the peer
1196 and there was just one response to the previous valid request. This
1197 prevents the peer from matching the transmit timestamp with an older
1198 response if it can't detect missed responses. In client mode, which has
1199 at most one response per request, check how many responses are missing to
1200 prevent the server from responding with a very old transmit timestamp. */
1201 interleaved = inst->interleaved &&
1202 ((inst->mode == MODE_CLIENT &&
1203 inst->tx_count < MAX_CLIENT_INTERLEAVED_TX) ||
1204 (inst->mode == MODE_ACTIVE &&
1205 inst->prev_tx_count == 1 && inst->tx_count == 0));
1206
1207 /* In symmetric mode, if no valid response was received since the previous
1208 transmission, respond to the last received packet even if it failed some
1209 specific NTP tests. This is necessary for starting and restarting the
1210 protocol, e.g. when a packet was lost. */
1211 initial = inst->mode == MODE_ACTIVE && !inst->valid_rx &&
1212 !UTI_IsZeroNtp64(&inst->init_remote_ntp_tx);
1213
1214 /* Prepare for the response */
1215 inst->valid_rx = 0;
1216 inst->updated_init_timestamps = 0;
1217 if (initial)
1218 inst->valid_timestamps = 0;
1219
1220 /* Check whether we need to 'warm up' the link to the other end by
1221 sending an NTP exchange to ensure both ends' ARP caches are
1222 primed or whether we need to send two packets first to ensure a
1223 server in the interleaved mode has a fresh timestamp for us. */
1224 if (inst->presend_minpoll <= inst->local_poll && !inst->presend_done &&
1225 !inst->burst_total_samples_to_go) {
1226 inst->presend_done = interleaved ? 2 : 1;
1227 } else if (inst->presend_done > 0) {
1228 inst->presend_done--;
1229 }
1230
1231 /* Send the request (which may also be a response in the symmetric mode) */
1232 sent = transmit_packet(inst->mode, interleaved, inst->local_poll, inst->version, 0,
1233 inst->auth,
1234 initial ? NULL : &inst->remote_ntp_rx,
1235 initial ? &inst->init_remote_ntp_tx : &inst->remote_ntp_tx,
1236 initial ? &inst->init_local_rx : &inst->local_rx,
1237 &inst->local_tx, &inst->local_ntp_rx, &inst->local_ntp_tx,
1238 &inst->remote_addr, &local_addr, NULL, NULL);
1239
1240 ++inst->tx_count;
1241 if (sent)
1242 inst->report.total_tx_count++;
1243
1244 /* If the source loses connectivity and our packets are still being sent,
1245 back off the sampling rate to reduce the network traffic. If it's the
1246 source to which we are currently locked, back off slowly. */
1247
1248 if (inst->tx_count >= 2) {
1249 /* Implies we have missed at least one transmission */
1250
1251 if (sent) {
1252 adjust_poll(inst, SRC_IsSyncPeer(inst->source) ? 0.1 : 0.25);
1253 }
1254
1255 SRC_UpdateReachability(inst->source, 0);
1256 }
1257
1258 /* With auto_offline take the source offline if sending failed */
1259 if (!sent && inst->auto_offline)
1260 NCR_SetConnectivity(inst, SRC_OFFLINE);
1261
1262 switch (inst->opmode) {
1263 case MD_BURST_WAS_ONLINE:
1264 /* When not reachable, don't stop online burst until sending succeeds */
1265 if (!sent && !SRC_IsReachable(inst->source))
1266 break;
1267 /* Fall through */
1268 case MD_BURST_WAS_OFFLINE:
1269 --inst->burst_total_samples_to_go;
1270 break;
1271 case MD_OFFLINE:
1272 return;
1273 default:
1274 break;
1275 }
1276
1277 /* Restart timer for this message */
1278 restart_timeout(inst, get_transmit_delay(inst, 1, 0.0));
1279
1280 /* If a client packet was just sent, schedule a timeout to close the socket
1281 at the time when all server replies would fail the delay test, so the
1282 socket is not open for longer than necessary */
1283 if (inst->mode == MODE_CLIENT)
1284 inst->rx_timeout_id = SCH_AddTimeoutByDelay(inst->max_delay + MAX_SERVER_INTERVAL,
1285 receive_timeout, (void *)inst);
1286 }
1287
1288 /* ================================================== */
1289
1290 static int
1291 parse_packet(NTP_Packet *packet, int length, NTP_PacketInfo *info)
1292 {
1293 if (length < NTP_HEADER_LENGTH || length % 4U != 0) {
1294 DEBUG_LOG("NTP packet has invalid length %d", length);
1295 return 0;
1296 }
1297
1298 info->length = length;
1299 info->version = NTP_LVM_TO_VERSION(packet->lvm);
1300 info->mode = NTP_LVM_TO_MODE(packet->lvm);
1301 info->ext_fields = 0;
1302 info->auth.mode = NTP_AUTH_NONE;
1303
1304 if (info->version < NTP_MIN_COMPAT_VERSION || info->version > NTP_MAX_COMPAT_VERSION) {
1305 DEBUG_LOG("NTP packet has invalid version %d", info->version);
1306 return 0;
1307 }
1308
1309 /* Parse authentication extension fields or MAC */
1310 if (!NAU_ParsePacket(packet, info))
1311 return 0;
1312
1313 return 1;
1314 }
1315
1316 /* ================================================== */
1317
1318 static int
1319 check_delay_ratio(NCR_Instance inst, SST_Stats stats,
1320 struct timespec *sample_time, double delay)
1321 {
1322 double last_sample_ago, predicted_offset, min_delay, skew, std_dev;
1323 double max_delay;
1324
1325 if (inst->max_delay_ratio < 1.0 ||
1326 !SST_GetDelayTestData(stats, sample_time, &last_sample_ago,
1327 &predicted_offset, &min_delay, &skew, &std_dev))
1328 return 1;
1329
1330 max_delay = min_delay * inst->max_delay_ratio +
1331 last_sample_ago * (skew + LCL_GetMaxClockError());
1332
1333 if (delay <= max_delay)
1334 return 1;
1335
1336 DEBUG_LOG("maxdelayratio: delay=%e max_delay=%e", delay, max_delay);
1337 return 0;
1338 }
1339
1340 /* ================================================== */
1341
1342 static int
1343 check_delay_dev_ratio(NCR_Instance inst, SST_Stats stats,
1344 struct timespec *sample_time, double offset, double delay)
1345 {
1346 double last_sample_ago, predicted_offset, min_delay, skew, std_dev;
1347 double delta, max_delta, error_in_estimate;
1348
1349 if (!SST_GetDelayTestData(stats, sample_time, &last_sample_ago,
1350 &predicted_offset, &min_delay, &skew, &std_dev))
1351 return 1;
1352
1353 /* Require that the ratio of the increase in delay from the minimum to the
1354 standard deviation is less than max_delay_dev_ratio. In the allowed
1355 increase in delay include also dispersion. */
1356
1357 max_delta = std_dev * inst->max_delay_dev_ratio +
1358 last_sample_ago * (skew + LCL_GetMaxClockError());
1359 delta = (delay - min_delay) / 2.0;
1360
1361 if (delta <= max_delta)
1362 return 1;
1363
1364 error_in_estimate = offset + predicted_offset;
1365
1366 /* Before we decide to drop the sample, make sure the difference between
1367 measured offset and predicted offset is not significantly larger than
1368 the increase in delay */
1369 if (fabs(error_in_estimate) - delta > max_delta)
1370 return 1;
1371
1372 DEBUG_LOG("maxdelaydevratio: error=%e delay=%e delta=%e max_delta=%e",
1373 error_in_estimate, delay, delta, max_delta);
1374 return 0;
1375 }
1376
1377 /* ================================================== */
1378
1379 static int
1380 check_sync_loop(NCR_Instance inst, NTP_Packet *message, NTP_Local_Address *local_addr,
1381 struct timespec *local_ts)
1382 {
1383 double our_root_delay, our_root_dispersion;
1384 int are_we_synchronised, our_stratum;
1385 struct timespec our_ref_time;
1386 NTP_Leap leap_status;
1387 uint32_t our_ref_id;
1388
1389 /* Check if a server socket is open, i.e. a client or peer can actually
1390 be synchronised to us */
1391 if (!NIO_IsServerSocketOpen())
1392 return 1;
1393
1394 /* Check if the source indicates that it is synchronised to our address
1395 (assuming it uses the same address as the one from which we send requests
1396 to the source) */
1397 if (message->stratum > 1 &&
1398 message->reference_id == htonl(UTI_IPToRefid(&local_addr->ip_addr)))
1399 return 0;
1400
1401 /* Compare our reference data with the source to make sure it is not us
1402 (e.g. due to a misconfiguration) */
1403
1404 REF_GetReferenceParams(local_ts, &are_we_synchronised, &leap_status, &our_stratum,
1405 &our_ref_id, &our_ref_time, &our_root_delay, &our_root_dispersion);
1406
1407 if (message->stratum == our_stratum &&
1408 message->reference_id == htonl(our_ref_id) &&
1409 message->root_delay == UTI_DoubleToNtp32(our_root_delay) &&
1410 !UTI_IsZeroNtp64(&message->reference_ts)) {
1411 NTP_int64 ntp_ref_time;
1412
1413 UTI_TimespecToNtp64(&our_ref_time, &ntp_ref_time, NULL);
1414 if (UTI_CompareNtp64(&message->reference_ts, &ntp_ref_time) == 0) {
1415 DEBUG_LOG("Source %s is me", UTI_IPToString(&inst->remote_addr.ip_addr));
1416 return 0;
1417 }
1418 }
1419
1420 return 1;
1421 }
1422
1423 /* ================================================== */
1424
1425 static void
1426 process_sample(NCR_Instance inst, NTP_Sample *sample)
1427 {
1428 double estimated_offset, error_in_estimate, filtered_sample_ago;
1429 NTP_Sample filtered_sample;
1430 int filtered_samples;
1431
1432 /* Accumulate the sample to the median filter if it is enabled. When the
1433 filter produces a result, check if it is not too old, i.e. the filter did
1434 not miss too many samples due to missing responses or failing tests. */
1435 if (inst->filter) {
1436 SPF_AccumulateSample(inst->filter, sample);
1437
1438 filtered_samples = SPF_GetNumberOfSamples(inst->filter);
1439
1440 if (!SPF_GetFilteredSample(inst->filter, &filtered_sample))
1441 return;
1442
1443 filtered_sample_ago = UTI_DiffTimespecsToDouble(&sample->time, &filtered_sample.time);
1444
1445 if (filtered_sample_ago > SOURCE_REACH_BITS / 2 * filtered_samples *
1446 UTI_Log2ToDouble(inst->local_poll)) {
1447 DEBUG_LOG("filtered sample dropped ago=%f poll=%d", filtered_sample_ago,
1448 inst->local_poll);
1449 return;
1450 }
1451
1452 sample = &filtered_sample;
1453 }
1454
1455 /* Get the estimated offset predicted from previous samples. The
1456 convention here is that positive means local clock FAST of
1457 reference, i.e. backwards to the way that 'offset' is defined. */
1458 estimated_offset = SST_PredictOffset(SRC_GetSourcestats(inst->source), &sample->time);
1459
1460 error_in_estimate = fabs(-sample->offset - estimated_offset);
1461
1462 SRC_AccumulateSample(inst->source, sample);
1463 SRC_SelectSource(inst->source);
1464
1465 adjust_poll(inst, get_poll_adj(inst, error_in_estimate,
1466 sample->peer_dispersion + 0.5 * sample->peer_delay));
1467 }
1468
1469 /* ================================================== */
1470
1471 static int
1472 process_response(NCR_Instance inst, NTP_Local_Address *local_addr,
1473 NTP_Local_Timestamp *rx_ts, NTP_Packet *message, NTP_PacketInfo *info)
1474 {
1475 NTP_Sample sample;
1476 SST_Stats stats;
1477
1478 int pkt_leap, pkt_version;
1479 uint32_t pkt_refid;
1480 double pkt_root_delay;
1481 double pkt_root_dispersion;
1482
1483 /* The skew and estimated frequency offset relative to the remote source */
1484 double skew, source_freq_lo, source_freq_hi;
1485
1486 /* RFC 5905 packet tests */
1487 int test1, test2n, test2i, test2, test3, test5, test6, test7;
1488 int interleaved_packet, valid_packet, synced_packet;
1489
1490 /* Additional tests */
1491 int testA, testB, testC, testD;
1492 int good_packet;
1493
1494 /* Kiss-o'-Death codes */
1495 int kod_rate;
1496
1497 NTP_Local_Timestamp local_receive, local_transmit;
1498 double remote_interval, local_interval, response_time;
1499 double delay_time, precision;
1500 int updated_timestamps;
1501
1502 /* ==================== */
1503
1504 stats = SRC_GetSourcestats(inst->source);
1505
1506 pkt_leap = NTP_LVM_TO_LEAP(message->lvm);
1507 pkt_version = NTP_LVM_TO_VERSION(message->lvm);
1508 pkt_refid = ntohl(message->reference_id);
1509 pkt_root_delay = UTI_Ntp32ToDouble(message->root_delay);
1510 pkt_root_dispersion = UTI_Ntp32ToDouble(message->root_dispersion);
1511
1512 /* Check if the packet is valid per RFC 5905, section 8.
1513 The test values are 1 when passed and 0 when failed. */
1514
1515 /* Test 1 checks for duplicate packet */
1516 test1 = UTI_CompareNtp64(&message->receive_ts, &inst->remote_ntp_rx) ||
1517 UTI_CompareNtp64(&message->transmit_ts, &inst->remote_ntp_tx);
1518
1519 /* Test 2 checks for bogus packet in the basic and interleaved modes. This
1520 ensures the source is responding to the latest packet we sent to it. */
1521 test2n = !UTI_CompareNtp64(&message->originate_ts, &inst->local_ntp_tx);
1522 test2i = inst->interleaved &&
1523 !UTI_CompareNtp64(&message->originate_ts, &inst->local_ntp_rx);
1524 test2 = test2n || test2i;
1525 interleaved_packet = !test2n && test2i;
1526
1527 /* Test 3 checks for invalid timestamps. This can happen when the
1528 association if not properly 'up'. */
1529 test3 = !UTI_IsZeroNtp64(&message->originate_ts) &&
1530 !UTI_IsZeroNtp64(&message->receive_ts) &&
1531 !UTI_IsZeroNtp64(&message->transmit_ts);
1532
1533 /* Test 4 would check for denied access. It would always pass as this
1534 function is called only for known sources. */
1535
1536 /* Test 5 checks for authentication failure */
1537 test5 = NAU_CheckResponseAuth(inst->auth, message, info);
1538
1539 /* Test 6 checks for unsynchronised server */
1540 test6 = pkt_leap != LEAP_Unsynchronised &&
1541 message->stratum < NTP_MAX_STRATUM &&
1542 message->stratum != NTP_INVALID_STRATUM;
1543
1544 /* Test 7 checks for bad data. The root distance must be smaller than a
1545 defined maximum. */
1546 test7 = pkt_root_delay / 2.0 + pkt_root_dispersion < NTP_MAX_DISPERSION;
1547
1548 /* The packet is considered valid if the tests 1-5 passed. The timestamps
1549 can be used for synchronisation if the tests 6 and 7 passed too. */
1550 valid_packet = test1 && test2 && test3 && test5;
1551 synced_packet = valid_packet && test6 && test7;
1552
1553 /* Check for Kiss-o'-Death codes */
1554 kod_rate = 0;
1555 if (test1 && test2 && test5 && pkt_leap == LEAP_Unsynchronised &&
1556 message->stratum == NTP_INVALID_STRATUM) {
1557 if (pkt_refid == KOD_RATE)
1558 kod_rate = 1;
1559 }
1560
1561 if (synced_packet && (!interleaved_packet || inst->valid_timestamps)) {
1562 /* These are the timespec equivalents of the remote and local epochs */
1563 struct timespec remote_receive, remote_transmit, remote_request_receive;
1564 struct timespec local_average, remote_average, prev_remote_transmit;
1565 double prev_remote_poll_interval;
1566
1567 /* Select remote and local timestamps for the new sample */
1568 if (interleaved_packet) {
1569 /* Prefer previous local TX and remote RX timestamps if it will make
1570 the intervals significantly shorter in order to improve the accuracy
1571 of the measured delay */
1572 if (!UTI_IsZeroTimespec(&inst->prev_local_tx.ts) &&
1573 MAX_INTERLEAVED_L2L_RATIO *
1574 UTI_DiffTimespecsToDouble(&inst->local_tx.ts, &inst->local_rx.ts) >
1575 UTI_DiffTimespecsToDouble(&inst->local_rx.ts, &inst->prev_local_tx.ts)) {
1576 UTI_Ntp64ToTimespec(&inst->remote_ntp_rx, &remote_receive);
1577 remote_request_receive = remote_receive;
1578 local_transmit = inst->prev_local_tx;
1579 } else {
1580 UTI_Ntp64ToTimespec(&message->receive_ts, &remote_receive);
1581 UTI_Ntp64ToTimespec(&inst->remote_ntp_rx, &remote_request_receive);
1582 local_transmit = inst->local_tx;
1583 }
1584 UTI_Ntp64ToTimespec(&message->transmit_ts, &remote_transmit);
1585 UTI_Ntp64ToTimespec(&inst->remote_ntp_tx, &prev_remote_transmit);
1586 local_receive = inst->local_rx;
1587 } else {
1588 UTI_Ntp64ToTimespec(&message->receive_ts, &remote_receive);
1589 UTI_Ntp64ToTimespec(&message->transmit_ts, &remote_transmit);
1590 UTI_ZeroTimespec(&prev_remote_transmit);
1591 remote_request_receive = remote_receive;
1592 local_receive = *rx_ts;
1593 local_transmit = inst->local_tx;
1594 }
1595
1596 /* Calculate intervals between remote and local timestamps */
1597 UTI_AverageDiffTimespecs(&remote_receive, &remote_transmit,
1598 &remote_average, &remote_interval);
1599 UTI_AverageDiffTimespecs(&local_transmit.ts, &local_receive.ts,
1600 &local_average, &local_interval);
1601 response_time = fabs(UTI_DiffTimespecsToDouble(&remote_transmit,
1602 &remote_request_receive));
1603
1604 precision = LCL_GetSysPrecisionAsQuantum() + UTI_Log2ToDouble(message->precision);
1605
1606 /* Calculate delay */
1607 sample.peer_delay = fabs(local_interval - remote_interval);
1608 if (sample.peer_delay < precision)
1609 sample.peer_delay = precision;
1610
1611 /* Calculate offset. Following the NTP definition, this is negative
1612 if we are fast of the remote source. */
1613 sample.offset = UTI_DiffTimespecsToDouble(&remote_average, &local_average);
1614
1615 /* Apply configured correction */
1616 sample.offset += inst->offset_correction;
1617
1618 /* We treat the time of the sample as being midway through the local
1619 measurement period. An analysis assuming constant relative
1620 frequency and zero network delay shows this is the only possible
1621 choice to estimate the frequency difference correctly for every
1622 sample pair. */
1623 sample.time = local_average;
1624
1625 SST_GetFrequencyRange(stats, &source_freq_lo, &source_freq_hi);
1626
1627 /* Calculate skew */
1628 skew = (source_freq_hi - source_freq_lo) / 2.0;
1629
1630 /* and then calculate peer dispersion */
1631 sample.peer_dispersion = MAX(precision, MAX(local_transmit.err, local_receive.err)) +
1632 skew * fabs(local_interval);
1633
1634 /* If the source is an active peer, this is the minimum assumed interval
1635 between previous two transmissions (if not constrained by minpoll) */
1636 prev_remote_poll_interval = UTI_Log2ToDouble(MIN(inst->remote_poll,
1637 inst->prev_local_poll));
1638
1639 /* Additional tests required to pass before accumulating the sample */
1640
1641 /* Test A requires that the minimum estimate of the peer delay is not
1642 larger than the configured maximum, in both client modes that the server
1643 processing time is sane, and in interleaved symmetric mode that the
1644 measured delay and intervals between remote timestamps don't indicate
1645 a missed response */
1646 testA = sample.peer_delay - sample.peer_dispersion <= inst->max_delay &&
1647 precision <= inst->max_delay &&
1648 !(inst->mode == MODE_CLIENT && response_time > MAX_SERVER_INTERVAL) &&
1649 !(inst->mode == MODE_ACTIVE && interleaved_packet &&
1650 (sample.peer_delay > 0.5 * prev_remote_poll_interval ||
1651 UTI_CompareNtp64(&message->receive_ts, &message->transmit_ts) <= 0 ||
1652 (inst->remote_poll <= inst->prev_local_poll &&
1653 UTI_DiffTimespecsToDouble(&remote_transmit, &prev_remote_transmit) >
1654 1.5 * prev_remote_poll_interval)));
1655
1656 /* Test B requires in client mode that the ratio of the round trip delay
1657 to the minimum one currently in the stats data register is less than an
1658 administrator-defined value */
1659 testB = check_delay_ratio(inst, stats, &sample.time, sample.peer_delay);
1660
1661 /* Test C requires that the ratio of the increase in delay from the minimum
1662 one in the stats data register to the standard deviation of the offsets
1663 in the register is less than an administrator-defined value or the
1664 difference between measured offset and predicted offset is larger than
1665 the increase in delay */
1666 testC = check_delay_dev_ratio(inst, stats, &sample.time, sample.offset, sample.peer_delay);
1667
1668 /* Test D requires that the source is not synchronised to us and is not us
1669 to prevent a synchronisation loop */
1670 testD = check_sync_loop(inst, message, local_addr, &rx_ts->ts);
1671 } else {
1672 remote_interval = local_interval = response_time = 0.0;
1673 sample.offset = sample.peer_delay = sample.peer_dispersion = 0.0;
1674 sample.time = rx_ts->ts;
1675 local_receive = *rx_ts;
1676 local_transmit = inst->local_tx;
1677 testA = testB = testC = testD = 0;
1678 }
1679
1680 /* The packet is considered good for synchronisation if
1681 the additional tests passed */
1682 good_packet = testA && testB && testC && testD;
1683
1684 sample.root_delay = pkt_root_delay + sample.peer_delay;
1685 sample.root_dispersion = pkt_root_dispersion + sample.peer_dispersion;
1686 sample.stratum = MAX(message->stratum, inst->min_stratum);
1687
1688 /* Update the NTP timestamps. If it's a valid packet from a synchronised
1689 source, the timestamps may be used later when processing a packet in the
1690 interleaved mode. Protect the timestamps against replay attacks in client
1691 mode, and also in symmetric mode as long as the peers use the same polling
1692 interval and never start with clocks in future or very distant past.
1693 The authentication test (test5) is required to prevent DoS attacks using
1694 unauthenticated packets on authenticated symmetric associations. */
1695 if ((inst->mode == MODE_CLIENT && valid_packet && !inst->valid_rx) ||
1696 (inst->mode == MODE_ACTIVE && valid_packet &&
1697 (!inst->valid_rx ||
1698 UTI_CompareNtp64(&inst->remote_ntp_tx, &message->transmit_ts) < 0))) {
1699 inst->remote_ntp_rx = message->receive_ts;
1700 inst->remote_ntp_tx = message->transmit_ts;
1701 inst->local_rx = *rx_ts;
1702 inst->valid_timestamps = synced_packet;
1703
1704 UTI_ZeroNtp64(&inst->init_remote_ntp_tx);
1705 zero_local_timestamp(&inst->init_local_rx);
1706 inst->updated_init_timestamps = 0;
1707 updated_timestamps = 2;
1708
1709 /* Don't use the same set of timestamps for the next sample */
1710 if (interleaved_packet)
1711 inst->prev_local_tx = inst->local_tx;
1712 else
1713 zero_local_timestamp(&inst->prev_local_tx);
1714 } else if (inst->mode == MODE_ACTIVE &&
1715 test1 && !UTI_IsZeroNtp64(&message->transmit_ts) && test5 &&
1716 (!inst->updated_init_timestamps ||
1717 UTI_CompareNtp64(&inst->init_remote_ntp_tx, &message->transmit_ts) < 0)) {
1718 inst->init_remote_ntp_tx = message->transmit_ts;
1719 inst->init_local_rx = *rx_ts;
1720 inst->updated_init_timestamps = 1;
1721 updated_timestamps = 1;
1722 } else {
1723 updated_timestamps = 0;
1724 }
1725
1726 /* Accept at most one response per request. The NTP specification recommends
1727 resetting local_ntp_tx to make the following packets fail test2 or test3,
1728 but that would not allow the code above to make multiple updates of the
1729 timestamps in symmetric mode. Also, ignore presend responses. */
1730 if (inst->valid_rx) {
1731 test2 = test3 = 0;
1732 valid_packet = synced_packet = good_packet = 0;
1733 } else if (valid_packet) {
1734 if (inst->presend_done) {
1735 testA = 0;
1736 good_packet = 0;
1737 }
1738 inst->valid_rx = 1;
1739 }
1740
1741 if ((unsigned int)local_receive.source >= sizeof (tss_chars) ||
1742 (unsigned int)local_transmit.source >= sizeof (tss_chars))
1743 assert(0);
1744
1745 DEBUG_LOG("NTP packet lvm=%o stratum=%d poll=%d prec=%d root_delay=%f root_disp=%f refid=%"PRIx32" [%s]",
1746 message->lvm, message->stratum, message->poll, message->precision,
1747 pkt_root_delay, pkt_root_dispersion, pkt_refid,
1748 message->stratum == NTP_INVALID_STRATUM ? UTI_RefidToString(pkt_refid) : "");
1749 DEBUG_LOG("reference=%s origin=%s receive=%s transmit=%s",
1750 UTI_Ntp64ToString(&message->reference_ts),
1751 UTI_Ntp64ToString(&message->originate_ts),
1752 UTI_Ntp64ToString(&message->receive_ts),
1753 UTI_Ntp64ToString(&message->transmit_ts));
1754 DEBUG_LOG("offset=%.9f delay=%.9f dispersion=%f root_delay=%f root_dispersion=%f",
1755 sample.offset, sample.peer_delay, sample.peer_dispersion,
1756 sample.root_delay, sample.root_dispersion);
1757 DEBUG_LOG("remote_interval=%.9f local_interval=%.9f response_time=%.9f txs=%c rxs=%c",
1758 remote_interval, local_interval, response_time,
1759 tss_chars[local_transmit.source], tss_chars[local_receive.source]);
1760 DEBUG_LOG("test123=%d%d%d test567=%d%d%d testABCD=%d%d%d%d kod_rate=%d interleaved=%d"
1761 " presend=%d valid=%d good=%d updated=%d",
1762 test1, test2, test3, test5, test6, test7, testA, testB, testC, testD,
1763 kod_rate, interleaved_packet, inst->presend_done, valid_packet, good_packet,
1764 updated_timestamps);
1765
1766 if (valid_packet) {
1767 inst->remote_poll = message->poll;
1768 inst->remote_stratum = message->stratum != NTP_INVALID_STRATUM ?
1769 message->stratum : NTP_MAX_STRATUM;
1770
1771 inst->prev_local_poll = inst->local_poll;
1772 inst->prev_tx_count = inst->tx_count;
1773 inst->tx_count = 0;
1774
1775 SRC_UpdateReachability(inst->source, synced_packet);
1776 SRC_SetLeapStatus(inst->source, pkt_leap);
1777
1778 if (good_packet) {
1779 /* Adjust the polling interval, accumulate the sample, etc. */
1780 process_sample(inst, &sample);
1781
1782 /* If we're in burst mode, check whether the burst is completed and
1783 revert to the previous mode */
1784 switch (inst->opmode) {
1785 case MD_BURST_WAS_ONLINE:
1786 case MD_BURST_WAS_OFFLINE:
1787 --inst->burst_good_samples_to_go;
1788 if (inst->burst_good_samples_to_go <= 0) {
1789 if (inst->opmode == MD_BURST_WAS_ONLINE)
1790 inst->opmode = MD_ONLINE;
1791 else
1792 take_offline(inst);
1793 }
1794 break;
1795 default:
1796 break;
1797 }
1798 } else {
1799 /* Slowly increase the polling interval if we can't get good packet */
1800 adjust_poll(inst, 0.1);
1801 }
1802
1803 /* If in client mode, no more packets are expected to be coming from the
1804 server and the socket can be closed */
1805 close_client_socket(inst);
1806
1807 /* Update the local address and interface */
1808 inst->local_addr.ip_addr = local_addr->ip_addr;
1809 inst->local_addr.if_index = local_addr->if_index;
1810
1811 /* And now, requeue the timer */
1812 if (inst->opmode != MD_OFFLINE) {
1813 delay_time = get_transmit_delay(inst, 0,
1814 UTI_DiffTimespecsToDouble(&inst->local_rx.ts, &inst->local_tx.ts));
1815
1816 if (kod_rate) {
1817 LOG(LOGS_WARN, "Received KoD RATE from %s",
1818 UTI_IPToString(&inst->remote_addr.ip_addr));
1819
1820 /* Back off for a while and stop ongoing burst */
1821 delay_time += 4 * UTI_Log2ToDouble(inst->local_poll);
1822
1823 if (inst->opmode == MD_BURST_WAS_OFFLINE || inst->opmode == MD_BURST_WAS_ONLINE) {
1824 inst->burst_good_samples_to_go = 0;
1825 }
1826 }
1827
1828 /* Get rid of old timeout and start a new one */
1829 assert(inst->tx_timeout_id);
1830 restart_timeout(inst, delay_time);
1831 }
1832
1833 /* Update the NTP report */
1834 inst->report.remote_addr = inst->remote_addr.ip_addr;
1835 inst->report.local_addr = inst->local_addr.ip_addr;
1836 inst->report.remote_port = inst->remote_addr.port;
1837 inst->report.leap = pkt_leap;
1838 inst->report.version = pkt_version;
1839 inst->report.mode = NTP_LVM_TO_MODE(message->lvm);
1840 inst->report.stratum = message->stratum;
1841 inst->report.poll = message->poll;
1842 inst->report.precision = message->precision;
1843 inst->report.root_delay = pkt_root_delay;
1844 inst->report.root_dispersion = pkt_root_dispersion;
1845 inst->report.ref_id = pkt_refid;
1846 UTI_Ntp64ToTimespec(&message->reference_ts, &inst->report.ref_time);
1847 inst->report.offset = sample.offset;
1848 inst->report.peer_delay = sample.peer_delay;
1849 inst->report.peer_dispersion = sample.peer_dispersion;
1850 inst->report.response_time = response_time;
1851 inst->report.jitter_asymmetry = SST_GetJitterAsymmetry(stats);
1852 inst->report.tests = ((((((((test1 << 1 | test2) << 1 | test3) << 1 |
1853 test5) << 1 | test6) << 1 | test7) << 1 |
1854 testA) << 1 | testB) << 1 | testC) << 1 | testD;
1855 inst->report.interleaved = interleaved_packet;
1856 inst->report.authenticated = NAU_IsAuthEnabled(inst->auth);
1857 inst->report.tx_tss_char = tss_chars[local_transmit.source];
1858 inst->report.rx_tss_char = tss_chars[local_receive.source];
1859
1860 inst->report.total_valid_count++;
1861 }
1862
1863 /* Do measurement logging */
1864 if (logfileid != -1 && (log_raw_measurements || synced_packet)) {
1865 LOG_FileWrite(logfileid, "%s %-15s %1c %2d %1d%1d%1d %1d%1d%1d %1d%1d%1d%d %2d %2d %4.2f %10.3e %10.3e %10.3e %10.3e %10.3e %08"PRIX32" %1d%1c %1c %1c",
1866 UTI_TimeToLogForm(sample.time.tv_sec),
1867 UTI_IPToString(&inst->remote_addr.ip_addr),
1868 leap_chars[pkt_leap],
1869 message->stratum,
1870 test1, test2, test3, test5, test6, test7, testA, testB, testC, testD,
1871 inst->local_poll, message->poll,
1872 inst->poll_score,
1873 sample.offset, sample.peer_delay, sample.peer_dispersion,
1874 pkt_root_delay, pkt_root_dispersion, pkt_refid,
1875 NTP_LVM_TO_MODE(message->lvm), interleaved_packet ? 'I' : 'B',
1876 tss_chars[local_transmit.source],
1877 tss_chars[local_receive.source]);
1878 }
1879
1880 return good_packet;
1881 }
1882
1883 /* ================================================== */
1884 /* From RFC 5905, the standard handling of received packets, depending
1885 on the mode of the packet and of the source, is :
1886
1887 +------------------+---------------------------------------+
1888 | | Packet Mode |
1889 +------------------+-------+-------+-------+-------+-------+
1890 | Association Mode | 1 | 2 | 3 | 4 | 5 |
1891 +------------------+-------+-------+-------+-------+-------+
1892 | No Association 0 | NEWPS | DSCRD | FXMIT | MANY | NEWBC |
1893 | Symm. Active 1 | PROC | PROC | DSCRD | DSCRD | DSCRD |
1894 | Symm. Passive 2 | PROC | ERR | DSCRD | DSCRD | DSCRD |
1895 | Client 3 | DSCRD | DSCRD | DSCRD | PROC | DSCRD |
1896 | Server 4 | DSCRD | DSCRD | DSCRD | DSCRD | DSCRD |
1897 | Broadcast 5 | DSCRD | DSCRD | DSCRD | DSCRD | DSCRD |
1898 | Bcast Client 6 | DSCRD | DSCRD | DSCRD | DSCRD | PROC |
1899 +------------------+-------+-------+-------+-------+-------+
1900
1901 Association mode 0 is implemented in NCR_ProcessRxUnknown(), other modes
1902 in NCR_ProcessRxKnown().
1903
1904 Broadcast, manycast and ephemeral symmetric passive associations are not
1905 supported yet.
1906 */
1907
1908 /* ================================================== */
1909 /* This routine is called when a new packet arrives off the network,
1910 and it relates to a source we have an ongoing protocol exchange with */
1911
1912 int
1913 NCR_ProcessRxKnown(NCR_Instance inst, NTP_Local_Address *local_addr,
1914 NTP_Local_Timestamp *rx_ts, NTP_Packet *message, int length)
1915 {
1916 int proc_packet, proc_as_unknown;
1917 NTP_PacketInfo info;
1918
1919 inst->report.total_rx_count++;
1920
1921 if (!parse_packet(message, length, &info))
1922 return 0;
1923
1924 proc_packet = 0;
1925 proc_as_unknown = 0;
1926
1927 /* Now, depending on the mode we decide what to do */
1928 switch (info.mode) {
1929 case MODE_ACTIVE:
1930 switch (inst->mode) {
1931 case MODE_ACTIVE:
1932 /* Ordinary symmetric peering */
1933 proc_packet = 1;
1934 break;
1935 case MODE_PASSIVE:
1936 /* In this software this case should not arise, we don't
1937 support unconfigured peers */
1938 break;
1939 case MODE_CLIENT:
1940 /* This is where we have the remote configured as a server and he has
1941 us configured as a peer, process as from an unknown source */
1942 proc_as_unknown = 1;
1943 break;
1944 default:
1945 /* Discard */
1946 break;
1947 }
1948 break;
1949
1950 case MODE_PASSIVE:
1951 switch (inst->mode) {
1952 case MODE_ACTIVE:
1953 /* This would arise if we have the remote configured as a peer and
1954 he does not have us configured */
1955 proc_packet = 1;
1956 break;
1957 case MODE_PASSIVE:
1958 /* Error condition in RFC 5905 */
1959 break;
1960 default:
1961 /* Discard */
1962 break;
1963 }
1964 break;
1965
1966 case MODE_CLIENT:
1967 /* If message is client mode, we just respond with a server mode
1968 packet, regardless of what we think the remote machine is
1969 supposed to be. However, even though this is a configured
1970 peer or server, we still implement access restrictions on
1971 client mode operation.
1972
1973 This copes with the case for an isolated network where one
1974 machine is set by eye and is used as the master, with the
1975 other machines pointed at it. If the master goes down, we
1976 want to be able to reset its time at startup by relying on
1977 one of the secondaries to flywheel it. The behaviour coded here
1978 is required in the secondaries to make this possible. */
1979
1980 proc_as_unknown = 1;
1981 break;
1982
1983 case MODE_SERVER:
1984 switch (inst->mode) {
1985 case MODE_CLIENT:
1986 /* Standard case where he's a server and we're the client */
1987 proc_packet = 1;
1988 break;
1989 default:
1990 /* Discard */
1991 break;
1992 }
1993 break;
1994
1995 case MODE_BROADCAST:
1996 /* Just ignore these */
1997 break;
1998
1999 default:
2000 /* Obviously ignore */
2001 break;
2002 }
2003
2004 if (proc_packet) {
2005 /* Check if the reply was received by the socket that sent the request */
2006 if (local_addr->sock_fd != inst->local_addr.sock_fd) {
2007 DEBUG_LOG("Packet received by wrong socket %d (expected %d)",
2008 local_addr->sock_fd, inst->local_addr.sock_fd);
2009 return 0;
2010 }
2011
2012 /* Ignore packets from offline sources */
2013 if (inst->opmode == MD_OFFLINE || inst->tx_suspended) {
2014 DEBUG_LOG("Packet from offline source");
2015 return 0;
2016 }
2017
2018 return process_response(inst, local_addr, rx_ts, message, &info);
2019 } else if (proc_as_unknown) {
2020 NCR_ProcessRxUnknown(&inst->remote_addr, local_addr, rx_ts, message, length);
2021 /* It's not a reply to our request, don't return success */
2022 return 0;
2023 } else {
2024 DEBUG_LOG("NTP packet discarded mode=%d our_mode=%u", (int)info.mode, inst->mode);
2025 return 0;
2026 }
2027 }
2028
2029 /* ================================================== */
2030 /* This routine is called when a new packet arrives off the network,
2031 and it relates to a source we don't know (not our server or peer) */
2032
2033 void
2034 NCR_ProcessRxUnknown(NTP_Remote_Address *remote_addr, NTP_Local_Address *local_addr,
2035 NTP_Local_Timestamp *rx_ts, NTP_Packet *message, int length)
2036 {
2037 NTP_PacketInfo info;
2038 NTP_Mode my_mode;
2039 NTP_int64 *local_ntp_rx, *local_ntp_tx;
2040 NTP_Local_Timestamp local_tx, *tx_ts;
2041 int log_index, interleaved, poll, version;
2042 uint32_t kod;
2043
2044 /* Ignore the packet if it wasn't received by server socket */
2045 if (!NIO_IsServerSocket(local_addr->sock_fd)) {
2046 DEBUG_LOG("NTP request packet received by client socket %d", local_addr->sock_fd);
2047 return;
2048 }
2049
2050 if (!parse_packet(message, length, &info))
2051 return;
2052
2053 if (!ADF_IsAllowed(access_auth_table, &remote_addr->ip_addr)) {
2054 DEBUG_LOG("NTP packet received from unauthorised host %s",
2055 UTI_IPToString(&remote_addr->ip_addr));
2056 return;
2057 }
2058
2059 switch (info.mode) {
2060 case MODE_ACTIVE:
2061 /* We are symmetric passive, even though we don't ever lock to him */
2062 my_mode = MODE_PASSIVE;
2063 break;
2064 case MODE_CLIENT:
2065 /* Reply with server packet */
2066 my_mode = MODE_SERVER;
2067 break;
2068 case MODE_UNDEFINED:
2069 /* Check if it is an NTPv1 client request (NTPv1 packets have a reserved
2070 field instead of the mode field and the actual mode is determined from
2071 the port numbers). Don't ever respond with a mode 0 packet! */
2072 if (info.version == 1 && remote_addr->port != NTP_PORT) {
2073 my_mode = MODE_SERVER;
2074 break;
2075 }
2076 /* Fall through */
2077 default:
2078 /* Discard */
2079 DEBUG_LOG("NTP packet discarded mode=%d", (int)info.mode);
2080 return;
2081 }
2082
2083 kod = 0;
2084 log_index = CLG_LogNTPAccess(&remote_addr->ip_addr, &rx_ts->ts);
2085
2086 /* Don't reply to all requests if the rate is excessive */
2087 if (log_index >= 0 && CLG_LimitNTPResponseRate(log_index)) {
2088 DEBUG_LOG("NTP packet discarded to limit response rate");
2089 return;
2090 }
2091
2092 /* Check authentication */
2093 if (!NAU_CheckRequestAuth(message, &info, &kod)) {
2094 DEBUG_LOG("NTP packet failed auth mode=%d kod=%"PRIx32, (int)info.auth.mode, kod);
2095
2096 /* Don't respond unless a non-zero KoD was returned */
2097 if (kod == 0)
2098 return;
2099 }
2100
2101 /* If it is an NTPv4 packet with a long MAC and no extension fields,
2102 respond with a NTPv3 packet to avoid breaking RFC 7822 and keep
2103 the length symmetric. Otherwise, respond with the same version. */
2104 if (info.version == 4 && info.ext_fields == 0 && info.auth.mode == NTP_AUTH_SYMMETRIC &&
2105 info.auth.mac.length > NTP_MAX_V4_MAC_LENGTH)
2106 version = 3;
2107 else
2108 version = info.version;
2109
2110 local_ntp_rx = local_ntp_tx = NULL;
2111 tx_ts = NULL;
2112 interleaved = 0;
2113
2114 /* Check if the client is using the interleaved mode. If it is, save the
2115 new transmit timestamp and if the old transmit timestamp is valid, respond
2116 in the interleaved mode. This means the third reply to a new client is
2117 the earliest one that can be interleaved. We don't want to waste time
2118 on clients that are not using the interleaved mode. */
2119 if (kod == 0 && log_index >= 0) {
2120 CLG_GetNtpTimestamps(log_index, &local_ntp_rx, &local_ntp_tx);
2121 interleaved = !UTI_IsZeroNtp64(local_ntp_rx) &&
2122 !UTI_CompareNtp64(&message->originate_ts, local_ntp_rx) &&
2123 UTI_CompareNtp64(&message->receive_ts, &message->transmit_ts);
2124
2125 if (interleaved) {
2126 UTI_Ntp64ToTimespec(local_ntp_tx, &local_tx.ts);
2127 tx_ts = &local_tx;
2128 } else {
2129 UTI_ZeroNtp64(local_ntp_tx);
2130 local_ntp_tx = NULL;
2131 }
2132 }
2133
2134 /* Suggest the client to increase its polling interval if it indicates
2135 the interval is shorter than the rate limiting interval */
2136 poll = CLG_GetNtpMinPoll();
2137 poll = MAX(poll, message->poll);
2138
2139 /* Send a reply */
2140 transmit_packet(my_mode, interleaved, poll, version, kod, NULL,
2141 &message->receive_ts, &message->transmit_ts,
2142 rx_ts, tx_ts, local_ntp_rx, NULL, remote_addr, local_addr,
2143 message, &info);
2144
2145 /* Save the transmit timestamp */
2146 if (tx_ts)
2147 UTI_TimespecToNtp64(&tx_ts->ts, local_ntp_tx, NULL);
2148 }
2149
2150 /* ================================================== */
2151
2152 static void
2153 update_tx_timestamp(NTP_Local_Timestamp *tx_ts, NTP_Local_Timestamp *new_tx_ts,
2154 NTP_int64 *local_ntp_rx, NTP_int64 *local_ntp_tx, NTP_Packet *message)
2155 {
2156 double delay;
2157
2158 if (UTI_IsZeroTimespec(&tx_ts->ts)) {
2159 DEBUG_LOG("Unexpected TX update");
2160 return;
2161 }
2162
2163 /* Check if this is the last packet that was sent */
2164 if ((local_ntp_rx && UTI_CompareNtp64(&message->receive_ts, local_ntp_rx)) ||
2165 (local_ntp_tx && UTI_CompareNtp64(&message->transmit_ts, local_ntp_tx))) {
2166 DEBUG_LOG("RX/TX timestamp mismatch");
2167 return;
2168 }
2169
2170 delay = UTI_DiffTimespecsToDouble(&new_tx_ts->ts, &tx_ts->ts);
2171
2172 if (delay < 0.0 || delay > MAX_TX_DELAY) {
2173 DEBUG_LOG("Unacceptable TX delay %.9f", delay);
2174 return;
2175 }
2176
2177 *tx_ts = *new_tx_ts;
2178
2179 DEBUG_LOG("Updated TX timestamp delay=%.9f", delay);
2180 }
2181
2182 /* ================================================== */
2183
2184 void
2185 NCR_ProcessTxKnown(NCR_Instance inst, NTP_Local_Address *local_addr,
2186 NTP_Local_Timestamp *tx_ts, NTP_Packet *message, int length)
2187 {
2188 NTP_PacketInfo info;
2189
2190 if (!parse_packet(message, length, &info))
2191 return;
2192
2193 /* Server and passive mode packets are responses to unknown sources */
2194 if (info.mode != MODE_CLIENT && info.mode != MODE_ACTIVE) {
2195 NCR_ProcessTxUnknown(&inst->remote_addr, local_addr, tx_ts, message, length);
2196 return;
2197 }
2198
2199 update_tx_timestamp(&inst->local_tx, tx_ts, &inst->local_ntp_rx, &inst->local_ntp_tx,
2200 message);
2201 }
2202
2203 /* ================================================== */
2204
2205 void
2206 NCR_ProcessTxUnknown(NTP_Remote_Address *remote_addr, NTP_Local_Address *local_addr,
2207 NTP_Local_Timestamp *tx_ts, NTP_Packet *message, int length)
2208 {
2209 NTP_int64 *local_ntp_rx, *local_ntp_tx;
2210 NTP_Local_Timestamp local_tx;
2211 NTP_PacketInfo info;
2212 int log_index;
2213
2214 if (!parse_packet(message, length, &info))
2215 return;
2216
2217 if (info.mode == MODE_BROADCAST)
2218 return;
2219
2220 log_index = CLG_GetClientIndex(&remote_addr->ip_addr);
2221 if (log_index < 0)
2222 return;
2223
2224 if (SMT_IsEnabled() && info.mode == MODE_SERVER)
2225 UTI_AddDoubleToTimespec(&tx_ts->ts, SMT_GetOffset(&tx_ts->ts), &tx_ts->ts);
2226
2227 CLG_GetNtpTimestamps(log_index, &local_ntp_rx, &local_ntp_tx);
2228
2229 UTI_Ntp64ToTimespec(local_ntp_tx, &local_tx.ts);
2230 update_tx_timestamp(&local_tx, tx_ts, local_ntp_rx, NULL, message);
2231 UTI_TimespecToNtp64(&local_tx.ts, local_ntp_tx, NULL);
2232 }
2233
2234 /* ================================================== */
2235
2236 void
2237 NCR_SlewTimes(NCR_Instance inst, struct timespec *when, double dfreq, double doffset)
2238 {
2239 double delta;
2240
2241 if (!UTI_IsZeroTimespec(&inst->local_rx.ts))
2242 UTI_AdjustTimespec(&inst->local_rx.ts, when, &inst->local_rx.ts, &delta, dfreq, doffset);
2243 if (!UTI_IsZeroTimespec(&inst->local_tx.ts))
2244 UTI_AdjustTimespec(&inst->local_tx.ts, when, &inst->local_tx.ts, &delta, dfreq, doffset);
2245 if (!UTI_IsZeroTimespec(&inst->prev_local_tx.ts))
2246 UTI_AdjustTimespec(&inst->prev_local_tx.ts, when, &inst->prev_local_tx.ts, &delta, dfreq,
2247 doffset);
2248 if (!UTI_IsZeroTimespec(&inst->init_local_rx.ts))
2249 UTI_AdjustTimespec(&inst->init_local_rx.ts, when, &inst->init_local_rx.ts, &delta, dfreq,
2250 doffset);
2251
2252 if (inst->filter)
2253 SPF_SlewSamples(inst->filter, when, dfreq, doffset);
2254 }
2255
2256 /* ================================================== */
2257
2258 void
2259 NCR_SetConnectivity(NCR_Instance inst, SRC_Connectivity connectivity)
2260 {
2261 char *s;
2262
2263 s = UTI_IPToString(&inst->remote_addr.ip_addr);
2264
2265 if (connectivity == SRC_MAYBE_ONLINE)
2266 connectivity = NIO_IsServerConnectable(&inst->remote_addr) ? SRC_ONLINE : SRC_OFFLINE;
2267
2268 switch (connectivity) {
2269 case SRC_ONLINE:
2270 switch (inst->opmode) {
2271 case MD_ONLINE:
2272 /* Nothing to do */
2273 break;
2274 case MD_OFFLINE:
2275 LOG(LOGS_INFO, "Source %s online", s);
2276 inst->opmode = MD_ONLINE;
2277 NCR_ResetInstance(inst);
2278 start_initial_timeout(inst);
2279 break;
2280 case MD_BURST_WAS_ONLINE:
2281 /* Will revert */
2282 break;
2283 case MD_BURST_WAS_OFFLINE:
2284 inst->opmode = MD_BURST_WAS_ONLINE;
2285 LOG(LOGS_INFO, "Source %s online", s);
2286 break;
2287 default:
2288 assert(0);
2289 }
2290 break;
2291 case SRC_OFFLINE:
2292 switch (inst->opmode) {
2293 case MD_ONLINE:
2294 LOG(LOGS_INFO, "Source %s offline", s);
2295 take_offline(inst);
2296 break;
2297 case MD_OFFLINE:
2298 break;
2299 case MD_BURST_WAS_ONLINE:
2300 inst->opmode = MD_BURST_WAS_OFFLINE;
2301 LOG(LOGS_INFO, "Source %s offline", s);
2302 break;
2303 case MD_BURST_WAS_OFFLINE:
2304 break;
2305 default:
2306 assert(0);
2307 }
2308 break;
2309 default:
2310 assert(0);
2311 }
2312 }
2313
2314 /* ================================================== */
2315
2316 void
2317 NCR_ModifyMinpoll(NCR_Instance inst, int new_minpoll)
2318 {
2319 if (new_minpoll < MIN_POLL || new_minpoll > MAX_POLL)
2320 return;
2321 inst->minpoll = new_minpoll;
2322 LOG(LOGS_INFO, "Source %s new minpoll %d", UTI_IPToString(&inst->remote_addr.ip_addr), new_minpoll);
2323 if (inst->maxpoll < inst->minpoll)
2324 NCR_ModifyMaxpoll(inst, inst->minpoll);
2325 }
2326
2327 /* ================================================== */
2328
2329 void
2330 NCR_ModifyMaxpoll(NCR_Instance inst, int new_maxpoll)
2331 {
2332 if (new_maxpoll < MIN_POLL || new_maxpoll > MAX_POLL)
2333 return;
2334 inst->maxpoll = new_maxpoll;
2335 LOG(LOGS_INFO, "Source %s new maxpoll %d", UTI_IPToString(&inst->remote_addr.ip_addr), new_maxpoll);
2336 if (inst->minpoll > inst->maxpoll)
2337 NCR_ModifyMinpoll(inst, inst->maxpoll);
2338 }
2339
2340 /* ================================================== */
2341
2342 void
2343 NCR_ModifyMaxdelay(NCR_Instance inst, double new_max_delay)
2344 {
2345 inst->max_delay = CLAMP(0.0, new_max_delay, MAX_MAXDELAY);
2346 LOG(LOGS_INFO, "Source %s new maxdelay %f",
2347 UTI_IPToString(&inst->remote_addr.ip_addr), inst->max_delay);
2348 }
2349
2350 /* ================================================== */
2351
2352 void
2353 NCR_ModifyMaxdelayratio(NCR_Instance inst, double new_max_delay_ratio)
2354 {
2355 inst->max_delay_ratio = CLAMP(0.0, new_max_delay_ratio, MAX_MAXDELAYRATIO);
2356 LOG(LOGS_INFO, "Source %s new maxdelayratio %f",
2357 UTI_IPToString(&inst->remote_addr.ip_addr), inst->max_delay_ratio);
2358 }
2359
2360 /* ================================================== */
2361
2362 void
2363 NCR_ModifyMaxdelaydevratio(NCR_Instance inst, double new_max_delay_dev_ratio)
2364 {
2365 inst->max_delay_dev_ratio = CLAMP(0.0, new_max_delay_dev_ratio, MAX_MAXDELAYDEVRATIO);
2366 LOG(LOGS_INFO, "Source %s new maxdelaydevratio %f",
2367 UTI_IPToString(&inst->remote_addr.ip_addr), inst->max_delay_dev_ratio);
2368 }
2369
2370 /* ================================================== */
2371
2372 void
2373 NCR_ModifyMinstratum(NCR_Instance inst, int new_min_stratum)
2374 {
2375 inst->min_stratum = new_min_stratum;
2376 LOG(LOGS_INFO, "Source %s new minstratum %d",
2377 UTI_IPToString(&inst->remote_addr.ip_addr), new_min_stratum);
2378 }
2379
2380 /* ================================================== */
2381
2382 void
2383 NCR_ModifyPolltarget(NCR_Instance inst, int new_poll_target)
2384 {
2385 inst->poll_target = new_poll_target;
2386 LOG(LOGS_INFO, "Source %s new polltarget %d",
2387 UTI_IPToString(&inst->remote_addr.ip_addr), new_poll_target);
2388 }
2389
2390 /* ================================================== */
2391
2392 void
2393 NCR_InitiateSampleBurst(NCR_Instance inst, int n_good_samples, int n_total_samples)
2394 {
2395
2396 if (inst->mode == MODE_CLIENT) {
2397
2398 /* We want to prevent burst mode being used on symmetric active
2399 associations - it will play havoc with the peer's sampling
2400 strategy. (This obviously relies on us having the peer
2401 configured that way if he has us configured symmetric active -
2402 but there's not much else we can do.) */
2403
2404 switch (inst->opmode) {
2405 case MD_BURST_WAS_OFFLINE:
2406 case MD_BURST_WAS_ONLINE:
2407 /* If already burst sampling, don't start again */
2408 break;
2409
2410 case MD_ONLINE:
2411 case MD_OFFLINE:
2412 inst->opmode = inst->opmode == MD_ONLINE ?
2413 MD_BURST_WAS_ONLINE : MD_BURST_WAS_OFFLINE;
2414 inst->burst_good_samples_to_go = n_good_samples;
2415 inst->burst_total_samples_to_go = n_total_samples;
2416 start_initial_timeout(inst);
2417 break;
2418 default:
2419 assert(0);
2420 break;
2421 }
2422 }
2423
2424 }
2425
2426 /* ================================================== */
2427
2428 void
2429 NCR_ReportSource(NCR_Instance inst, RPT_SourceReport *report, struct timespec *now)
2430 {
2431 report->poll = get_transmit_poll(inst);
2432
2433 switch (inst->mode) {
2434 case MODE_CLIENT:
2435 report->mode = RPT_NTP_CLIENT;
2436 break;
2437 case MODE_ACTIVE:
2438 report->mode = RPT_NTP_PEER;
2439 break;
2440 default:
2441 assert(0);
2442 }
2443 }
2444
2445 /* ================================================== */
2446
2447 void
2448 NCR_GetNTPReport(NCR_Instance inst, RPT_NTPReport *report)
2449 {
2450 *report = inst->report;
2451 }
2452
2453 /* ================================================== */
2454
2455 int
2456 NCR_AddAccessRestriction(IPAddr *ip_addr, int subnet_bits, int allow, int all)
2457 {
2458 ADF_Status status;
2459
2460 if (allow) {
2461 if (all) {
2462 status = ADF_AllowAll(access_auth_table, ip_addr, subnet_bits);
2463 } else {
2464 status = ADF_Allow(access_auth_table, ip_addr, subnet_bits);
2465 }
2466 } else {
2467 if (all) {
2468 status = ADF_DenyAll(access_auth_table, ip_addr, subnet_bits);
2469 } else {
2470 status = ADF_Deny(access_auth_table, ip_addr, subnet_bits);
2471 }
2472 }
2473
2474 if (status != ADF_SUCCESS)
2475 return 0;
2476
2477 /* Keep server sockets open only when an address allowed */
2478 if (allow) {
2479 NTP_Remote_Address remote_addr;
2480
2481 if (server_sock_fd4 == INVALID_SOCK_FD &&
2482 ADF_IsAnyAllowed(access_auth_table, IPADDR_INET4)) {
2483 remote_addr.ip_addr.family = IPADDR_INET4;
2484 server_sock_fd4 = NIO_OpenServerSocket(&remote_addr);
2485 }
2486 if (server_sock_fd6 == INVALID_SOCK_FD &&
2487 ADF_IsAnyAllowed(access_auth_table, IPADDR_INET6)) {
2488 remote_addr.ip_addr.family = IPADDR_INET6;
2489 server_sock_fd6 = NIO_OpenServerSocket(&remote_addr);
2490 }
2491 } else {
2492 if (server_sock_fd4 != INVALID_SOCK_FD &&
2493 !ADF_IsAnyAllowed(access_auth_table, IPADDR_INET4)) {
2494 NIO_CloseServerSocket(server_sock_fd4);
2495 server_sock_fd4 = INVALID_SOCK_FD;
2496 }
2497 if (server_sock_fd6 != INVALID_SOCK_FD &&
2498 !ADF_IsAnyAllowed(access_auth_table, IPADDR_INET6)) {
2499 NIO_CloseServerSocket(server_sock_fd6);
2500 server_sock_fd6 = INVALID_SOCK_FD;
2501 }
2502 }
2503
2504 return 1;
2505 }
2506
2507 /* ================================================== */
2508
2509 int
2510 NCR_CheckAccessRestriction(IPAddr *ip_addr)
2511 {
2512 return ADF_IsAllowed(access_auth_table, ip_addr);
2513 }
2514
2515 /* ================================================== */
2516
2517 void
2518 NCR_IncrementActivityCounters(NCR_Instance inst, int *online, int *offline,
2519 int *burst_online, int *burst_offline)
2520 {
2521 switch (inst->opmode) {
2522 case MD_BURST_WAS_OFFLINE:
2523 ++*burst_offline;
2524 break;
2525 case MD_BURST_WAS_ONLINE:
2526 ++*burst_online;
2527 break;
2528 case MD_ONLINE:
2529 ++*online;
2530 break;
2531 case MD_OFFLINE:
2532 ++*offline;
2533 break;
2534 default:
2535 assert(0);
2536 break;
2537 }
2538 }
2539
2540 /* ================================================== */
2541
2542 NTP_Remote_Address *
2543 NCR_GetRemoteAddress(NCR_Instance inst)
2544 {
2545 return &inst->remote_addr;
2546 }
2547
2548 /* ================================================== */
2549
2550 uint32_t
2551 NCR_GetLocalRefid(NCR_Instance inst)
2552 {
2553 return UTI_IPToRefid(&inst->local_addr.ip_addr);
2554 }
2555
2556 /* ================================================== */
2557
2558 int NCR_IsSyncPeer(NCR_Instance inst)
2559 {
2560 return SRC_IsSyncPeer(inst->source);
2561 }
2562
2563 /* ================================================== */
2564
2565 void
2566 NCR_DumpAuthData(NCR_Instance inst)
2567 {
2568 NAU_DumpData(inst->auth);
2569 }
2570
2571 /* ================================================== */
2572
2573 static void
2574 broadcast_timeout(void *arg)
2575 {
2576 BroadcastDestination *destination;
2577 NTP_int64 orig_ts;
2578 NTP_Local_Timestamp recv_ts;
2579 int poll;
2580
2581 destination = ARR_GetElement(broadcasts, (long)arg);
2582 poll = log(destination->interval) / log(2.0) + 0.5;
2583
2584 UTI_ZeroNtp64(&orig_ts);
2585 zero_local_timestamp(&recv_ts);
2586
2587 transmit_packet(MODE_BROADCAST, 0, poll, NTP_VERSION, 0, destination->auth,
2588 &orig_ts, &orig_ts, &recv_ts, NULL, NULL, NULL,
2589 &destination->addr, &destination->local_addr, NULL, NULL);
2590
2591 /* Requeue timeout. We don't care if interval drifts gradually. */
2592 SCH_AddTimeoutInClass(destination->interval, get_separation(poll), SAMPLING_RANDOMNESS,
2593 SCH_NtpBroadcastClass, broadcast_timeout, arg);
2594 }
2595
2596 /* ================================================== */
2597
2598 void
2599 NCR_AddBroadcastDestination(IPAddr *addr, unsigned short port, int interval)
2600 {
2601 BroadcastDestination *destination;
2602
2603 destination = (BroadcastDestination *)ARR_GetNewElement(broadcasts);
2604
2605 destination->addr.ip_addr = *addr;
2606 destination->addr.port = port;
2607 destination->local_addr.ip_addr.family = IPADDR_UNSPEC;
2608 destination->local_addr.if_index = INVALID_IF_INDEX;
2609 destination->local_addr.sock_fd = NIO_OpenServerSocket(&destination->addr);
2610 destination->auth = NAU_CreateNoneInstance();
2611 destination->interval = CLAMP(1, interval, 1 << MAX_POLL);
2612
2613 SCH_AddTimeoutInClass(destination->interval, MAX_SAMPLING_SEPARATION, SAMPLING_RANDOMNESS,
2614 SCH_NtpBroadcastClass, broadcast_timeout,
2615 (void *)(long)(ARR_GetSize(broadcasts) - 1));
2616 }