2 chronyd/chronyc - Programs for keeping computer clocks accurate.
4 **********************************************************************
5 * Copyright (C) Richard P. Curnow 1997-2003
6 * Copyright (C) Miroslav Lichvar 2009-2018
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.
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.
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.
21 **********************************************************************
23 =======================================================================
25 Core NTP protocol engine
38 #include "reference.h"
40 #include "samplefilt.h"
47 #include "clientlog.h"
49 /* ================================================== */
51 static LOG_FileID logfileid
;
52 static int log_raw_measurements
;
54 /* ================================================== */
55 /* Enumeration used for remembering the operating mode of one of the
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 */
65 /* ================================================== */
66 /* Structure used for holding a single peer/server's
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 */
81 int auto_burst
; /* If 1, initiate a burst on each poll */
82 int auto_offline
; /* If 1, automatically go offline when requests
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
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
101 int presend_done
; /* The presend packet has been sent */
103 int minpoll
; /* Log2 of minimum defined polling interval */
104 int maxpoll
; /* Log2 of maximum defined polling interval */
106 int min_stratum
; /* Increase stratum in received packets to the
109 int poll_target
; /* Target number of sourcestats samples */
111 int version
; /* Version set in packets for server/peer */
113 double poll_score
; /* Score of current local poll */
115 double max_delay
; /* Maximum round-trip delay to the
116 peer that we can tolerate and still
117 use the sample for generating
120 double max_delay_ratio
; /* Largest ratio of delay /
121 min_delay_in_register that we can
124 double max_delay_dev_ratio
; /* Maximum ratio of increase in delay / stddev */
126 double offset_correction
; /* Correction applied to measured offset
127 (e.g. for asymmetry in network delay) */
129 NAU_Instance auth
; /* Authentication */
131 /* Count of transmitted packets since last valid response */
132 unsigned int tx_count
;
134 /* Flag indicating a valid response was received since last request */
137 /* Flag indicating the timestamps below are from a valid packet and may
138 be used for synchronisation */
139 int valid_timestamps
;
141 /* Receive and transmit timestamps from the last valid response */
142 NTP_int64 remote_ntp_rx
;
143 NTP_int64 remote_ntp_tx
;
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
;
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
;
167 /* Previous values of some variables needed in interleaved mode */
168 NTP_Local_Timestamp prev_local_tx
;
170 unsigned int prev_tx_count
;
172 /* Flag indicating the two timestamps below were updated since the
174 int updated_init_timestamps
;
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
;
181 /* The instance record in the main source management module. This
182 performs the statistical analysis on the samples we generate */
186 /* Optional median filter for NTP measurements */
189 int burst_good_samples_to_go
;
190 int burst_total_samples_to_go
;
192 /* Report from last valid response */
193 RPT_NTPReport report
;
197 NTP_Remote_Address addr
;
198 NTP_Local_Address local_addr
;
201 } BroadcastDestination
;
203 /* Array of BroadcastDestination */
204 static ARR_Instance broadcasts
;
206 /* ================================================== */
207 /* Initial delay period before first packet is transmitted (in seconds) */
208 #define INITIAL_DELAY 0.2
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
215 /* Randomness added to spacing between samples for one server/peer */
216 #define SAMPLING_RANDOMNESS 0.02
218 /* Adjustment of the peer polling interval */
219 #define PEER_SAMPLING_ADJ 1.1
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
226 /* Number of samples in initial burst */
227 #define IBURST_GOOD_SAMPLES 4
228 #define IBURST_TOTAL_SAMPLES SOURCE_REACH_BITS
230 /* Number of samples in automatic burst */
231 #define BURST_GOOD_SAMPLES 1
232 #define MAX_BURST_TOTAL_SAMPLES 4
234 /* Time to wait after sending packet to 'warm up' link */
235 #define WARM_UP_DELAY 2.0
237 /* Compatible NTP protocol versions */
238 #define NTP_MAX_COMPAT_VERSION NTP_VERSION
239 #define NTP_MIN_COMPAT_VERSION 1
241 /* Maximum allowed dispersion - as defined in RFC 5905 (16 seconds) */
242 #define NTP_MAX_DISPERSION 16.0
244 /* Maximum allowed time for server to process client packet */
245 #define MAX_SERVER_INTERVAL 4.0
247 /* Maximum acceptable delay in transmission for timestamp correction */
248 #define MAX_TX_DELAY 1.0
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
255 /* Minimum and maximum allowed poll interval */
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
264 /* Kiss-o'-Death codes */
265 #define KOD_RATE 0x52415445UL /* RATE */
267 /* Maximum poll interval set by KoD RATE */
268 #define MAX_KOD_RATE_POLL SRC_DEFAULT_MAXPOLL
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
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
278 /* Invalid socket, different from the one in ntp_io.c */
279 #define INVALID_SOCK_FD -2
281 /* ================================================== */
283 /* Server IPv4/IPv6 sockets */
284 static int server_sock_fd4
;
285 static int server_sock_fd6
;
287 static ADF_AuthTable access_auth_table
;
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'};
293 /* ================================================== */
294 /* Forward prototypes */
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
);
301 /* ================================================== */
306 /* Assertions to check the sizes of certain data types
307 and the positions of certain record fields */
309 /* Check that certain invariants are true */
310 assert(sizeof(NTP_int32
) == 4);
311 assert(sizeof(NTP_int64
) == 8);
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);
327 /* ================================================== */
333 time_t warning_advance
= 3600 * 24 * 365 * 10; /* 10 years */
335 #ifdef HAVE_LONG_TIME_T
336 /* Check that time before NTP_ERA_SPLIT underflows correctly */
338 struct timespec ts1
= {NTP_ERA_SPLIT
, 1}, ts2
= {NTP_ERA_SPLIT
- 1, 1};
339 NTP_int64 nts1
, nts2
;
342 UTI_TimespecToNtp64(&ts1
, &nts1
, NULL
);
343 UTI_TimespecToNtp64(&ts2
, &nts2
, NULL
);
344 UTI_Ntp64ToTimespec(&nts1
, &ts1
);
345 UTI_Ntp64ToTimespec(&nts2
, &ts2
);
347 r
= ts1
.tv_sec
== NTP_ERA_SPLIT
&&
348 ts1
.tv_sec
+ (1ULL << 32) - 1 == ts2
.tv_sec
;
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
));
356 LCL_ReadRawTime(&now
);
357 if (now
.tv_sec
> 0x7fffffff - warning_advance
)
358 LOG(LOGS_WARN
, "System time ends at %s!", UTI_TimeToLogForm(0x7fffffff));
362 /* ================================================== */
365 zero_local_timestamp(NTP_Local_Timestamp
*ts
)
367 UTI_ZeroTimespec(&ts
->ts
);
369 ts
->source
= NTP_TS_DAEMON
;
372 /* ================================================== */
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")
384 access_auth_table
= ADF_CreateTable();
385 broadcasts
= ARR_CreateInstance(sizeof (BroadcastDestination
));
387 /* Server socket will be opened when access is allowed */
388 server_sock_fd4
= INVALID_SOCK_FD
;
389 server_sock_fd6
= INVALID_SOCK_FD
;
392 /* ================================================== */
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
);
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
);
409 ARR_DestroyInstance(broadcasts
);
410 ADF_DestroyTable(access_auth_table
);
413 /* ================================================== */
416 restart_timeout(NCR_Instance inst
, double delay
)
418 /* Check if we can transmit */
419 if (inst
->tx_suspended
) {
420 assert(!inst
->tx_timeout_id
);
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
);
429 /* Start new timer for transmission */
430 inst
->tx_timeout_id
= SCH_AddTimeoutInClass(delay
, get_separation(inst
->local_poll
),
432 inst
->mode
== MODE_CLIENT
?
433 SCH_NtpClientClass
: SCH_NtpPeerClass
,
434 transmit_timeout
, (void *)inst
);
437 /* ================================================== */
440 start_initial_timeout(NCR_Instance inst
)
442 double delay
, last_tx
;
445 if (!inst
->tx_timeout_id
) {
446 /* This will be the first transmission after mode change */
448 /* Mark source active */
449 SRC_SetActive(inst
->source
);
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
455 SCH_GetLastEventTime(&now
, NULL
, NULL
);
456 last_tx
= UTI_DiffTimespecsToDouble(&now
, &inst
->local_tx
.ts
);
459 delay
= get_transmit_delay(inst
, 0, 0.0) - last_tx
;
460 if (delay
< INITIAL_DELAY
)
461 delay
= INITIAL_DELAY
;
463 restart_timeout(inst
, delay
);
466 /* ================================================== */
469 close_client_socket(NCR_Instance inst
)
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
;
476 SCH_RemoveTimeout(inst
->rx_timeout_id
);
477 inst
->rx_timeout_id
= 0;
480 /* ================================================== */
483 take_offline(NCR_Instance inst
)
485 inst
->opmode
= MD_OFFLINE
;
487 SCH_RemoveTimeout(inst
->tx_timeout_id
);
488 inst
->tx_timeout_id
= 0;
490 /* Mark source unreachable */
491 SRC_ResetReachability(inst
->source
);
494 SRC_UnsetActive(inst
->source
);
496 close_client_socket(inst
);
498 NCR_ResetInstance(inst
);
501 /* ================================================== */
504 NCR_CreateInstance(NTP_Remote_Address
*remote_addr
, NTP_Source_Type type
,
505 SourceParameters
*params
, const char *name
)
509 result
= MallocNew(struct NCR_Instance_Record
);
511 result
->remote_addr
= *remote_addr
;
512 result
->local_addr
.ip_addr
.family
= IPADDR_UNSPEC
;
513 result
->local_addr
.if_index
= INVALID_IF_INDEX
;
517 /* Client socket will be obtained when sending request */
518 result
->local_addr
.sock_fd
= INVALID_SOCK_FD
;
519 result
->mode
= MODE_CLIENT
;
522 result
->local_addr
.sock_fd
= NIO_OpenServerSocket(remote_addr
);
523 result
->mode
= MODE_ACTIVE
;
529 result
->interleaved
= params
->interleaved
;
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
;
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
;
545 result
->min_stratum
= params
->min_stratum
;
546 if (result
->min_stratum
>= NTP_MAX_STRATUM
)
547 result
->min_stratum
= NTP_MAX_STRATUM
- 1;
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;
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
;
563 IPSockAddr nts_address
;
565 if (result
->mode
== MODE_ACTIVE
)
566 LOG(LOGS_WARN
, "NTS not supported with peers");
568 nts_address
.ip_addr
= remote_addr
->ip_addr
;
569 nts_address
.port
= params
->nts_port
;
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
);
575 result
->auth
= NAU_CreateNoneInstance();
578 result
->version
= NAU_GetSuggestedNtpVersion(result
->auth
);
581 result
->version
= CLAMP(NTP_MIN_COMPAT_VERSION
, params
->version
, NTP_VERSION
);
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
);
590 if (params
->filter_length
>= 1)
591 result
->filter
= SPF_CreateInstance(params
->filter_length
, params
->filter_length
,
592 NTP_MAX_DISPERSION
, 0.0);
594 result
->filter
= NULL
;
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
));
609 NCR_ResetInstance(result
);
611 if (params
->iburst
) {
612 NCR_InitiateSampleBurst(result
, IBURST_GOOD_SAMPLES
, IBURST_TOTAL_SAMPLES
);
618 /* ================================================== */
620 /* Destroy an instance */
622 NCR_DestroyInstance(NCR_Instance instance
)
624 if (instance
->opmode
!= MD_OFFLINE
)
625 take_offline(instance
);
627 if (instance
->mode
== MODE_ACTIVE
)
628 NIO_CloseServerSocket(instance
->local_addr
.sock_fd
);
630 if (instance
->filter
)
631 SPF_DestroyInstance(instance
->filter
);
633 NAU_DestroyInstance(instance
->auth
);
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
);
640 /* Free the data structure */
644 /* ================================================== */
647 NCR_StartInstance(NCR_Instance instance
)
649 instance
->tx_suspended
= 0;
650 if (instance
->opmode
!= MD_OFFLINE
)
651 start_initial_timeout(instance
);
654 /* ================================================== */
657 NCR_ResetInstance(NCR_Instance instance
)
659 instance
->tx_count
= 0;
660 instance
->presend_done
= 0;
662 instance
->remote_poll
= 0;
663 instance
->remote_stratum
= 0;
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
);
673 zero_local_timestamp(&instance
->prev_local_tx
);
674 instance
->prev_local_poll
= 0;
675 instance
->prev_tx_count
= 0;
677 instance
->updated_init_timestamps
= 0;
678 UTI_ZeroNtp64(&instance
->init_remote_ntp_tx
);
679 zero_local_timestamp(&instance
->init_local_rx
);
681 if (instance
->filter
)
682 SPF_DropSamples(instance
->filter
);
685 /* ================================================== */
688 NCR_ResetPoll(NCR_Instance instance
)
690 if (instance
->local_poll
!= instance
->minpoll
) {
691 instance
->local_poll
= instance
->minpoll
;
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));
699 /* ================================================== */
702 NCR_ChangeRemoteAddress(NCR_Instance inst
, NTP_Remote_Address
*remote_addr
, int ntp_only
)
704 memset(&inst
->report
, 0, sizeof (inst
->report
));
705 NCR_ResetInstance(inst
);
707 /* Update the authentication-specific address before NTP address */
709 NAU_ChangeAddress(inst
->auth
, &remote_addr
->ip_addr
);
711 inst
->remote_addr
= *remote_addr
;
713 if (inst
->mode
== MODE_CLIENT
)
714 close_client_socket(inst
);
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
);
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
);
728 /* ================================================== */
731 adjust_poll(NCR_Instance inst
, double adj
)
733 inst
->poll_score
+= adj
;
735 if (inst
->poll_score
>= 1.0) {
736 inst
->local_poll
+= (int)inst
->poll_score
;
737 inst
->poll_score
-= (int)inst
->poll_score
;
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);
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;
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
;
762 /* ================================================== */
765 get_poll_adj(NCR_Instance inst
, double error_in_estimate
, double peer_distance
)
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);
776 samples
= SST_Samples(SRC_GetSourcestats(inst
->source
));
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
;
782 /* Make interval shortening quicker */
783 if (samples
< inst
->poll_target
) {
791 /* ================================================== */
794 get_transmit_poll(NCR_Instance inst
)
798 poll
= inst
->local_poll
;
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
);
809 /* ================================================== */
812 get_transmit_delay(NCR_Instance inst
, int on_tx
, double last_tx
)
814 int poll_to_use
, stratum_diff
;
817 /* If we're in burst mode, queue for immediate dispatch.
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.
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. */
829 poll_to_use
= get_transmit_poll(inst
);
830 delay_time
= UTI_Log2ToDouble(poll_to_use
);
832 switch (inst
->opmode
) {
839 if (inst
->presend_done
)
840 delay_time
= WARM_UP_DELAY
;
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
;
855 /* Substract the already spend time */
857 delay_time
-= last_tx
;
858 if (delay_time
< 0.0)
868 case MD_BURST_WAS_ONLINE
:
869 case MD_BURST_WAS_OFFLINE
:
871 delay_time
= MIN(MAX_BURST_INTERVAL
, MAX_BURST_POLL_RATIO
* delay_time
);
881 /* ================================================== */
882 /* Calculate sampling separation for given polling interval */
885 get_separation(int poll
)
889 assert(poll
>= MIN_POLL
&& poll
<= MAX_POLL
);
891 /* Allow up to 8 sources using the same short interval to not be limited
893 separation
= UTI_Log2ToDouble(poll
- 3);
895 return CLAMP(MIN_SAMPLING_SEPARATION
, separation
, MAX_SAMPLING_SEPARATION
);
898 /* ================================================== */
899 /* Timeout handler for closing the client socket when no acceptable
900 reply can be received from the server */
903 receive_timeout(void *arg
)
905 NCR_Instance inst
= (NCR_Instance
)arg
;
907 DEBUG_LOG("Receive timeout for %s", UTI_IPSockAddrToString(&inst
->remote_addr
));
909 inst
->rx_timeout_id
= 0;
910 close_client_socket(inst
);
913 /* ================================================== */
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 */
939 struct timespec local_receive
, local_transmit
;
940 double smooth_offset
, local_transmit_err
;
944 /* Parameters read from reference module */
945 int are_we_synchronised
, our_stratum
, smooth_time
;
946 NTP_Leap leap_status
;
948 struct timespec our_ref_time
;
949 double our_root_delay
, our_root_dispersion
;
951 assert(auth
|| (request
&& request_info
));
953 /* Don't reply with version higher than ours */
954 if (version
> NTP_VERSION
) {
955 version
= NTP_VERSION
;
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
)))
965 if (my_mode
== MODE_CLIENT
) {
966 /* Don't reveal local time or state of the clock in client packets */
968 leap_status
= our_stratum
= our_ref_id
= 0;
969 our_root_delay
= our_root_dispersion
= 0.0;
970 UTI_ZeroTimespec(&our_ref_time
);
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
);
976 REF_GetReferenceParams(&local_transmit
,
977 &are_we_synchronised
, &leap_status
,
979 &our_ref_id
, &our_ref_time
,
980 &our_root_delay
, &our_root_dispersion
);
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();
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
;
993 precision
= LCL_GetSysPrecisionAsLog();
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
);
1001 local_receive
= local_rx
->ts
;
1005 leap_status
= LEAP_Unsynchronised
;
1006 our_stratum
= NTP_INVALID_STRATUM
;
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
;
1016 message
.stratum
= NTP_INVALID_STRATUM
;
1019 message
.poll
= my_poll
;
1020 message
.precision
= precision
;
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
);
1027 message
.reference_id
= htonl(our_ref_id
);
1029 /* Now fill in timestamps */
1031 UTI_TimespecToNtp64(&our_ref_time
, &message
.reference_ts
, NULL
);
1033 /* Don't reveal timestamps which are not necessary for the protocol */
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
;
1040 /* Prepare random bits which will be added to the receive timestamp */
1041 UTI_GetNtp64Fuzz(&ts_fuzz
, precision
);
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
);
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
));
1055 UTI_ZeroNtp64(&message
.originate_ts
);
1056 UTI_ZeroNtp64(&message
.receive_ts
);
1060 if (!parse_packet(&message
, NTP_HEADER_LENGTH
, &info
))
1063 /* Prepare random bits which will be added to the transmit timestamp */
1064 UTI_GetNtp64Fuzz(&ts_fuzz
, precision
);
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
);
1072 UTI_AddDoubleToTimespec(&local_transmit
, smooth_offset
, &local_transmit
);
1074 /* Pre-compensate the transmit time by approximately how long it will take
1075 to generate the authentication data */
1077 NAU_AdjustRequestTimestamp(auth
, &local_transmit
);
1079 NAU_AdjustResponseTimestamp(request
, request_info
, &local_transmit
);
1081 UTI_TimespecToNtp64(interleaved
? &local_tx
->ts
: &local_transmit
,
1082 &message
.transmit_ts
, &ts_fuzz
);
1084 /* Generate the authentication data */
1086 if (!NAU_GenerateRequestAuth(auth
, &message
, &info
)) {
1087 DEBUG_LOG("Could not generate request auth");
1091 if (!NAU_GenerateResponseAuth(request
, request_info
, &message
, &info
,
1092 where_to
, from
, kod
)) {
1093 DEBUG_LOG("Could not generate response auth");
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
));
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
);
1115 ret
= NIO_SendPacket(&message
, where_to
, from
, info
.length
, local_tx
!= NULL
);
1118 local_tx
->ts
= local_transmit
;
1119 local_tx
->err
= local_transmit_err
;
1120 local_tx
->source
= NTP_TS_DAEMON
;
1124 *local_ntp_rx
= message
.receive_ts
;
1126 *local_ntp_tx
= message
.transmit_ts
;
1131 /* ================================================== */
1132 /* Timeout handler for transmitting to a source. */
1135 transmit_timeout(void *arg
)
1137 NCR_Instance inst
= (NCR_Instance
) arg
;
1138 NTP_Local_Address local_addr
;
1139 int interleaved
, initial
, sent
;
1141 inst
->tx_timeout_id
= 0;
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
;
1149 case MD_BURST_WAS_OFFLINE
:
1150 if (inst
->burst_total_samples_to_go
<= 0)
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
));
1166 if (inst
->opmode
== MD_OFFLINE
) {
1170 DEBUG_LOG("Transmit timeout for %s", UTI_IPSockAddrToString(&inst
->remote_addr
));
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));
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
);
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
;
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));
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
);
1214 /* Prepare for the response */
1216 inst
->updated_init_timestamps
= 0;
1218 inst
->valid_timestamps
= 0;
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
--;
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,
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
);
1242 inst
->report
.total_tx_count
++;
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. */
1248 if (inst
->tx_count
>= 2) {
1249 /* Implies we have missed at least one transmission */
1252 adjust_poll(inst
, SRC_IsSyncPeer(inst
->source
) ? 0.1 : 0.25);
1255 SRC_UpdateReachability(inst
->source
, 0);
1258 /* With auto_offline take the source offline if sending failed */
1259 if (!sent
&& inst
->auto_offline
)
1260 NCR_SetConnectivity(inst
, SRC_OFFLINE
);
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
))
1268 case MD_BURST_WAS_OFFLINE
:
1269 --inst
->burst_total_samples_to_go
;
1277 /* Restart timer for this message */
1278 restart_timeout(inst
, get_transmit_delay(inst
, 1, 0.0));
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
);
1288 /* ================================================== */
1291 parse_packet(NTP_Packet
*packet
, int length
, NTP_PacketInfo
*info
)
1293 if (length
< NTP_HEADER_LENGTH
|| length
% 4U != 0) {
1294 DEBUG_LOG("NTP packet has invalid length %d", length
);
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
;
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
);
1309 /* Parse authentication extension fields or MAC */
1310 if (!NAU_ParsePacket(packet
, info
))
1316 /* ================================================== */
1319 check_delay_ratio(NCR_Instance inst
, SST_Stats stats
,
1320 struct timespec
*sample_time
, double delay
)
1322 double last_sample_ago
, predicted_offset
, min_delay
, skew
, std_dev
;
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
))
1330 max_delay
= min_delay
* inst
->max_delay_ratio
+
1331 last_sample_ago
* (skew
+ LCL_GetMaxClockError());
1333 if (delay
<= max_delay
)
1336 DEBUG_LOG("maxdelayratio: delay=%e max_delay=%e", delay
, max_delay
);
1340 /* ================================================== */
1343 check_delay_dev_ratio(NCR_Instance inst
, SST_Stats stats
,
1344 struct timespec
*sample_time
, double offset
, double delay
)
1346 double last_sample_ago
, predicted_offset
, min_delay
, skew
, std_dev
;
1347 double delta
, max_delta
, error_in_estimate
;
1349 if (!SST_GetDelayTestData(stats
, sample_time
, &last_sample_ago
,
1350 &predicted_offset
, &min_delay
, &skew
, &std_dev
))
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. */
1357 max_delta
= std_dev
* inst
->max_delay_dev_ratio
+
1358 last_sample_ago
* (skew
+ LCL_GetMaxClockError());
1359 delta
= (delay
- min_delay
) / 2.0;
1361 if (delta
<= max_delta
)
1364 error_in_estimate
= offset
+ predicted_offset
;
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
)
1372 DEBUG_LOG("maxdelaydevratio: error=%e delay=%e delta=%e max_delta=%e",
1373 error_in_estimate
, delay
, delta
, max_delta
);
1377 /* ================================================== */
1380 check_sync_loop(NCR_Instance inst
, NTP_Packet
*message
, NTP_Local_Address
*local_addr
,
1381 struct timespec
*local_ts
)
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
;
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())
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
1397 if (message
->stratum
> 1 &&
1398 message
->reference_id
== htonl(UTI_IPToRefid(&local_addr
->ip_addr
)))
1401 /* Compare our reference data with the source to make sure it is not us
1402 (e.g. due to a misconfiguration) */
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
);
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
;
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
));
1423 /* ================================================== */
1426 process_sample(NCR_Instance inst
, NTP_Sample
*sample
)
1428 double estimated_offset
, error_in_estimate
, filtered_sample_ago
;
1429 NTP_Sample filtered_sample
;
1430 int filtered_samples
;
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. */
1436 SPF_AccumulateSample(inst
->filter
, sample
);
1438 filtered_samples
= SPF_GetNumberOfSamples(inst
->filter
);
1440 if (!SPF_GetFilteredSample(inst
->filter
, &filtered_sample
))
1443 filtered_sample_ago
= UTI_DiffTimespecsToDouble(&sample
->time
, &filtered_sample
.time
);
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
,
1452 sample
= &filtered_sample
;
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
);
1460 error_in_estimate
= fabs(-sample
->offset
- estimated_offset
);
1462 SRC_AccumulateSample(inst
->source
, sample
);
1463 SRC_SelectSource(inst
->source
);
1465 adjust_poll(inst
, get_poll_adj(inst
, error_in_estimate
,
1466 sample
->peer_dispersion
+ 0.5 * sample
->peer_delay
));
1469 /* ================================================== */
1472 process_response(NCR_Instance inst
, NTP_Local_Address
*local_addr
,
1473 NTP_Local_Timestamp
*rx_ts
, NTP_Packet
*message
, NTP_PacketInfo
*info
)
1478 int pkt_leap
, pkt_version
;
1480 double pkt_root_delay
;
1481 double pkt_root_dispersion
;
1483 /* The skew and estimated frequency offset relative to the remote source */
1484 double skew
, source_freq_lo
, source_freq_hi
;
1486 /* RFC 5905 packet tests */
1487 int test1
, test2n
, test2i
, test2
, test3
, test5
, test6
, test7
;
1488 int interleaved_packet
, valid_packet
, synced_packet
;
1490 /* Additional tests */
1491 int testA
, testB
, testC
, testD
;
1494 /* Kiss-o'-Death codes */
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
;
1502 /* ==================== */
1504 stats
= SRC_GetSourcestats(inst
->source
);
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
);
1512 /* Check if the packet is valid per RFC 5905, section 8.
1513 The test values are 1 when passed and 0 when failed. */
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
);
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
;
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
);
1533 /* Test 4 would check for denied access. It would always pass as this
1534 function is called only for known sources. */
1536 /* Test 5 checks for authentication failure */
1537 test5
= NAU_CheckResponseAuth(inst
->auth
, message
, info
);
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
;
1544 /* Test 7 checks for bad data. The root distance must be smaller than a
1546 test7
= pkt_root_delay
/ 2.0 + pkt_root_dispersion
< NTP_MAX_DISPERSION
;
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
;
1553 /* Check for Kiss-o'-Death codes */
1555 if (test1
&& test2
&& test5
&& pkt_leap
== LEAP_Unsynchronised
&&
1556 message
->stratum
== NTP_INVALID_STRATUM
) {
1557 if (pkt_refid
== KOD_RATE
)
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
;
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
;
1580 UTI_Ntp64ToTimespec(&message
->receive_ts
, &remote_receive
);
1581 UTI_Ntp64ToTimespec(&inst
->remote_ntp_rx
, &remote_request_receive
);
1582 local_transmit
= inst
->local_tx
;
1584 UTI_Ntp64ToTimespec(&message
->transmit_ts
, &remote_transmit
);
1585 UTI_Ntp64ToTimespec(&inst
->remote_ntp_tx
, &prev_remote_transmit
);
1586 local_receive
= inst
->local_rx
;
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
;
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
));
1604 precision
= LCL_GetSysPrecisionAsQuantum() + UTI_Log2ToDouble(message
->precision
);
1606 /* Calculate delay */
1607 sample
.peer_delay
= fabs(local_interval
- remote_interval
);
1608 if (sample
.peer_delay
< precision
)
1609 sample
.peer_delay
= precision
;
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
);
1615 /* Apply configured correction */
1616 sample
.offset
+= inst
->offset_correction
;
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
1623 sample
.time
= local_average
;
1625 SST_GetFrequencyRange(stats
, &source_freq_lo
, &source_freq_hi
);
1627 /* Calculate skew */
1628 skew
= (source_freq_hi
- source_freq_lo
) / 2.0;
1630 /* and then calculate peer dispersion */
1631 sample
.peer_dispersion
= MAX(precision
, MAX(local_transmit
.err
, local_receive
.err
)) +
1632 skew
* fabs(local_interval
);
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
));
1639 /* Additional tests required to pass before accumulating the sample */
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
)));
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
);
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
);
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
);
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;
1680 /* The packet is considered good for synchronisation if
1681 the additional tests passed */
1682 good_packet
= testA
&& testB
&& testC
&& testD
;
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
);
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
&&
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
;
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;
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
;
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;
1723 updated_timestamps
= 0;
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
) {
1732 valid_packet
= synced_packet
= good_packet
= 0;
1733 } else if (valid_packet
) {
1734 if (inst
->presend_done
) {
1741 if ((unsigned int)local_receive
.source
>= sizeof (tss_chars
) ||
1742 (unsigned int)local_transmit
.source
>= sizeof (tss_chars
))
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
);
1767 inst
->remote_poll
= message
->poll
;
1768 inst
->remote_stratum
= message
->stratum
!= NTP_INVALID_STRATUM
?
1769 message
->stratum
: NTP_MAX_STRATUM
;
1771 inst
->prev_local_poll
= inst
->local_poll
;
1772 inst
->prev_tx_count
= inst
->tx_count
;
1775 SRC_UpdateReachability(inst
->source
, synced_packet
);
1776 SRC_SetLeapStatus(inst
->source
, pkt_leap
);
1779 /* Adjust the polling interval, accumulate the sample, etc. */
1780 process_sample(inst
, &sample
);
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
;
1799 /* Slowly increase the polling interval if we can't get good packet */
1800 adjust_poll(inst
, 0.1);
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
);
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
;
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
));
1817 LOG(LOGS_WARN
, "Received KoD RATE from %s",
1818 UTI_IPToString(&inst
->remote_addr
.ip_addr
));
1820 /* Back off for a while and stop ongoing burst */
1821 delay_time
+= 4 * UTI_Log2ToDouble(inst
->local_poll
);
1823 if (inst
->opmode
== MD_BURST_WAS_OFFLINE
|| inst
->opmode
== MD_BURST_WAS_ONLINE
) {
1824 inst
->burst_good_samples_to_go
= 0;
1828 /* Get rid of old timeout and start a new one */
1829 assert(inst
->tx_timeout_id
);
1830 restart_timeout(inst
, delay_time
);
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
];
1860 inst
->report
.total_valid_count
++;
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
],
1870 test1
, test2
, test3
, test5
, test6
, test7
, testA
, testB
, testC
, testD
,
1871 inst
->local_poll
, message
->poll
,
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
]);
1883 /* ================================================== */
1884 /* From RFC 5905, the standard handling of received packets, depending
1885 on the mode of the packet and of the source, is :
1887 +------------------+---------------------------------------+
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 +------------------+-------+-------+-------+-------+-------+
1901 Association mode 0 is implemented in NCR_ProcessRxUnknown(), other modes
1902 in NCR_ProcessRxKnown().
1904 Broadcast, manycast and ephemeral symmetric passive associations are not
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 */
1913 NCR_ProcessRxKnown(NCR_Instance inst
, NTP_Local_Address
*local_addr
,
1914 NTP_Local_Timestamp
*rx_ts
, NTP_Packet
*message
, int length
)
1916 int proc_packet
, proc_as_unknown
;
1917 NTP_PacketInfo info
;
1919 inst
->report
.total_rx_count
++;
1921 if (!parse_packet(message
, length
, &info
))
1925 proc_as_unknown
= 0;
1927 /* Now, depending on the mode we decide what to do */
1928 switch (info
.mode
) {
1930 switch (inst
->mode
) {
1932 /* Ordinary symmetric peering */
1936 /* In this software this case should not arise, we don't
1937 support unconfigured peers */
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;
1951 switch (inst
->mode
) {
1953 /* This would arise if we have the remote configured as a peer and
1954 he does not have us configured */
1958 /* Error condition in RFC 5905 */
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.
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. */
1980 proc_as_unknown
= 1;
1984 switch (inst
->mode
) {
1986 /* Standard case where he's a server and we're the client */
1995 case MODE_BROADCAST
:
1996 /* Just ignore these */
2000 /* Obviously ignore */
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
);
2012 /* Ignore packets from offline sources */
2013 if (inst
->opmode
== MD_OFFLINE
|| inst
->tx_suspended
) {
2014 DEBUG_LOG("Packet from offline source");
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 */
2024 DEBUG_LOG("NTP packet discarded mode=%d our_mode=%u", (int)info
.mode
, inst
->mode
);
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) */
2034 NCR_ProcessRxUnknown(NTP_Remote_Address
*remote_addr
, NTP_Local_Address
*local_addr
,
2035 NTP_Local_Timestamp
*rx_ts
, NTP_Packet
*message
, int length
)
2037 NTP_PacketInfo info
;
2039 NTP_int64
*local_ntp_rx
, *local_ntp_tx
;
2040 NTP_Local_Timestamp local_tx
, *tx_ts
;
2041 int log_index
, interleaved
, poll
, version
;
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
);
2050 if (!parse_packet(message
, length
, &info
))
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
));
2059 switch (info
.mode
) {
2061 /* We are symmetric passive, even though we don't ever lock to him */
2062 my_mode
= MODE_PASSIVE
;
2065 /* Reply with server packet */
2066 my_mode
= MODE_SERVER
;
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
;
2079 DEBUG_LOG("NTP packet discarded mode=%d", (int)info
.mode
);
2084 log_index
= CLG_LogNTPAccess(&remote_addr
->ip_addr
, &rx_ts
->ts
);
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");
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
);
2096 /* Don't respond unless a non-zero KoD was returned */
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
)
2108 version
= info
.version
;
2110 local_ntp_rx
= local_ntp_tx
= NULL
;
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
);
2126 UTI_Ntp64ToTimespec(local_ntp_tx
, &local_tx
.ts
);
2129 UTI_ZeroNtp64(local_ntp_tx
);
2130 local_ntp_tx
= NULL
;
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
);
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
,
2145 /* Save the transmit timestamp */
2147 UTI_TimespecToNtp64(&tx_ts
->ts
, local_ntp_tx
, NULL
);
2150 /* ================================================== */
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
)
2158 if (UTI_IsZeroTimespec(&tx_ts
->ts
)) {
2159 DEBUG_LOG("Unexpected TX update");
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");
2170 delay
= UTI_DiffTimespecsToDouble(&new_tx_ts
->ts
, &tx_ts
->ts
);
2172 if (delay
< 0.0 || delay
> MAX_TX_DELAY
) {
2173 DEBUG_LOG("Unacceptable TX delay %.9f", delay
);
2177 *tx_ts
= *new_tx_ts
;
2179 DEBUG_LOG("Updated TX timestamp delay=%.9f", delay
);
2182 /* ================================================== */
2185 NCR_ProcessTxKnown(NCR_Instance inst
, NTP_Local_Address
*local_addr
,
2186 NTP_Local_Timestamp
*tx_ts
, NTP_Packet
*message
, int length
)
2188 NTP_PacketInfo info
;
2190 if (!parse_packet(message
, length
, &info
))
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
);
2199 update_tx_timestamp(&inst
->local_tx
, tx_ts
, &inst
->local_ntp_rx
, &inst
->local_ntp_tx
,
2203 /* ================================================== */
2206 NCR_ProcessTxUnknown(NTP_Remote_Address
*remote_addr
, NTP_Local_Address
*local_addr
,
2207 NTP_Local_Timestamp
*tx_ts
, NTP_Packet
*message
, int length
)
2209 NTP_int64
*local_ntp_rx
, *local_ntp_tx
;
2210 NTP_Local_Timestamp local_tx
;
2211 NTP_PacketInfo info
;
2214 if (!parse_packet(message
, length
, &info
))
2217 if (info
.mode
== MODE_BROADCAST
)
2220 log_index
= CLG_GetClientIndex(&remote_addr
->ip_addr
);
2224 if (SMT_IsEnabled() && info
.mode
== MODE_SERVER
)
2225 UTI_AddDoubleToTimespec(&tx_ts
->ts
, SMT_GetOffset(&tx_ts
->ts
), &tx_ts
->ts
);
2227 CLG_GetNtpTimestamps(log_index
, &local_ntp_rx
, &local_ntp_tx
);
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
);
2234 /* ================================================== */
2237 NCR_SlewTimes(NCR_Instance inst
, struct timespec
*when
, double dfreq
, double doffset
)
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
,
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
,
2253 SPF_SlewSamples(inst
->filter
, when
, dfreq
, doffset
);
2256 /* ================================================== */
2259 NCR_SetConnectivity(NCR_Instance inst
, SRC_Connectivity connectivity
)
2263 s
= UTI_IPToString(&inst
->remote_addr
.ip_addr
);
2265 if (connectivity
== SRC_MAYBE_ONLINE
)
2266 connectivity
= NIO_IsServerConnectable(&inst
->remote_addr
) ? SRC_ONLINE
: SRC_OFFLINE
;
2268 switch (connectivity
) {
2270 switch (inst
->opmode
) {
2275 LOG(LOGS_INFO
, "Source %s online", s
);
2276 inst
->opmode
= MD_ONLINE
;
2277 NCR_ResetInstance(inst
);
2278 start_initial_timeout(inst
);
2280 case MD_BURST_WAS_ONLINE
:
2283 case MD_BURST_WAS_OFFLINE
:
2284 inst
->opmode
= MD_BURST_WAS_ONLINE
;
2285 LOG(LOGS_INFO
, "Source %s online", s
);
2292 switch (inst
->opmode
) {
2294 LOG(LOGS_INFO
, "Source %s offline", s
);
2299 case MD_BURST_WAS_ONLINE
:
2300 inst
->opmode
= MD_BURST_WAS_OFFLINE
;
2301 LOG(LOGS_INFO
, "Source %s offline", s
);
2303 case MD_BURST_WAS_OFFLINE
:
2314 /* ================================================== */
2317 NCR_ModifyMinpoll(NCR_Instance inst
, int new_minpoll
)
2319 if (new_minpoll
< MIN_POLL
|| new_minpoll
> MAX_POLL
)
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
);
2327 /* ================================================== */
2330 NCR_ModifyMaxpoll(NCR_Instance inst
, int new_maxpoll
)
2332 if (new_maxpoll
< MIN_POLL
|| new_maxpoll
> MAX_POLL
)
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
);
2340 /* ================================================== */
2343 NCR_ModifyMaxdelay(NCR_Instance inst
, double new_max_delay
)
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
);
2350 /* ================================================== */
2353 NCR_ModifyMaxdelayratio(NCR_Instance inst
, double new_max_delay_ratio
)
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
);
2360 /* ================================================== */
2363 NCR_ModifyMaxdelaydevratio(NCR_Instance inst
, double new_max_delay_dev_ratio
)
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
);
2370 /* ================================================== */
2373 NCR_ModifyMinstratum(NCR_Instance inst
, int new_min_stratum
)
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
);
2380 /* ================================================== */
2383 NCR_ModifyPolltarget(NCR_Instance inst
, int new_poll_target
)
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
);
2390 /* ================================================== */
2393 NCR_InitiateSampleBurst(NCR_Instance inst
, int n_good_samples
, int n_total_samples
)
2396 if (inst
->mode
== MODE_CLIENT
) {
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.) */
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 */
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
);
2426 /* ================================================== */
2429 NCR_ReportSource(NCR_Instance inst
, RPT_SourceReport
*report
, struct timespec
*now
)
2431 report
->poll
= get_transmit_poll(inst
);
2433 switch (inst
->mode
) {
2435 report
->mode
= RPT_NTP_CLIENT
;
2438 report
->mode
= RPT_NTP_PEER
;
2445 /* ================================================== */
2448 NCR_GetNTPReport(NCR_Instance inst
, RPT_NTPReport
*report
)
2450 *report
= inst
->report
;
2453 /* ================================================== */
2456 NCR_AddAccessRestriction(IPAddr
*ip_addr
, int subnet_bits
, int allow
, int all
)
2462 status
= ADF_AllowAll(access_auth_table
, ip_addr
, subnet_bits
);
2464 status
= ADF_Allow(access_auth_table
, ip_addr
, subnet_bits
);
2468 status
= ADF_DenyAll(access_auth_table
, ip_addr
, subnet_bits
);
2470 status
= ADF_Deny(access_auth_table
, ip_addr
, subnet_bits
);
2474 if (status
!= ADF_SUCCESS
)
2477 /* Keep server sockets open only when an address allowed */
2479 NTP_Remote_Address remote_addr
;
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
);
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
);
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
;
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
;
2507 /* ================================================== */
2510 NCR_CheckAccessRestriction(IPAddr
*ip_addr
)
2512 return ADF_IsAllowed(access_auth_table
, ip_addr
);
2515 /* ================================================== */
2518 NCR_IncrementActivityCounters(NCR_Instance inst
, int *online
, int *offline
,
2519 int *burst_online
, int *burst_offline
)
2521 switch (inst
->opmode
) {
2522 case MD_BURST_WAS_OFFLINE
:
2525 case MD_BURST_WAS_ONLINE
:
2540 /* ================================================== */
2542 NTP_Remote_Address
*
2543 NCR_GetRemoteAddress(NCR_Instance inst
)
2545 return &inst
->remote_addr
;
2548 /* ================================================== */
2551 NCR_GetLocalRefid(NCR_Instance inst
)
2553 return UTI_IPToRefid(&inst
->local_addr
.ip_addr
);
2556 /* ================================================== */
2558 int NCR_IsSyncPeer(NCR_Instance inst
)
2560 return SRC_IsSyncPeer(inst
->source
);
2563 /* ================================================== */
2566 NCR_DumpAuthData(NCR_Instance inst
)
2568 NAU_DumpData(inst
->auth
);
2571 /* ================================================== */
2574 broadcast_timeout(void *arg
)
2576 BroadcastDestination
*destination
;
2578 NTP_Local_Timestamp recv_ts
;
2581 destination
= ARR_GetElement(broadcasts
, (long)arg
);
2582 poll
= log(destination
->interval
) / log(2.0) + 0.5;
2584 UTI_ZeroNtp64(&orig_ts
);
2585 zero_local_timestamp(&recv_ts
);
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
);
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
);
2596 /* ================================================== */
2599 NCR_AddBroadcastDestination(IPAddr
*addr
, unsigned short port
, int interval
)
2601 BroadcastDestination
*destination
;
2603 destination
= (BroadcastDestination
*)ARR_GetNewElement(broadcasts
);
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
);
2613 SCH_AddTimeoutInClass(destination
->interval
, MAX_SAMPLING_SEPARATION
, SAMPLING_RANDOMNESS
,
2614 SCH_NtpBroadcastClass
, broadcast_timeout
,
2615 (void *)(long)(ARR_GetSize(broadcasts
) - 1));