-
Notifications
You must be signed in to change notification settings - Fork 26
/
ntpd.c
2489 lines (2278 loc) · 77.7 KB
/
ntpd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* NTP client/server, based on OpenNTPD 3.9p1
*
* Author: Adam Tkac <vonsch@gmail.com>
*
* Licensed under GPLv2, see file LICENSE in this source tree.
*
* Parts of OpenNTPD clock syncronization code is replaced by
* code which is based on ntp-4.2.6, whuch carries the following
* copyright notice:
*
***********************************************************************
* *
* Copyright (c) University of Delaware 1992-2009 *
* *
* Permission to use, copy, modify, and distribute this software and *
* its documentation for any purpose with or without fee is hereby *
* granted, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission *
* notice appear in supporting documentation, and that the name *
* University of Delaware not be used in advertising or publicity *
* pertaining to distribution of the software without specific, *
* written prior permission. The University of Delaware makes no *
* representations about the suitability this software for any *
* purpose. It is provided "as is" without express or implied *
* warranty. *
* *
***********************************************************************
*/
//usage:#define ntpd_trivial_usage
//usage: "[-dnqNw"IF_FEATURE_NTPD_SERVER("l")"] [-S PROG] [-p PEER]..."
//usage:#define ntpd_full_usage "\n\n"
//usage: "NTP client/server\n"
//usage: "\n -d Verbose"
//usage: "\n -n Do not daemonize"
//usage: "\n -q Quit after clock is set"
//usage: "\n -N Run at high priority"
//usage: "\n -w Do not set time (only query peers), implies -n"
//usage: IF_FEATURE_NTPD_SERVER(
//usage: "\n -l Run as server on port 123"
//usage: )
//usage: "\n -S PROG Run PROG after stepping time, stratum change, and every 11 mins"
//usage: "\n -p PEER Obtain time from PEER (may be repeated)"
#include "libbb.h"
#include <math.h>
#include <netinet/ip.h> /* For IPTOS_LOWDELAY definition */
#include <sys/resource.h> /* setpriority */
#include <sys/timex.h>
#ifndef IPTOS_LOWDELAY
# define IPTOS_LOWDELAY 0x10
#endif
#ifndef IP_PKTINFO
# error "Sorry, your kernel has to support IP_PKTINFO"
#endif
/* Verbosity control (max level of -dddd options accepted).
* max 6 is very talkative (and bloated). 3 is non-bloated,
* production level setting.
*/
#define MAX_VERBOSE 3
/* High-level description of the algorithm:
*
* We start running with very small poll_exp, BURSTPOLL,
* in order to quickly accumulate INITIAL_SAMPLES datapoints
* for each peer. Then, time is stepped if the offset is larger
* than STEP_THRESHOLD, otherwise it isn't; anyway, we enlarge
* poll_exp to MINPOLL and enter frequency measurement step:
* we collect new datapoints but ignore them for WATCH_THRESHOLD
* seconds. After WATCH_THRESHOLD seconds we look at accumulated
* offset and estimate frequency drift.
*
* (frequency measurement step seems to not be strictly needed,
* it is conditionally disabled with USING_INITIAL_FREQ_ESTIMATION
* define set to 0)
*
* After this, we enter "steady state": we collect a datapoint,
* we select the best peer, if this datapoint is not a new one
* (IOW: if this datapoint isn't for selected peer), sleep
* and collect another one; otherwise, use its offset to update
* frequency drift, if offset is somewhat large, reduce poll_exp,
* otherwise increase poll_exp.
*
* If offset is larger than STEP_THRESHOLD, which shouldn't normally
* happen, we assume that something "bad" happened (computer
* was hibernated, someone set totally wrong date, etc),
* then the time is stepped, all datapoints are discarded,
* and we go back to steady state.
*
* Made some changes to speed up re-syncing after our clock goes bad
* (tested with suspending my laptop):
* - if largish offset (>= STEP_THRESHOLD * 8 == 1 sec) is seen
* from a peer, schedule next query for this peer soon
* without drastically lowering poll interval for everybody.
* This makes us collect enough data for step much faster:
* e.g. at poll = 10 (1024 secs), step was done within 5 minutes
* after first reply which indicated that our clock is 14 seconds off.
* - on step, do not discard d_dispersion data of the existing datapoints,
* do not clear reachable_bits. This prevents discarding first ~8
* datapoints after the step.
*/
#define RETRY_INTERVAL 5 /* on error, retry in N secs */
#define RESPONSE_INTERVAL 15 /* wait for reply up to N secs */
#define INITIAL_SAMPLES 4 /* how many samples do we want for init */
#define BAD_DELAY_GROWTH 4 /* drop packet if its delay grew by more than this */
/* Clock discipline parameters and constants */
/* Step threshold (sec). std ntpd uses 0.128.
* Using exact power of 2 (1/8) results in smaller code */
#define STEP_THRESHOLD 0.125
#define WATCH_THRESHOLD 128 /* stepout threshold (sec). std ntpd uses 900 (11 mins (!)) */
/* NB: set WATCH_THRESHOLD to ~60 when debugging to save time) */
//UNUSED: #define PANIC_THRESHOLD 1000 /* panic threshold (sec) */
#define FREQ_TOLERANCE 0.000015 /* frequency tolerance (15 PPM) */
#define BURSTPOLL 0 /* initial poll */
#define MINPOLL 5 /* minimum poll interval. std ntpd uses 6 (6: 64 sec) */
/* If we got largish offset from a peer, cap next query interval
* for this peer by this many seconds:
*/
#define BIGOFF_INTERVAL (1 << 6)
/* If offset > discipline_jitter * POLLADJ_GATE, and poll interval is >= 2^BIGPOLL,
* then it is decreased _at once_. (If < 2^BIGPOLL, it will be decreased _eventually_).
*/
#define BIGPOLL 10 /* 2^10 sec ~= 17 min */
#define MAXPOLL 12 /* maximum poll interval (12: 1.1h, 17: 36.4h). std ntpd uses 17 */
/* Actively lower poll when we see such big offsets.
* With STEP_THRESHOLD = 0.125, it means we try to sync more aggressively
* if offset increases over ~0.04 sec */
#define POLLDOWN_OFFSET (STEP_THRESHOLD / 3)
#define MINDISP 0.01 /* minimum dispersion (sec) */
#define MAXDISP 16 /* maximum dispersion (sec) */
#define MAXSTRAT 16 /* maximum stratum (infinity metric) */
#define MAXDIST 1 /* distance threshold (sec) */
#define MIN_SELECTED 1 /* minimum intersection survivors */
#define MIN_CLUSTERED 3 /* minimum cluster survivors */
#define MAXDRIFT 0.000500 /* frequency drift we can correct (500 PPM) */
/* Poll-adjust threshold.
* When we see that offset is small enough compared to discipline jitter,
* we grow a counter: += MINPOLL. When counter goes over POLLADJ_LIMIT,
* we poll_exp++. If offset isn't small, counter -= poll_exp*2,
* and when it goes below -POLLADJ_LIMIT, we poll_exp--.
* (Bumped from 30 to 40 since otherwise I often see poll_exp going *2* steps down)
*/
#define POLLADJ_LIMIT 40
/* If offset < discipline_jitter * POLLADJ_GATE, then we decide to increase
* poll interval (we think we can't improve timekeeping
* by staying at smaller poll).
*/
#define POLLADJ_GATE 4
#define TIMECONST_HACK_GATE 2
/* Compromise Allan intercept (sec). doc uses 1500, std ntpd uses 512 */
#define ALLAN 512
/* PLL loop gain */
#define PLL 65536
/* FLL loop gain [why it depends on MAXPOLL??] */
#define FLL (MAXPOLL + 1)
/* Parameter averaging constant */
#define AVG 4
enum {
NTP_VERSION = 4,
NTP_MAXSTRATUM = 15,
NTP_DIGESTSIZE = 16,
NTP_MSGSIZE_NOAUTH = 48,
NTP_MSGSIZE = (NTP_MSGSIZE_NOAUTH + 4 + NTP_DIGESTSIZE),
/* Status Masks */
MODE_MASK = (7 << 0),
VERSION_MASK = (7 << 3),
VERSION_SHIFT = 3,
LI_MASK = (3 << 6),
/* Leap Second Codes (high order two bits of m_status) */
LI_NOWARNING = (0 << 6), /* no warning */
LI_PLUSSEC = (1 << 6), /* add a second (61 seconds) */
LI_MINUSSEC = (2 << 6), /* minus a second (59 seconds) */
LI_ALARM = (3 << 6), /* alarm condition */
/* Mode values */
MODE_RES0 = 0, /* reserved */
MODE_SYM_ACT = 1, /* symmetric active */
MODE_SYM_PAS = 2, /* symmetric passive */
MODE_CLIENT = 3, /* client */
MODE_SERVER = 4, /* server */
MODE_BROADCAST = 5, /* broadcast */
MODE_RES1 = 6, /* reserved for NTP control message */
MODE_RES2 = 7, /* reserved for private use */
};
//TODO: better base selection
#define OFFSET_1900_1970 2208988800UL /* 1970 - 1900 in seconds */
#define NUM_DATAPOINTS 8
typedef struct {
uint32_t int_partl;
uint32_t fractionl;
} l_fixedpt_t;
typedef struct {
uint16_t int_parts;
uint16_t fractions;
} s_fixedpt_t;
typedef struct {
uint8_t m_status; /* status of local clock and leap info */
uint8_t m_stratum;
uint8_t m_ppoll; /* poll value */
int8_t m_precision_exp;
s_fixedpt_t m_rootdelay;
s_fixedpt_t m_rootdisp;
uint32_t m_refid;
l_fixedpt_t m_reftime;
l_fixedpt_t m_orgtime;
l_fixedpt_t m_rectime;
l_fixedpt_t m_xmttime;
uint32_t m_keyid;
uint8_t m_digest[NTP_DIGESTSIZE];
} msg_t;
typedef struct {
double d_offset;
double d_recv_time;
double d_dispersion;
} datapoint_t;
typedef struct {
len_and_sockaddr *p_lsa;
char *p_dotted;
int p_fd;
int datapoint_idx;
uint32_t lastpkt_refid;
uint8_t lastpkt_status;
uint8_t lastpkt_stratum;
uint8_t reachable_bits;
/* when to send new query (if p_fd == -1)
* or when receive times out (if p_fd >= 0): */
double next_action_time;
double p_xmttime;
double lastpkt_recv_time;
double lastpkt_delay;
double lastpkt_rootdelay;
double lastpkt_rootdisp;
/* produced by filter algorithm: */
double filter_offset;
double filter_dispersion;
double filter_jitter;
datapoint_t filter_datapoint[NUM_DATAPOINTS];
/* last sent packet: */
msg_t p_xmt_msg;
} peer_t;
#define USING_KERNEL_PLL_LOOP 1
#define USING_INITIAL_FREQ_ESTIMATION 0
enum {
OPT_n = (1 << 0),
OPT_q = (1 << 1),
OPT_N = (1 << 2),
OPT_x = (1 << 3),
/* Insert new options above this line. */
/* Non-compat options: */
OPT_w = (1 << 4),
OPT_p = (1 << 5),
OPT_S = (1 << 6),
OPT_l = (1 << 7) * ENABLE_FEATURE_NTPD_SERVER,
/* We hijack some bits for other purposes */
OPT_qq = (1 << 31),
};
struct globals {
double cur_time;
/* total round trip delay to currently selected reference clock */
double rootdelay;
/* reference timestamp: time when the system clock was last set or corrected */
double reftime;
/* total dispersion to currently selected reference clock */
double rootdisp;
double last_script_run;
char *script_name;
llist_t *ntp_peers;
#if ENABLE_FEATURE_NTPD_SERVER
int listen_fd;
# define G_listen_fd (G.listen_fd)
#else
# define G_listen_fd (-1)
#endif
unsigned verbose;
unsigned peer_cnt;
/* refid: 32-bit code identifying the particular server or reference clock
* in stratum 0 packets this is a four-character ASCII string,
* called the kiss code, used for debugging and monitoring
* in stratum 1 packets this is a four-character ASCII string
* assigned to the reference clock by IANA. Example: "GPS "
* in stratum 2+ packets, it's IPv4 address or 4 first bytes
* of MD5 hash of IPv6
*/
uint32_t refid;
uint8_t ntp_status;
/* precision is defined as the larger of the resolution and time to
* read the clock, in log2 units. For instance, the precision of a
* mains-frequency clock incrementing at 60 Hz is 16 ms, even when the
* system clock hardware representation is to the nanosecond.
*
* Delays, jitters of various kinds are clamped down to precision.
*
* If precision_sec is too large, discipline_jitter gets clamped to it
* and if offset is smaller than discipline_jitter * POLLADJ_GATE, poll
* interval grows even though we really can benefit from staying at
* smaller one, collecting non-lagged datapoits and correcting offset.
* (Lagged datapoits exist when poll_exp is large but we still have
* systematic offset error - the time distance between datapoints
* is significant and older datapoints have smaller offsets.
* This makes our offset estimation a bit smaller than reality)
* Due to this effect, setting G_precision_sec close to
* STEP_THRESHOLD isn't such a good idea - offsets may grow
* too big and we will step. I observed it with -6.
*
* OTOH, setting precision_sec far too small would result in futile
* attempts to syncronize to an unachievable precision.
*
* -6 is 1/64 sec, -7 is 1/128 sec and so on.
* -8 is 1/256 ~= 0.003906 (worked well for me --vda)
* -9 is 1/512 ~= 0.001953 (let's try this for some time)
*/
#define G_precision_exp -9
/*
* G_precision_exp is used only for construction outgoing packets.
* It's ok to set G_precision_sec to a slightly different value
* (One which is "nicer looking" in logs).
* Exact value would be (1.0 / (1 << (- G_precision_exp))):
*/
#define G_precision_sec 0.002
uint8_t stratum;
/* Bool. After set to 1, never goes back to 0: */
smallint initial_poll_complete;
#define STATE_NSET 0 /* initial state, "nothing is set" */
//#define STATE_FSET 1 /* frequency set from file */
//#define STATE_SPIK 2 /* spike detected */
//#define STATE_FREQ 3 /* initial frequency */
#define STATE_SYNC 4 /* clock synchronized (normal operation) */
uint8_t discipline_state; // doc calls it c.state
uint8_t poll_exp; // s.poll
int polladj_count; // c.count
long kernel_freq_drift;
peer_t *last_update_peer;
double last_update_offset; // c.last
double last_update_recv_time; // s.t
double discipline_jitter; // c.jitter
/* Since we only compare it with ints, can simplify code
* by not making this variable floating point:
*/
unsigned offset_to_jitter_ratio;
//double cluster_offset; // s.offset
//double cluster_jitter; // s.jitter
#if !USING_KERNEL_PLL_LOOP
double discipline_freq_drift; // c.freq
/* Maybe conditionally calculate wander? it's used only for logging */
double discipline_wander; // c.wander
#endif
};
#define G (*ptr_to_globals)
static const int const_IPTOS_LOWDELAY = IPTOS_LOWDELAY;
#define VERB1 if (MAX_VERBOSE && G.verbose)
#define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
#define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
#define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
#define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
#define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
static double LOG2D(int a)
{
if (a < 0)
return 1.0 / (1UL << -a);
return 1UL << a;
}
static ALWAYS_INLINE double SQUARE(double x)
{
return x * x;
}
static ALWAYS_INLINE double MAXD(double a, double b)
{
if (a > b)
return a;
return b;
}
static ALWAYS_INLINE double MIND(double a, double b)
{
if (a < b)
return a;
return b;
}
static NOINLINE double my_SQRT(double X)
{
union {
float f;
int32_t i;
} v;
double invsqrt;
double Xhalf = X * 0.5;
/* Fast and good approximation to 1/sqrt(X), black magic */
v.f = X;
/*v.i = 0x5f3759df - (v.i >> 1);*/
v.i = 0x5f375a86 - (v.i >> 1); /* - this constant is slightly better */
invsqrt = v.f; /* better than 0.2% accuracy */
/* Refining it using Newton's method: x1 = x0 - f(x0)/f'(x0)
* f(x) = 1/(x*x) - X (f==0 when x = 1/sqrt(X))
* f'(x) = -2/(x*x*x)
* f(x)/f'(x) = (X - 1/(x*x)) / (2/(x*x*x)) = X*x*x*x/2 - x/2
* x1 = x0 - (X*x0*x0*x0/2 - x0/2) = 1.5*x0 - X*x0*x0*x0/2 = x0*(1.5 - (X/2)*x0*x0)
*/
invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); /* ~0.05% accuracy */
/* invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt); 2nd iter: ~0.0001% accuracy */
/* With 4 iterations, more than half results will be exact,
* at 6th iterations result stabilizes with about 72% results exact.
* We are well satisfied with 0.05% accuracy.
*/
return X * invsqrt; /* X * 1/sqrt(X) ~= sqrt(X) */
}
static ALWAYS_INLINE double SQRT(double X)
{
/* If this arch doesn't use IEEE 754 floats, fall back to using libm */
if (sizeof(float) != 4)
return sqrt(X);
/* This avoids needing libm, saves about 0.5k on x86-32 */
return my_SQRT(X);
}
static double
gettime1900d(void)
{
struct timeval tv;
gettimeofday(&tv, NULL); /* never fails */
G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
return G.cur_time;
}
static void
d_to_tv(double d, struct timeval *tv)
{
tv->tv_sec = (long)d;
tv->tv_usec = (d - tv->tv_sec) * 1000000;
}
static double
lfp_to_d(l_fixedpt_t lfp)
{
double ret;
lfp.int_partl = ntohl(lfp.int_partl);
lfp.fractionl = ntohl(lfp.fractionl);
ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
return ret;
}
static double
sfp_to_d(s_fixedpt_t sfp)
{
double ret;
sfp.int_parts = ntohs(sfp.int_parts);
sfp.fractions = ntohs(sfp.fractions);
ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
return ret;
}
#if ENABLE_FEATURE_NTPD_SERVER
static l_fixedpt_t
d_to_lfp(double d)
{
l_fixedpt_t lfp;
lfp.int_partl = (uint32_t)d;
lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
lfp.int_partl = htonl(lfp.int_partl);
lfp.fractionl = htonl(lfp.fractionl);
return lfp;
}
static s_fixedpt_t
d_to_sfp(double d)
{
s_fixedpt_t sfp;
sfp.int_parts = (uint16_t)d;
sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
sfp.int_parts = htons(sfp.int_parts);
sfp.fractions = htons(sfp.fractions);
return sfp;
}
#endif
static double
dispersion(const datapoint_t *dp)
{
return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
}
static double
root_distance(peer_t *p)
{
/* The root synchronization distance is the maximum error due to
* all causes of the local clock relative to the primary server.
* It is defined as half the total delay plus total dispersion
* plus peer jitter.
*/
return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
+ p->lastpkt_rootdisp
+ p->filter_dispersion
+ FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
+ p->filter_jitter;
}
static void
set_next(peer_t *p, unsigned t)
{
p->next_action_time = G.cur_time + t;
}
/*
* Peer clock filter and its helpers
*/
static void
filter_datapoints(peer_t *p)
{
int i, idx;
double sum, wavg;
datapoint_t *fdp;
#if 0
/* Simulations have shown that use of *averaged* offset for p->filter_offset
* is in fact worse than simply using last received one: with large poll intervals
* (>= 2048) averaging code uses offset values which are outdated by hours,
* and time/frequency correction goes totally wrong when fed essentially bogus offsets.
*/
int got_newest;
double minoff, maxoff, w;
double x = x; /* for compiler */
double oldest_off = oldest_off;
double oldest_age = oldest_age;
double newest_off = newest_off;
double newest_age = newest_age;
fdp = p->filter_datapoint;
minoff = maxoff = fdp[0].d_offset;
for (i = 1; i < NUM_DATAPOINTS; i++) {
if (minoff > fdp[i].d_offset)
minoff = fdp[i].d_offset;
if (maxoff < fdp[i].d_offset)
maxoff = fdp[i].d_offset;
}
idx = p->datapoint_idx; /* most recent datapoint's index */
/* Average offset:
* Drop two outliers and take weighted average of the rest:
* most_recent/2 + older1/4 + older2/8 ... + older5/32 + older6/32
* we use older6/32, not older6/64 since sum of weights should be 1:
* 1/2 + 1/4 + 1/8 + 1/16 + 1/32 + 1/32 = 1
*/
wavg = 0;
w = 0.5;
/* n-1
* --- dispersion(i)
* filter_dispersion = \ -------------
* / (i+1)
* --- 2
* i=0
*/
got_newest = 0;
sum = 0;
for (i = 0; i < NUM_DATAPOINTS; i++) {
VERB5 {
bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
i,
fdp[idx].d_offset,
fdp[idx].d_dispersion, dispersion(&fdp[idx]),
G.cur_time - fdp[idx].d_recv_time,
(minoff == fdp[idx].d_offset || maxoff == fdp[idx].d_offset)
? " (outlier by offset)" : ""
);
}
sum += dispersion(&fdp[idx]) / (2 << i);
if (minoff == fdp[idx].d_offset) {
minoff -= 1; /* so that we don't match it ever again */
} else
if (maxoff == fdp[idx].d_offset) {
maxoff += 1;
} else {
oldest_off = fdp[idx].d_offset;
oldest_age = G.cur_time - fdp[idx].d_recv_time;
if (!got_newest) {
got_newest = 1;
newest_off = oldest_off;
newest_age = oldest_age;
}
x = oldest_off * w;
wavg += x;
w /= 2;
}
idx = (idx - 1) & (NUM_DATAPOINTS - 1);
}
p->filter_dispersion = sum;
wavg += x; /* add another older6/64 to form older6/32 */
/* Fix systematic underestimation with large poll intervals.
* Imagine that we still have a bit of uncorrected drift,
* and poll interval is big (say, 100 sec). Offsets form a progression:
* 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 - 0.7 is most recent.
* The algorithm above drops 0.0 and 0.7 as outliers,
* and then we have this estimation, ~25% off from 0.7:
* 0.1/32 + 0.2/32 + 0.3/16 + 0.4/8 + 0.5/4 + 0.6/2 = 0.503125
*/
x = oldest_age - newest_age;
if (x != 0) {
x = newest_age / x; /* in above example, 100 / (600 - 100) */
if (x < 1) { /* paranoia check */
x = (newest_off - oldest_off) * x; /* 0.5 * 100/500 = 0.1 */
wavg += x;
}
}
p->filter_offset = wavg;
#else
fdp = p->filter_datapoint;
idx = p->datapoint_idx; /* most recent datapoint's index */
/* filter_offset: simply use the most recent value */
p->filter_offset = fdp[idx].d_offset;
/* n-1
* --- dispersion(i)
* filter_dispersion = \ -------------
* / (i+1)
* --- 2
* i=0
*/
wavg = 0;
sum = 0;
for (i = 0; i < NUM_DATAPOINTS; i++) {
sum += dispersion(&fdp[idx]) / (2 << i);
wavg += fdp[idx].d_offset;
idx = (idx - 1) & (NUM_DATAPOINTS - 1);
}
wavg /= NUM_DATAPOINTS;
p->filter_dispersion = sum;
#endif
/* +----- -----+ ^ 1/2
* | n-1 |
* | --- |
* | 1 \ 2 |
* filter_jitter = | --- * / (avg-offset_j) |
* | n --- |
* | j=0 |
* +----- -----+
* where n is the number of valid datapoints in the filter (n > 1);
* if filter_jitter < precision then filter_jitter = precision
*/
sum = 0;
for (i = 0; i < NUM_DATAPOINTS; i++) {
sum += SQUARE(wavg - fdp[i].d_offset);
}
sum = SQRT(sum / NUM_DATAPOINTS);
p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
p->filter_offset,
p->filter_dispersion,
p->filter_jitter);
}
static void
reset_peer_stats(peer_t *p, double offset)
{
int i;
bool small_ofs = fabs(offset) < 16 * STEP_THRESHOLD;
/* Used to set p->filter_datapoint[i].d_dispersion = MAXDISP
* and clear reachable bits, but this proved to be too agressive:
* after step (tested with suspinding laptop for ~30 secs),
* this caused all previous data to be considered invalid,
* making us needing to collect full ~8 datapoins per peer
* after step in order to start trusting them.
* In turn, this was making poll interval decrease even after
* step was done. (Poll interval decreases already before step
* in this scenario, because we see large offsets and end up with
* no good peer to select).
*/
for (i = 0; i < NUM_DATAPOINTS; i++) {
if (small_ofs) {
p->filter_datapoint[i].d_recv_time += offset;
if (p->filter_datapoint[i].d_offset != 0) {
p->filter_datapoint[i].d_offset -= offset;
//bb_error_msg("p->filter_datapoint[%d].d_offset %f -> %f",
// i,
// p->filter_datapoint[i].d_offset + offset,
// p->filter_datapoint[i].d_offset);
}
} else {
p->filter_datapoint[i].d_recv_time = G.cur_time;
p->filter_datapoint[i].d_offset = 0;
/*p->filter_datapoint[i].d_dispersion = MAXDISP;*/
}
}
if (small_ofs) {
p->lastpkt_recv_time += offset;
} else {
/*p->reachable_bits = 0;*/
p->lastpkt_recv_time = G.cur_time;
}
filter_datapoints(p); /* recalc p->filter_xxx */
VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
}
static void
add_peers(char *s)
{
peer_t *p;
p = xzalloc(sizeof(*p));
p->p_lsa = xhost2sockaddr(s, 123);
p->p_dotted = xmalloc_sockaddr2dotted_noport(&p->p_lsa->u.sa);
p->p_fd = -1;
p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
p->next_action_time = G.cur_time; /* = set_next(p, 0); */
reset_peer_stats(p, 16 * STEP_THRESHOLD);
llist_add_to(&G.ntp_peers, p);
G.peer_cnt++;
}
static int
do_sendto(int fd,
const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
msg_t *msg, ssize_t len)
{
ssize_t ret;
errno = 0;
if (!from) {
ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
} else {
ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
}
if (ret != len) {
bb_perror_msg("send failed");
return -1;
}
return 0;
}
static void
send_query_to_peer(peer_t *p)
{
/* Why do we need to bind()?
* See what happens when we don't bind:
*
* socket(PF_INET, SOCK_DGRAM, IPPROTO_IP) = 3
* setsockopt(3, SOL_IP, IP_TOS, [16], 4) = 0
* gettimeofday({1259071266, 327885}, NULL) = 0
* sendto(3, "xxx", 48, MSG_DONTWAIT, {sa_family=AF_INET, sin_port=htons(123), sin_addr=inet_addr("10.34.32.125")}, 16) = 48
* ^^^ we sent it from some source port picked by kernel.
* time(NULL) = 1259071266
* write(2, "ntpd: entering poll 15 secs\n", 28) = 28
* poll([{fd=3, events=POLLIN}], 1, 15000) = 1 ([{fd=3, revents=POLLIN}])
* recv(3, "yyy", 68, MSG_DONTWAIT) = 48
* ^^^ this recv will receive packets to any local port!
*
* Uncomment this and use strace to see it in action:
*/
#define PROBE_LOCAL_ADDR /* { len_and_sockaddr lsa; lsa.len = LSA_SIZEOF_SA; getsockname(p->query.fd, &lsa.u.sa, &lsa.len); } */
if (p->p_fd == -1) {
int fd, family;
len_and_sockaddr *local_lsa;
family = p->p_lsa->u.sa.sa_family;
p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
/* local_lsa has "null" address and port 0 now.
* bind() ensures we have a *particular port* selected by kernel
* and remembered in p->p_fd, thus later recv(p->p_fd)
* receives only packets sent to this port.
*/
PROBE_LOCAL_ADDR
xbind(fd, &local_lsa->u.sa, local_lsa->len);
PROBE_LOCAL_ADDR
#if ENABLE_FEATURE_IPV6
if (family == AF_INET)
#endif
setsockopt(fd, IPPROTO_IP, IP_TOS, &const_IPTOS_LOWDELAY, sizeof(const_IPTOS_LOWDELAY));
free(local_lsa);
}
/* Emit message _before_ attempted send. Think of a very short
* roundtrip networks: we need to go back to recv loop ASAP,
* to reduce delay. Printing messages after send works against that.
*/
VERB1 bb_error_msg("sending query to %s", p->p_dotted);
/*
* Send out a random 64-bit number as our transmit time. The NTP
* server will copy said number into the originate field on the
* response that it sends us. This is totally legal per the SNTP spec.
*
* The impact of this is two fold: we no longer send out the current
* system time for the world to see (which may aid an attacker), and
* it gives us a (not very secure) way of knowing that we're not
* getting spoofed by an attacker that can't capture our traffic
* but can spoof packets from the NTP server we're communicating with.
*
* Save the real transmit timestamp locally.
*/
p->p_xmt_msg.m_xmttime.int_partl = random();
p->p_xmt_msg.m_xmttime.fractionl = random();
p->p_xmttime = gettime1900d();
/* Were doing it only if sendto worked, but
* loss of sync detection needs reachable_bits updated
* even if sending fails *locally*:
* "network is unreachable" because cable was pulled?
* We still need to declare "unsync" if this condition persists.
*/
p->reachable_bits <<= 1;
if (do_sendto(p->p_fd, /*from:*/ NULL, /*to:*/ &p->p_lsa->u.sa, /*addrlen:*/ p->p_lsa->len,
&p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
) {
close(p->p_fd);
p->p_fd = -1;
/*
* We know that we sent nothing.
* We can retry *soon* without fearing
* that we are flooding the peer.
*/
set_next(p, RETRY_INTERVAL);
return;
}
set_next(p, RESPONSE_INTERVAL);
}
/* Note that there is no provision to prevent several run_scripts
* to be started in quick succession. In fact, it happens rather often
* if initial syncronization results in a step.
* You will see "step" and then "stratum" script runs, sometimes
* as close as only 0.002 seconds apart.
* Script should be ready to deal with this.
*/
static void run_script(const char *action, double offset)
{
char *argv[3];
char *env1, *env2, *env3, *env4;
G.last_script_run = G.cur_time;
if (!G.script_name)
return;
argv[0] = (char*) G.script_name;
argv[1] = (char*) action;
argv[2] = NULL;
VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
env1 = xasprintf("%s=%u", "stratum", G.stratum);
putenv(env1);
env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
putenv(env2);
env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
putenv(env3);
env4 = xasprintf("%s=%f", "offset", offset);
putenv(env4);
/* Other items of potential interest: selected peer,
* rootdelay, reftime, rootdisp, refid, ntp_status,
* last_update_offset, last_update_recv_time, discipline_jitter,
* how many peers have reachable_bits = 0?
*/
/* Don't want to wait: it may run hwclock --systohc, and that
* may take some time (seconds): */
/*spawn_and_wait(argv);*/
spawn(argv);
unsetenv("stratum");
unsetenv("freq_drift_ppm");
unsetenv("poll_interval");
unsetenv("offset");
free(env1);
free(env2);
free(env3);
free(env4);
}
static NOINLINE void
step_time(double offset)
{
llist_t *item;
double dtime;
struct timeval tvc, tvn;
char buf[sizeof("yyyy-mm-dd hh:mm:ss") + /*paranoia:*/ 4];
time_t tval;
gettimeofday(&tvc, NULL); /* never fails */
dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
d_to_tv(dtime, &tvn);
if (settimeofday(&tvn, NULL) == -1)
bb_perror_msg_and_die("settimeofday");
VERB2 {
tval = tvc.tv_sec;
strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
}
tval = tvn.tv_sec;
strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
bb_error_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
/* Correct various fields which contain time-relative values: */
/* Globals: */
G.cur_time += offset;
G.last_update_recv_time += offset;
G.last_script_run += offset;
/* p->lastpkt_recv_time, p->next_action_time and such: */
for (item = G.ntp_peers; item != NULL; item = item->link) {
peer_t *pp = (peer_t *) item->data;
reset_peer_stats(pp, offset);
//bb_error_msg("offset:%+f pp->next_action_time:%f -> %f",
// offset, pp->next_action_time, pp->next_action_time + offset);
pp->next_action_time += offset;
if (pp->p_fd >= 0) {
/* We wait for reply from this peer too.
* But due to step we are doing, reply's data is no longer
* useful (in fact, it'll be bogus). Stop waiting for it.
*/
close(pp->p_fd);
pp->p_fd = -1;
set_next(pp, RETRY_INTERVAL);
}
}
}
/*
* Selection and clustering, and their helpers
*/
typedef struct {
peer_t *p;
int type;
double edge;
double opt_rd; /* optimization */
} point_t;
static int
compare_point_edge(const void *aa, const void *bb)
{
const point_t *a = aa;
const point_t *b = bb;
if (a->edge < b->edge) {
return -1;
}
return (a->edge > b->edge);
}
typedef struct {
peer_t *p;
double metric;
} survivor_t;
static int
compare_survivor_metric(const void *aa, const void *bb)
{
const survivor_t *a = aa;
const survivor_t *b = bb;
if (a->metric < b->metric) {
return -1;
}
return (a->metric > b->metric);
}
static int
fit(peer_t *p, double rd)