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