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#include "libbb.h"
109#include <math.h>
110#include <netinet/ip.h>
111#include <sys/timex.h>
112#ifndef IPTOS_DSCP_AF21
113# define IPTOS_DSCP_AF21 0x48
114#endif
115
116
117
118
119
120
121#define MAX_VERBOSE 3
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#define INITIAL_SAMPLES 4
166#define MIN_FREQHOLD 10
167#define BAD_DELAY_GROWTH 4
168
169#define RETRY_INTERVAL 32
170#define NOREPLY_INTERVAL 512
171#define RESPONSE_INTERVAL 16
172#define HOSTNAME_INTERVAL 4
173#define DNS_ERRORS_CAP 0x3f
174
175
176
177#define STEP_THRESHOLD 1
178
179
180
181#define SLEW_THRESHOLD 0.5
182
183
184
185
186
187
188
189
190
191
192
193
194#define BIGOFF STEP_THRESHOLD
195#define BIGOFF_INTERVAL (1 << 7)
196
197#define FREQ_TOLERANCE 0.000015
198#define BURSTPOLL 0
199#define MINPOLL 5
200
201
202
203
204#define BIGPOLL 9
205#define MAXPOLL 12
206
207
208
209
210
211
212#define MINDISP 0.01
213#define MAXDISP 16
214#define MAXSTRAT 16
215#define MAXDIST 1
216#define MIN_SELECTED 1
217#define MIN_CLUSTERED 3
218
219#define MAXDRIFT 0.000500
220
221
222
223
224
225
226
227
228#define POLLADJ_LIMIT 40
229
230
231
232
233#define POLLADJ_GATE 4
234#define TIMECONST_HACK_GATE 2
235
236#define ALLAN 512
237
238#define PLL 65536
239
240#define FLL (MAXPOLL + 1)
241
242#define AVG 4
243
244#define MAX_KEY_NUMBER 65535
245#define KEYID_SIZE sizeof(uint32_t)
246
247enum {
248 NTP_VERSION = 4,
249 NTP_MAXSTRATUM = 15,
250
251 NTP_MD5_DIGESTSIZE = 16,
252 NTP_MSGSIZE_NOAUTH = 48,
253 NTP_MSGSIZE_MD5_AUTH = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_MD5_DIGESTSIZE,
254 NTP_SHA1_DIGESTSIZE = 20,
255 NTP_MSGSIZE_SHA1_AUTH = NTP_MSGSIZE_NOAUTH + KEYID_SIZE + NTP_SHA1_DIGESTSIZE,
256
257
258 MODE_MASK = (7 << 0),
259 VERSION_MASK = (7 << 3),
260 VERSION_SHIFT = 3,
261 LI_MASK = (3 << 6),
262
263
264 LI_NOWARNING = (0 << 6),
265 LI_PLUSSEC = (1 << 6),
266 LI_MINUSSEC = (2 << 6),
267 LI_ALARM = (3 << 6),
268
269
270 MODE_RES0 = 0,
271 MODE_SYM_ACT = 1,
272 MODE_SYM_PAS = 2,
273 MODE_CLIENT = 3,
274 MODE_SERVER = 4,
275 MODE_BROADCAST = 5,
276 MODE_RES1 = 6,
277 MODE_RES2 = 7,
278};
279
280
281#define OFFSET_1900_1970 2208988800UL
282
283#define NUM_DATAPOINTS 8
284
285typedef struct {
286 uint32_t int_partl;
287 uint32_t fractionl;
288} l_fixedpt_t;
289
290typedef struct {
291 uint16_t int_parts;
292 uint16_t fractions;
293} s_fixedpt_t;
294
295typedef struct {
296 uint8_t m_status;
297 uint8_t m_stratum;
298 uint8_t m_ppoll;
299 int8_t m_precision_exp;
300 s_fixedpt_t m_rootdelay;
301 s_fixedpt_t m_rootdisp;
302 uint32_t m_refid;
303 l_fixedpt_t m_reftime;
304 l_fixedpt_t m_orgtime;
305 l_fixedpt_t m_rectime;
306 l_fixedpt_t m_xmttime;
307 uint32_t m_keyid;
308 uint8_t m_digest[ENABLE_FEATURE_NTP_AUTH ? NTP_SHA1_DIGESTSIZE : NTP_MD5_DIGESTSIZE];
309} msg_t;
310
311typedef struct {
312 double d_offset;
313 double d_recv_time;
314 double d_dispersion;
315} datapoint_t;
316
317#if ENABLE_FEATURE_NTP_AUTH
318enum {
319 HASH_MD5,
320 HASH_SHA1,
321};
322typedef struct {
323 unsigned id;
324 smalluint type;
325 smalluint msg_size;
326 smalluint key_length;
327 char key[0];
328} key_entry_t;
329#endif
330
331typedef struct {
332 len_and_sockaddr *p_lsa;
333 char *p_dotted;
334#if ENABLE_FEATURE_NTP_AUTH
335 key_entry_t *key_entry;
336#endif
337 int p_fd;
338 int datapoint_idx;
339#if ENABLE_FEATURE_NTPD_SERVER
340 uint32_t p_refid;
341#endif
342 uint32_t lastpkt_refid;
343 uint8_t lastpkt_status;
344 uint8_t lastpkt_stratum;
345 uint8_t reachable_bits;
346 uint8_t dns_errors;
347
348
349 double next_action_time;
350 double p_xmttime;
351 double p_raw_delay;
352
353
354 double lastpkt_recv_time;
355 double lastpkt_delay;
356 double lastpkt_rootdelay;
357 double lastpkt_rootdisp;
358
359 double filter_offset;
360 double filter_dispersion;
361 double filter_jitter;
362 datapoint_t filter_datapoint[NUM_DATAPOINTS];
363
364 msg_t p_xmt_msg;
365 char p_hostname[1];
366} peer_t;
367
368
369#define USING_KERNEL_PLL_LOOP 1
370#define USING_INITIAL_FREQ_ESTIMATION 0
371
372enum {
373 OPT_n = (1 << 0),
374 OPT_q = (1 << 1),
375 OPT_N = (1 << 2),
376 OPT_x = (1 << 3),
377 OPT_k = (1 << 4) * ENABLE_FEATURE_NTP_AUTH,
378
379
380 OPT_w = (1 << (4+ENABLE_FEATURE_NTP_AUTH)),
381 OPT_p = (1 << (5+ENABLE_FEATURE_NTP_AUTH)),
382 OPT_S = (1 << (6+ENABLE_FEATURE_NTP_AUTH)),
383 OPT_l = (1 << (7+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
384 OPT_I = (1 << (8+ENABLE_FEATURE_NTP_AUTH)) * ENABLE_FEATURE_NTPD_SERVER,
385
386 OPT_qq = (1 << 31),
387};
388
389struct globals {
390 double cur_time;
391
392 double rootdelay;
393
394 double reftime;
395
396 double rootdisp;
397
398 double last_script_run;
399 char *script_name;
400 llist_t *ntp_peers;
401#if ENABLE_FEATURE_NTPD_SERVER
402 int listen_fd;
403 char *if_name;
404# define G_listen_fd (G.listen_fd)
405#else
406# define G_listen_fd (-1)
407#endif
408 unsigned verbose;
409 unsigned peer_cnt;
410
411
412
413
414
415
416
417
418#if ENABLE_FEATURE_NTPD_SERVER
419 uint32_t refid;
420#endif
421 uint8_t ntp_status;
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#define G_precision_exp -9
449
450
451
452
453
454
455#define G_precision_sec 0.002
456 uint8_t stratum;
457
458#define STATE_NSET 0
459
460
461
462#define STATE_SYNC 4
463 uint8_t discipline_state;
464 uint8_t poll_exp;
465 int polladj_count;
466 int FREQHOLD_cnt;
467 long kernel_freq_drift;
468 peer_t *last_update_peer;
469 double last_update_offset;
470 double last_update_recv_time;
471 double discipline_jitter;
472
473
474
475 unsigned offset_to_jitter_ratio;
476
477
478#if !USING_KERNEL_PLL_LOOP
479 double discipline_freq_drift;
480
481 double discipline_wander;
482#endif
483};
484#define G (*ptr_to_globals)
485
486
487#define VERB1 if (MAX_VERBOSE && G.verbose)
488#define VERB2 if (MAX_VERBOSE >= 2 && G.verbose >= 2)
489#define VERB3 if (MAX_VERBOSE >= 3 && G.verbose >= 3)
490#define VERB4 if (MAX_VERBOSE >= 4 && G.verbose >= 4)
491#define VERB5 if (MAX_VERBOSE >= 5 && G.verbose >= 5)
492#define VERB6 if (MAX_VERBOSE >= 6 && G.verbose >= 6)
493
494
495static double LOG2D(int a)
496{
497 if (a < 0)
498 return 1.0 / (1UL << -a);
499 return 1UL << a;
500}
501static ALWAYS_INLINE double SQUARE(double x)
502{
503 return x * x;
504}
505static ALWAYS_INLINE double MAXD(double a, double b)
506{
507 if (a > b)
508 return a;
509 return b;
510}
511#if !USING_KERNEL_PLL_LOOP
512static ALWAYS_INLINE double MIND(double a, double b)
513{
514 if (a < b)
515 return a;
516 return b;
517}
518#endif
519static NOINLINE double my_SQRT(double X)
520{
521 union {
522 float f;
523 int32_t i;
524 } v;
525 double invsqrt;
526 double Xhalf = X * 0.5;
527
528
529 v.f = X;
530
531 v.i = 0x5f375a86 - (v.i >> 1);
532 invsqrt = v.f;
533
534
535
536
537
538
539
540 invsqrt = invsqrt * (1.5 - Xhalf * invsqrt * invsqrt);
541
542
543
544
545
546
547 return X * invsqrt;
548}
549static ALWAYS_INLINE double SQRT(double X)
550{
551
552 if (sizeof(float) != 4)
553 return sqrt(X);
554
555
556 return my_SQRT(X);
557}
558
559static double
560gettime1900d(void)
561{
562 struct timeval tv;
563 gettimeofday(&tv, NULL);
564 G.cur_time = tv.tv_sec + (1.0e-6 * tv.tv_usec) + OFFSET_1900_1970;
565 return G.cur_time;
566}
567
568static void
569d_to_tv(double d, struct timeval *tv)
570{
571 tv->tv_sec = (long)d;
572 tv->tv_usec = (d - tv->tv_sec) * 1000000;
573}
574
575static double
576lfp_to_d(l_fixedpt_t lfp)
577{
578 double ret;
579 lfp.int_partl = ntohl(lfp.int_partl);
580 lfp.fractionl = ntohl(lfp.fractionl);
581 ret = (double)lfp.int_partl + ((double)lfp.fractionl / UINT_MAX);
582 return ret;
583}
584static double
585sfp_to_d(s_fixedpt_t sfp)
586{
587 double ret;
588 sfp.int_parts = ntohs(sfp.int_parts);
589 sfp.fractions = ntohs(sfp.fractions);
590 ret = (double)sfp.int_parts + ((double)sfp.fractions / USHRT_MAX);
591 return ret;
592}
593#if ENABLE_FEATURE_NTPD_SERVER
594static l_fixedpt_t
595d_to_lfp(double d)
596{
597 l_fixedpt_t lfp;
598 lfp.int_partl = (uint32_t)d;
599 lfp.fractionl = (uint32_t)((d - lfp.int_partl) * UINT_MAX);
600 lfp.int_partl = htonl(lfp.int_partl);
601 lfp.fractionl = htonl(lfp.fractionl);
602 return lfp;
603}
604static s_fixedpt_t
605d_to_sfp(double d)
606{
607 s_fixedpt_t sfp;
608 sfp.int_parts = (uint16_t)d;
609 sfp.fractions = (uint16_t)((d - sfp.int_parts) * USHRT_MAX);
610 sfp.int_parts = htons(sfp.int_parts);
611 sfp.fractions = htons(sfp.fractions);
612 return sfp;
613}
614#endif
615
616static double
617dispersion(const datapoint_t *dp)
618{
619 return dp->d_dispersion + FREQ_TOLERANCE * (G.cur_time - dp->d_recv_time);
620}
621
622static double
623root_distance(peer_t *p)
624{
625
626
627
628
629
630 return MAXD(MINDISP, p->lastpkt_rootdelay + p->lastpkt_delay) / 2
631 + p->lastpkt_rootdisp
632 + p->filter_dispersion
633 + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time)
634 + p->filter_jitter;
635}
636
637static void
638set_next(peer_t *p, unsigned t)
639{
640 p->next_action_time = G.cur_time + t;
641}
642
643
644
645
646static void
647filter_datapoints(peer_t *p)
648{
649 int i, idx;
650 double sum, wavg;
651 datapoint_t *fdp;
652
653#if 0
654
655
656
657
658
659 int got_newest;
660 double minoff, maxoff, w;
661 double x = x;
662 double oldest_off = oldest_off;
663 double oldest_age = oldest_age;
664 double newest_off = newest_off;
665 double newest_age = newest_age;
666
667 fdp = p->filter_datapoint;
668
669 minoff = maxoff = fdp[0].d_offset;
670 for (i = 1; i < NUM_DATAPOINTS; i++) {
671 if (minoff > fdp[i].d_offset)
672 minoff = fdp[i].d_offset;
673 if (maxoff < fdp[i].d_offset)
674 maxoff = fdp[i].d_offset;
675 }
676
677 idx = p->datapoint_idx;
678
679
680
681
682
683
684 wavg = 0;
685 w = 0.5;
686
687
688
689
690
691
692
693 got_newest = 0;
694 sum = 0;
695 for (i = 0; i < NUM_DATAPOINTS; i++) {
696 VERB5 {
697 bb_error_msg("datapoint[%d]: off:%f disp:%f(%f) age:%f%s",
698 i,
699 fdp[idx].d_offset,
700 fdp[idx].d_dispersion, dispersion(&fdp[idx]),
701 G.cur_time - fdp[idx].d_recv_time,
702 (minoff == fdp[idx].d_offset || maxoff == fdp[idx].d_offset)
703 ? " (outlier by offset)" : ""
704 );
705 }
706
707 sum += dispersion(&fdp[idx]) / (2 << i);
708
709 if (minoff == fdp[idx].d_offset) {
710 minoff -= 1;
711 } else
712 if (maxoff == fdp[idx].d_offset) {
713 maxoff += 1;
714 } else {
715 oldest_off = fdp[idx].d_offset;
716 oldest_age = G.cur_time - fdp[idx].d_recv_time;
717 if (!got_newest) {
718 got_newest = 1;
719 newest_off = oldest_off;
720 newest_age = oldest_age;
721 }
722 x = oldest_off * w;
723 wavg += x;
724 w /= 2;
725 }
726
727 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
728 }
729 p->filter_dispersion = sum;
730 wavg += x;
731
732
733
734
735
736
737
738
739 x = oldest_age - newest_age;
740 if (x != 0) {
741 x = newest_age / x;
742 if (x < 1) {
743 x = (newest_off - oldest_off) * x;
744 wavg += x;
745 }
746 }
747 p->filter_offset = wavg;
748
749#else
750
751 fdp = p->filter_datapoint;
752 idx = p->datapoint_idx;
753
754
755 p->filter_offset = fdp[idx].d_offset;
756
757
758
759
760
761
762
763
764 wavg = 0;
765 sum = 0;
766 for (i = 0; i < NUM_DATAPOINTS; i++) {
767 sum += dispersion(&fdp[idx]) / (2 << i);
768 wavg += fdp[idx].d_offset;
769 idx = (idx - 1) & (NUM_DATAPOINTS - 1);
770 }
771 wavg /= NUM_DATAPOINTS;
772 p->filter_dispersion = sum;
773#endif
774
775
776
777
778
779
780
781
782
783
784
785
786 sum = 0;
787 for (i = 0; i < NUM_DATAPOINTS; i++) {
788 sum += SQUARE(wavg - fdp[i].d_offset);
789 }
790 sum = SQRT(sum / NUM_DATAPOINTS);
791 p->filter_jitter = sum > G_precision_sec ? sum : G_precision_sec;
792
793 VERB4 bb_error_msg("filter offset:%+f disp:%f jitter:%f",
794 p->filter_offset,
795 p->filter_dispersion,
796 p->filter_jitter);
797}
798
799static void
800reset_peer_stats(peer_t *p, double offset)
801{
802 int i;
803 bool small_ofs = fabs(offset) < STEP_THRESHOLD;
804
805
806
807
808
809
810
811
812
813
814
815
816
817 for (i = 0; i < NUM_DATAPOINTS; i++) {
818 if (small_ofs) {
819 p->filter_datapoint[i].d_recv_time += offset;
820 if (p->filter_datapoint[i].d_offset != 0) {
821 p->filter_datapoint[i].d_offset -= offset;
822
823
824
825
826 }
827 } else {
828 p->filter_datapoint[i].d_recv_time = G.cur_time;
829 p->filter_datapoint[i].d_offset = 0;
830
831 }
832 }
833 if (small_ofs) {
834 p->lastpkt_recv_time += offset;
835 } else {
836
837 p->lastpkt_recv_time = G.cur_time;
838 }
839 filter_datapoints(p);
840 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
841}
842
843#if ENABLE_FEATURE_NTPD_SERVER
844static uint32_t calculate_refid(len_and_sockaddr *lsa)
845{
846# if ENABLE_FEATURE_IPV6
847 if (lsa->u.sa.sa_family == AF_INET6) {
848 md5_ctx_t md5;
849 uint32_t res[MD5_OUTSIZE / 4];
850
851 md5_begin(&md5);
852 md5_hash(&md5, &lsa->u.sin6.sin6_addr, sizeof(lsa->u.sin6.sin6_addr));
853 md5_end(&md5, res);
854 return res[0];
855 }
856# endif
857 return lsa->u.sin.sin_addr.s_addr;
858}
859#endif
860
861static len_and_sockaddr*
862resolve_peer_hostname(peer_t *p)
863{
864 len_and_sockaddr *lsa = host2sockaddr(p->p_hostname, 123);
865 if (lsa) {
866 free(p->p_lsa);
867 free(p->p_dotted);
868 p->p_lsa = lsa;
869 p->p_dotted = xmalloc_sockaddr2dotted_noport(&lsa->u.sa);
870 VERB1 if (strcmp(p->p_hostname, p->p_dotted) != 0)
871 bb_error_msg("'%s' is %s", p->p_hostname, p->p_dotted);
872#if ENABLE_FEATURE_NTPD_SERVER
873 p->p_refid = calculate_refid(p->p_lsa);
874#endif
875 p->dns_errors = 0;
876 return lsa;
877 }
878 p->dns_errors = ((p->dns_errors << 1) | 1) & DNS_ERRORS_CAP;
879 return lsa;
880}
881
882#if !ENABLE_FEATURE_NTP_AUTH
883#define add_peers(s, key_entry) \
884 add_peers(s)
885#endif
886static void
887add_peers(const char *s, key_entry_t *key_entry)
888{
889 llist_t *item;
890 peer_t *p;
891
892 p = xzalloc(sizeof(*p) + strlen(s));
893 strcpy(p->p_hostname, s);
894 p->p_fd = -1;
895 p->p_xmt_msg.m_status = MODE_CLIENT | (NTP_VERSION << 3);
896 p->next_action_time = G.cur_time;
897 reset_peer_stats(p, STEP_THRESHOLD);
898
899
900
901
902
903 if (resolve_peer_hostname(p)) {
904 for (item = G.ntp_peers; item != NULL; item = item->link) {
905 peer_t *pp = (peer_t *) item->data;
906 if (pp->p_dotted && strcmp(p->p_dotted, pp->p_dotted) == 0) {
907 bb_error_msg("duplicate peer %s (%s)", s, p->p_dotted);
908 free(p->p_lsa);
909 free(p->p_dotted);
910 free(p);
911 return;
912 }
913 }
914 }
915
916 IF_FEATURE_NTP_AUTH(p->key_entry = key_entry;)
917 llist_add_to(&G.ntp_peers, p);
918 G.peer_cnt++;
919}
920
921static int
922do_sendto(int fd,
923 const struct sockaddr *from, const struct sockaddr *to, socklen_t addrlen,
924 msg_t *msg, ssize_t len)
925{
926 ssize_t ret;
927
928 errno = 0;
929 if (!from) {
930 ret = sendto(fd, msg, len, MSG_DONTWAIT, to, addrlen);
931 } else {
932 ret = send_to_from(fd, msg, len, MSG_DONTWAIT, to, from, addrlen);
933 }
934 if (ret != len) {
935 bb_simple_perror_msg("send failed");
936 return -1;
937 }
938 return 0;
939}
940
941#if ENABLE_FEATURE_NTP_AUTH
942static void
943hash(key_entry_t *key_entry, const msg_t *msg, uint8_t *output)
944{
945 union {
946 md5_ctx_t m;
947 sha1_ctx_t s;
948 } ctx;
949 unsigned hash_size = sizeof(*msg) - sizeof(msg->m_keyid) - sizeof(msg->m_digest);
950
951 switch (key_entry->type) {
952 case HASH_MD5:
953 md5_begin(&ctx.m);
954 md5_hash(&ctx.m, key_entry->key, key_entry->key_length);
955 md5_hash(&ctx.m, msg, hash_size);
956 md5_end(&ctx.m, output);
957 break;
958 default:
959 sha1_begin(&ctx.s);
960 sha1_hash(&ctx.s, key_entry->key, key_entry->key_length);
961 sha1_hash(&ctx.s, msg, hash_size);
962 sha1_end(&ctx.s, output);
963 break;
964 }
965}
966
967static void
968hash_peer(peer_t *p)
969{
970 p->p_xmt_msg.m_keyid = htonl(p->key_entry->id);
971 hash(p->key_entry, &p->p_xmt_msg, p->p_xmt_msg.m_digest);
972}
973
974static int
975hashes_differ(peer_t *p, const msg_t *msg)
976{
977 uint8_t digest[NTP_SHA1_DIGESTSIZE];
978 hash(p->key_entry, msg, digest);
979 return memcmp(digest, msg->m_digest, p->key_entry->msg_size - NTP_MSGSIZE_NOAUTH - KEYID_SIZE);
980}
981#endif
982
983static void
984send_query_to_peer(peer_t *p)
985{
986 if (!p->p_lsa)
987 return;
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005#define PROBE_LOCAL_ADDR
1006
1007 if (p->p_fd == -1) {
1008 int fd, family;
1009 len_and_sockaddr *local_lsa;
1010
1011 family = p->p_lsa->u.sa.sa_family;
1012 p->p_fd = fd = xsocket_type(&local_lsa, family, SOCK_DGRAM);
1013
1014
1015
1016
1017
1018 PROBE_LOCAL_ADDR
1019 xbind(fd, &local_lsa->u.sa, local_lsa->len);
1020 PROBE_LOCAL_ADDR
1021#if ENABLE_FEATURE_IPV6
1022 if (family == AF_INET)
1023#endif
1024 setsockopt_int(fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
1025 free(local_lsa);
1026 }
1027
1028
1029
1030
1031
1032 VERB1 bb_error_msg("sending query to %s", p->p_dotted);
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047 p->p_xmt_msg.m_xmttime.int_partl = rand();
1048 p->p_xmt_msg.m_xmttime.fractionl = rand();
1049 p->p_xmttime = gettime1900d();
1050
1051
1052
1053
1054
1055
1056
1057 p->reachable_bits <<= 1;
1058
1059#if ENABLE_FEATURE_NTP_AUTH
1060 if (p->key_entry)
1061 hash_peer(p);
1062 if (do_sendto(p->p_fd, NULL, &p->p_lsa->u.sa, p->p_lsa->len,
1063 &p->p_xmt_msg, !p->key_entry ? NTP_MSGSIZE_NOAUTH : p->key_entry->msg_size) == -1
1064 )
1065#else
1066 if (do_sendto(p->p_fd, NULL, &p->p_lsa->u.sa, p->p_lsa->len,
1067 &p->p_xmt_msg, NTP_MSGSIZE_NOAUTH) == -1
1068 )
1069#endif
1070 {
1071 close(p->p_fd);
1072 p->p_fd = -1;
1073
1074
1075
1076
1077
1078 set_next(p, RETRY_INTERVAL);
1079 return;
1080 }
1081
1082 set_next(p, RESPONSE_INTERVAL);
1083}
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093static void run_script(const char *action, double offset)
1094{
1095 char *argv[3];
1096 char *env1, *env2, *env3, *env4;
1097
1098 G.last_script_run = G.cur_time;
1099
1100 if (!G.script_name)
1101 return;
1102
1103 argv[0] = (char*) G.script_name;
1104 argv[1] = (char*) action;
1105 argv[2] = NULL;
1106
1107 VERB1 bb_error_msg("executing '%s %s'", G.script_name, action);
1108
1109 env1 = xasprintf("%s=%u", "stratum", G.stratum);
1110 putenv(env1);
1111 env2 = xasprintf("%s=%ld", "freq_drift_ppm", G.kernel_freq_drift);
1112 putenv(env2);
1113 env3 = xasprintf("%s=%u", "poll_interval", 1 << G.poll_exp);
1114 putenv(env3);
1115 env4 = xasprintf("%s=%f", "offset", offset);
1116 putenv(env4);
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126 spawn(argv);
1127
1128 unsetenv("stratum");
1129 unsetenv("freq_drift_ppm");
1130 unsetenv("poll_interval");
1131 unsetenv("offset");
1132 free(env1);
1133 free(env2);
1134 free(env3);
1135 free(env4);
1136}
1137
1138static NOINLINE void
1139step_time(double offset)
1140{
1141 llist_t *item;
1142 double dtime;
1143 struct timeval tvc, tvn;
1144 char buf[sizeof("yyyy-mm-dd hh:mm:ss") + 4];
1145 time_t tval;
1146
1147 gettimeofday(&tvc, NULL);
1148 dtime = tvc.tv_sec + (1.0e-6 * tvc.tv_usec) + offset;
1149 d_to_tv(dtime, &tvn);
1150 xsettimeofday(&tvn);
1151
1152 VERB2 {
1153 tval = tvc.tv_sec;
1154 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1155 bb_error_msg("current time is %s.%06u", buf, (unsigned)tvc.tv_usec);
1156 }
1157 tval = tvn.tv_sec;
1158 strftime_YYYYMMDDHHMMSS(buf, sizeof(buf), &tval);
1159 bb_info_msg("setting time to %s.%06u (offset %+fs)", buf, (unsigned)tvn.tv_usec, offset);
1160
1161
1162
1163
1164
1165 G.cur_time += offset;
1166 G.last_update_recv_time += offset;
1167 G.last_script_run += offset;
1168
1169
1170 for (item = G.ntp_peers; item != NULL; item = item->link) {
1171 peer_t *pp = (peer_t *) item->data;
1172 reset_peer_stats(pp, offset);
1173
1174
1175 pp->next_action_time += offset;
1176 if (pp->p_fd >= 0) {
1177
1178
1179
1180
1181 close(pp->p_fd);
1182 pp->p_fd = -1;
1183 set_next(pp, RETRY_INTERVAL);
1184 }
1185 }
1186}
1187
1188static void clamp_pollexp_and_set_MAXSTRAT(void)
1189{
1190 if (G.poll_exp < MINPOLL)
1191 G.poll_exp = MINPOLL;
1192 if (G.poll_exp > BIGPOLL)
1193 G.poll_exp = BIGPOLL;
1194 G.polladj_count = 0;
1195 G.stratum = MAXSTRAT;
1196}
1197
1198
1199
1200
1201
1202typedef struct {
1203 peer_t *p;
1204 int type;
1205 double edge;
1206 double opt_rd;
1207} point_t;
1208static int
1209compare_point_edge(const void *aa, const void *bb)
1210{
1211 const point_t *a = aa;
1212 const point_t *b = bb;
1213 if (a->edge < b->edge) {
1214 return -1;
1215 }
1216 return (a->edge > b->edge);
1217}
1218typedef struct {
1219 peer_t *p;
1220 double metric;
1221} survivor_t;
1222static int
1223compare_survivor_metric(const void *aa, const void *bb)
1224{
1225 const survivor_t *a = aa;
1226 const survivor_t *b = bb;
1227 if (a->metric < b->metric) {
1228 return -1;
1229 }
1230 return (a->metric > b->metric);
1231}
1232static int
1233fit(peer_t *p, double rd)
1234{
1235 if ((p->reachable_bits & (p->reachable_bits-1)) == 0) {
1236
1237 VERB4 bb_error_msg("peer %s unfit for selection: "
1238 "unreachable", p->p_dotted);
1239 return 0;
1240 }
1241#if 0
1242 if ((p->lastpkt_status & LI_ALARM) == LI_ALARM
1243 || p->lastpkt_stratum >= MAXSTRAT
1244 ) {
1245 VERB4 bb_error_msg("peer %s unfit for selection: "
1246 "bad status/stratum", p->p_dotted);
1247 return 0;
1248 }
1249#endif
1250
1251 if (rd > MAXDIST + FREQ_TOLERANCE * (1 << G.poll_exp)) {
1252 VERB3 bb_error_msg("peer %s unfit for selection: "
1253 "root distance %f too high, jitter:%f",
1254 p->p_dotted, rd, p->filter_jitter
1255 );
1256 return 0;
1257 }
1258
1259
1260
1261
1262 return 1;
1263}
1264static peer_t*
1265select_and_cluster(void)
1266{
1267 peer_t *p;
1268 llist_t *item;
1269 int i, j;
1270 int size = 3 * G.peer_cnt;
1271
1272 point_t point[size];
1273 unsigned num_points, num_candidates;
1274 double low, high;
1275 unsigned num_falsetickers;
1276
1277 survivor_t survivor[size];
1278 unsigned num_survivors;
1279
1280
1281
1282 num_points = 0;
1283 item = G.ntp_peers;
1284 while (item != NULL) {
1285 double rd, offset;
1286
1287 p = (peer_t *) item->data;
1288 rd = root_distance(p);
1289 offset = p->filter_offset;
1290 if (!fit(p, rd)) {
1291 item = item->link;
1292 continue;
1293 }
1294
1295 VERB5 bb_error_msg("interval: [%f %f %f] %s",
1296 offset - rd,
1297 offset,
1298 offset + rd,
1299 p->p_dotted
1300 );
1301 point[num_points].p = p;
1302 point[num_points].type = -1;
1303 point[num_points].edge = offset - rd;
1304 point[num_points].opt_rd = rd;
1305 num_points++;
1306 point[num_points].p = p;
1307 point[num_points].type = 0;
1308 point[num_points].edge = offset;
1309 point[num_points].opt_rd = rd;
1310 num_points++;
1311 point[num_points].p = p;
1312 point[num_points].type = 1;
1313 point[num_points].edge = offset + rd;
1314 point[num_points].opt_rd = rd;
1315 num_points++;
1316 item = item->link;
1317 }
1318 num_candidates = num_points / 3;
1319 if (num_candidates == 0) {
1320 VERB3 bb_error_msg("no valid datapoints%s", ", no peer selected");
1321 return NULL;
1322 }
1323
1324 qsort(point, num_points, sizeof(point[0]), compare_point_edge);
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336 num_falsetickers = 0;
1337 while (1) {
1338 int c;
1339 unsigned num_midpoints = 0;
1340
1341 low = 1 << 9;
1342 high = - (1 << 9);
1343 c = 0;
1344 for (i = 0; i < num_points; i++) {
1345
1346
1347
1348
1349
1350 c -= point[i].type;
1351 if (c >= num_candidates - num_falsetickers) {
1352
1353 low = point[i].edge;
1354 break;
1355 }
1356 if (point[i].type == 0)
1357 num_midpoints++;
1358 }
1359 c = 0;
1360 for (i = num_points-1; i >= 0; i--) {
1361 c += point[i].type;
1362 if (c >= num_candidates - num_falsetickers) {
1363 high = point[i].edge;
1364 break;
1365 }
1366 if (point[i].type == 0)
1367 num_midpoints++;
1368 }
1369
1370
1371
1372
1373
1374 if (num_midpoints <= num_falsetickers && low < high)
1375 break;
1376 num_falsetickers++;
1377 if (num_falsetickers * 2 >= num_candidates) {
1378 VERB3 bb_error_msg("falsetickers:%d, candidates:%d%s",
1379 num_falsetickers, num_candidates,
1380 ", no peer selected");
1381 return NULL;
1382 }
1383 }
1384 VERB4 bb_error_msg("selected interval: [%f, %f]; candidates:%d falsetickers:%d",
1385 low, high, num_candidates, num_falsetickers);
1386
1387
1388
1389
1390
1391
1392
1393
1394 num_survivors = 0;
1395 for (i = 0; i < num_points; i++) {
1396 if (point[i].edge < low || point[i].edge > high)
1397 continue;
1398 p = point[i].p;
1399 survivor[num_survivors].p = p;
1400
1401 survivor[num_survivors].metric = MAXDIST * p->lastpkt_stratum + point[i].opt_rd;
1402 VERB5 bb_error_msg("survivor[%d] metric:%f peer:%s",
1403 num_survivors, survivor[num_survivors].metric, p->p_dotted);
1404 num_survivors++;
1405 }
1406
1407
1408
1409
1410
1411 if (num_survivors < MIN_SELECTED) {
1412 VERB3 bb_error_msg("survivors:%d%s",
1413 num_survivors,
1414 ", no peer selected");
1415 return NULL;
1416 }
1417
1418
1419
1420 qsort(survivor, num_survivors, sizeof(survivor[0]), compare_survivor_metric);
1421
1422
1423
1424
1425
1426
1427
1428 while (1) {
1429 unsigned max_idx = max_idx;
1430 double max_selection_jitter = max_selection_jitter;
1431 double min_jitter = min_jitter;
1432
1433 if (num_survivors <= MIN_CLUSTERED) {
1434 VERB4 bb_error_msg("num_survivors %d <= %d, not discarding more",
1435 num_survivors, MIN_CLUSTERED);
1436 break;
1437 }
1438
1439
1440
1441
1442
1443
1444 for (i = 0; i < num_survivors; i++) {
1445 double selection_jitter_sq;
1446
1447 p = survivor[i].p;
1448 if (i == 0 || p->filter_jitter < min_jitter)
1449 min_jitter = p->filter_jitter;
1450
1451 selection_jitter_sq = 0;
1452 for (j = 0; j < num_survivors; j++) {
1453 peer_t *q = survivor[j].p;
1454 selection_jitter_sq += SQUARE(p->filter_offset - q->filter_offset);
1455 }
1456 if (i == 0 || selection_jitter_sq > max_selection_jitter) {
1457 max_selection_jitter = selection_jitter_sq;
1458 max_idx = i;
1459 }
1460 VERB6 bb_error_msg("survivor %d selection_jitter^2:%f",
1461 i, selection_jitter_sq);
1462 }
1463 max_selection_jitter = SQRT(max_selection_jitter / num_survivors);
1464 VERB5 bb_error_msg("max_selection_jitter (at %d):%f min_jitter:%f",
1465 max_idx, max_selection_jitter, min_jitter);
1466
1467
1468
1469
1470
1471
1472 if (max_selection_jitter < min_jitter) {
1473 VERB4 bb_error_msg("max_selection_jitter:%f < min_jitter:%f, num_survivors:%d, not discarding more",
1474 max_selection_jitter, min_jitter, num_survivors);
1475 break;
1476 }
1477
1478
1479
1480
1481 VERB6 bb_error_msg("dropping survivor %d", max_idx);
1482 num_survivors--;
1483 while (max_idx < num_survivors) {
1484 survivor[max_idx] = survivor[max_idx + 1];
1485 max_idx++;
1486 }
1487 }
1488
1489 if (0) {
1490
1491
1492
1493
1494
1495
1496
1497
1498 double x, y, z, w;
1499 y = z = w = 0;
1500 for (i = 0; i < num_survivors; i++) {
1501 p = survivor[i].p;
1502 x = root_distance(p);
1503 y += 1 / x;
1504 z += p->filter_offset / x;
1505 w += SQUARE(p->filter_offset - survivor[0].p->filter_offset) / x;
1506 }
1507
1508
1509 }
1510
1511
1512
1513
1514
1515
1516 p = survivor[0].p;
1517 if (G.last_update_peer
1518 && G.last_update_peer->lastpkt_stratum <= p->lastpkt_stratum
1519 ) {
1520
1521 for (i = 1; i < num_survivors; i++) {
1522 if (G.last_update_peer == survivor[i].p) {
1523 VERB5 bb_simple_error_msg("keeping old synced peer");
1524 p = G.last_update_peer;
1525 goto keep_old;
1526 }
1527 }
1528 }
1529 G.last_update_peer = p;
1530 keep_old:
1531 VERB4 bb_error_msg("selected peer %s filter_offset:%+f age:%f",
1532 p->p_dotted,
1533 p->filter_offset,
1534 G.cur_time - p->lastpkt_recv_time
1535 );
1536 return p;
1537}
1538
1539
1540
1541
1542
1543static void
1544set_new_values(int disc_state, double offset, double recv_time)
1545{
1546
1547
1548
1549
1550 VERB4 bb_error_msg("disc_state=%d last update offset=%f recv_time=%f",
1551 disc_state, offset, recv_time);
1552 G.discipline_state = disc_state;
1553 G.last_update_offset = offset;
1554 G.last_update_recv_time = recv_time;
1555}
1556
1557static NOINLINE int
1558update_local_clock(peer_t *p)
1559{
1560 int rc;
1561 struct timex tmx;
1562
1563 double offset = p->filter_offset;
1564 double recv_time = p->lastpkt_recv_time;
1565 double abs_offset;
1566#if !USING_KERNEL_PLL_LOOP
1567 double freq_drift;
1568#endif
1569#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1570 double since_last_update;
1571#endif
1572 double etemp, dtemp;
1573
1574 abs_offset = fabs(offset);
1575
1576#if 0
1577
1578
1579
1580 if (abs_offset > PANIC_THRESHOLD) {
1581 bb_error_msg_and_die("offset %f far too big, exiting", offset);
1582 }
1583#endif
1584
1585
1586
1587
1588
1589 if (recv_time <= G.last_update_recv_time) {
1590 VERB3 bb_error_msg("update from %s: same or older datapoint, not using it",
1591 p->p_dotted);
1592 return 0;
1593 }
1594
1595
1596
1597
1598
1599#if !USING_KERNEL_PLL_LOOP || USING_INITIAL_FREQ_ESTIMATION
1600 since_last_update = recv_time - G.reftime;
1601#endif
1602#if !USING_KERNEL_PLL_LOOP
1603 freq_drift = 0;
1604#endif
1605#if USING_INITIAL_FREQ_ESTIMATION
1606 if (G.discipline_state == STATE_FREQ) {
1607
1608 if (since_last_update < WATCH_THRESHOLD) {
1609 VERB4 bb_error_msg("measuring drift, datapoint ignored, %f sec remains",
1610 WATCH_THRESHOLD - since_last_update);
1611 return 0;
1612 }
1613# if !USING_KERNEL_PLL_LOOP
1614 freq_drift = (offset - G.last_update_offset) / since_last_update;
1615# endif
1616 }
1617#endif
1618
1619
1620
1621
1622 if (abs_offset > STEP_THRESHOLD) {
1623#if 0
1624 double remains;
1625
1626
1627
1628
1629
1630
1631
1632 switch (G.discipline_state) {
1633 case STATE_SYNC:
1634
1635 VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1636 p->p_dotted, offset,
1637 "");
1638 G.discipline_state = STATE_SPIK;
1639 return -1;
1640
1641 case STATE_SPIK:
1642
1643
1644
1645 remains = WATCH_THRESHOLD - since_last_update;
1646 if (remains > 0) {
1647 VERB3 bb_error_msg("update from %s: offset:%+f, spike%s",
1648 p->p_dotted, offset,
1649 ", datapoint ignored");
1650 return -1;
1651 }
1652
1653 }
1654#endif
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677 VERB4 bb_error_msg("stepping time by %+f; poll_exp=MINPOLL", offset);
1678 step_time(offset);
1679 if (option_mask32 & OPT_q) {
1680
1681 exit(0);
1682 }
1683
1684 clamp_pollexp_and_set_MAXSTRAT();
1685
1686 run_script("step", offset);
1687
1688 recv_time += offset;
1689
1690#if USING_INITIAL_FREQ_ESTIMATION
1691 if (G.discipline_state == STATE_NSET) {
1692 set_new_values(STATE_FREQ, 0, recv_time);
1693 return 1;
1694 }
1695#endif
1696 abs_offset = offset = 0;
1697 set_new_values(STATE_SYNC, offset, recv_time);
1698 } else {
1699
1700
1701
1702
1703 G.offset_to_jitter_ratio = abs_offset / G.discipline_jitter;
1704
1705
1706
1707
1708 etemp = SQUARE(G.discipline_jitter);
1709 dtemp = SQUARE(offset - G.last_update_offset);
1710 G.discipline_jitter = SQRT(etemp + (dtemp - etemp) / AVG);
1711 if (G.discipline_jitter < G_precision_sec)
1712 G.discipline_jitter = G_precision_sec;
1713
1714 switch (G.discipline_state) {
1715 case STATE_NSET:
1716 if (option_mask32 & OPT_q) {
1717
1718
1719
1720 exit(0);
1721 }
1722#if USING_INITIAL_FREQ_ESTIMATION
1723
1724
1725
1726
1727 set_new_values(STATE_FREQ, offset, recv_time);
1728#else
1729 set_new_values(STATE_SYNC, offset, recv_time);
1730#endif
1731 VERB4 bb_simple_error_msg("transitioning to FREQ, datapoint ignored");
1732 return 0;
1733
1734#if 0
1735 case STATE_FSET:
1736
1737
1738
1739
1740 set_new_values(STATE_SYNC, offset, recv_time);
1741
1742 break;
1743#endif
1744
1745#if USING_INITIAL_FREQ_ESTIMATION
1746 case STATE_FREQ:
1747
1748
1749
1750
1751 set_new_values(STATE_SYNC, offset, recv_time);
1752 break;
1753#endif
1754
1755 default:
1756#if !USING_KERNEL_PLL_LOOP
1757
1758
1759
1760
1761
1762
1763
1764
1765 if ((1 << G.poll_exp) > ALLAN / 2) {
1766 etemp = FLL - G.poll_exp;
1767 if (etemp < AVG)
1768 etemp = AVG;
1769 freq_drift += (offset - G.last_update_offset) / (MAXD(since_last_update, ALLAN) * etemp);
1770 }
1771
1772
1773
1774
1775
1776 etemp = MIND(since_last_update, (1 << G.poll_exp));
1777 dtemp = (4 * PLL) << G.poll_exp;
1778 freq_drift += offset * etemp / SQUARE(dtemp);
1779#endif
1780 set_new_values(STATE_SYNC, offset, recv_time);
1781 break;
1782 }
1783 if (G.stratum != p->lastpkt_stratum + 1) {
1784 G.stratum = p->lastpkt_stratum + 1;
1785 run_script("stratum", offset);
1786 }
1787 }
1788
1789 G.reftime = G.cur_time;
1790 G.ntp_status = p->lastpkt_status;
1791#if ENABLE_FEATURE_NTPD_SERVER
1792
1793 G.refid = p->p_refid;
1794#endif
1795 G.rootdelay = p->lastpkt_rootdelay + p->lastpkt_delay;
1796 dtemp = p->filter_jitter;
1797 dtemp += MAXD(p->filter_dispersion + FREQ_TOLERANCE * (G.cur_time - p->lastpkt_recv_time) + abs_offset, MINDISP);
1798 G.rootdisp = p->lastpkt_rootdisp + dtemp;
1799 VERB4 bb_error_msg("updating leap/refid/reftime/rootdisp from peer %s", p->p_dotted);
1800
1801
1802
1803
1804
1805
1806#if !USING_KERNEL_PLL_LOOP
1807
1808
1809
1810
1811
1812
1813 dtemp = G.discipline_freq_drift + freq_drift;
1814 G.discipline_freq_drift = MAXD(MIND(MAXDRIFT, dtemp), -MAXDRIFT);
1815 etemp = SQUARE(G.discipline_wander);
1816 dtemp = SQUARE(dtemp);
1817 G.discipline_wander = SQRT(etemp + (dtemp - etemp) / AVG);
1818
1819 VERB4 bb_error_msg("discipline freq_drift=%.9f(int:%ld corr:%e) wander=%f",
1820 G.discipline_freq_drift,
1821 (long)(G.discipline_freq_drift * 65536e6),
1822 freq_drift,
1823 G.discipline_wander);
1824#endif
1825 VERB4 {
1826 memset(&tmx, 0, sizeof(tmx));
1827 if (adjtimex(&tmx) < 0)
1828 bb_simple_perror_msg_and_die("adjtimex");
1829 bb_error_msg("p adjtimex freq:%ld offset:%+ld status:0x%x tc:%ld",
1830 tmx.freq, tmx.offset, tmx.status, tmx.constant);
1831 }
1832
1833 memset(&tmx, 0, sizeof(tmx));
1834#if 0
1835
1836
1837
1838
1839 tmx.modes = ADJ_FREQUENCY | ADJ_OFFSET;
1840
1841 tmx.freq = G.discipline_freq_drift * 65536e6;
1842#endif
1843 tmx.modes = ADJ_OFFSET | ADJ_STATUS | ADJ_TIMECONST;
1844
1845 tmx.offset = (long)(offset * 1000000);
1846 if (SLEW_THRESHOLD < STEP_THRESHOLD) {
1847 if (tmx.offset > (long)(SLEW_THRESHOLD * 1000000)) {
1848 tmx.offset = (long)(SLEW_THRESHOLD * 1000000);
1849 }
1850 if (tmx.offset < -(long)(SLEW_THRESHOLD * 1000000)) {
1851 tmx.offset = -(long)(SLEW_THRESHOLD * 1000000);
1852 }
1853 }
1854
1855 tmx.status = STA_PLL;
1856 if (G.FREQHOLD_cnt != 0) {
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869 if (G.FREQHOLD_cnt < 0) {
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909 unsigned off_032 = abs((int)(tmx.offset >> 15));
1910 G.FREQHOLD_cnt = 1 + MIN_FREQHOLD + off_032;
1911 }
1912 G.FREQHOLD_cnt--;
1913 tmx.status |= STA_FREQHOLD;
1914 }
1915 if (G.ntp_status & LI_PLUSSEC)
1916 tmx.status |= STA_INS;
1917 if (G.ntp_status & LI_MINUSSEC)
1918 tmx.status |= STA_DEL;
1919
1920 tmx.constant = (int)G.poll_exp - 4;
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931 if (G.offset_to_jitter_ratio >= TIMECONST_HACK_GATE)
1932 tmx.constant--;
1933 if (tmx.constant < 0)
1934 tmx.constant = 0;
1935
1936
1937
1938 rc = adjtimex(&tmx);
1939 if (rc < 0)
1940 bb_simple_perror_msg_and_die("adjtimex");
1941
1942
1943
1944 VERB4 bb_error_msg("adjtimex:%d freq:%ld offset:%+ld status:0x%x",
1945 rc, tmx.freq, tmx.offset, tmx.status);
1946 G.kernel_freq_drift = tmx.freq / 65536;
1947 VERB2 bb_error_msg("update from:%s offset:%+f delay:%f jitter:%f clock drift:%+.3fppm tc:%d",
1948 p->p_dotted,
1949 offset,
1950 p->p_raw_delay,
1951 G.discipline_jitter,
1952 (double)tmx.freq / 65536,
1953 (int)tmx.constant
1954 );
1955
1956 return 1;
1957}
1958
1959
1960
1961
1962
1963
1964static unsigned
1965poll_interval(int upper_bound)
1966{
1967 unsigned interval, r, mask;
1968 interval = 1 << G.poll_exp;
1969 if (interval > upper_bound)
1970 interval = upper_bound;
1971 mask = ((interval-1) >> 4) | 1;
1972 r = rand();
1973 interval += r & mask;
1974 VERB4 bb_error_msg("chose poll interval:%u (poll_exp:%d)", interval, G.poll_exp);
1975 return interval;
1976}
1977static void
1978adjust_poll(int count)
1979{
1980 G.polladj_count += count;
1981 if (G.polladj_count > POLLADJ_LIMIT) {
1982 G.polladj_count = 0;
1983 if (G.poll_exp < MAXPOLL) {
1984 G.poll_exp++;
1985 VERB4 bb_error_msg("polladj: discipline_jitter:%f ++poll_exp=%d",
1986 G.discipline_jitter, G.poll_exp);
1987 }
1988 } else if (G.polladj_count < -POLLADJ_LIMIT || (count < 0 && G.poll_exp > BIGPOLL)) {
1989 G.polladj_count = 0;
1990 if (G.poll_exp > MINPOLL) {
1991 llist_t *item;
1992
1993 G.poll_exp--;
1994
1995
1996
1997
1998
1999
2000 for (item = G.ntp_peers; item != NULL; item = item->link) {
2001 peer_t *pp = (peer_t *) item->data;
2002 if (pp->p_fd < 0)
2003 pp->next_action_time -= (1 << G.poll_exp);
2004 }
2005 VERB4 bb_error_msg("polladj: discipline_jitter:%f --poll_exp=%d",
2006 G.discipline_jitter, G.poll_exp);
2007 }
2008 } else {
2009 VERB4 bb_error_msg("polladj: count:%d", G.polladj_count);
2010 }
2011}
2012static NOINLINE void
2013recv_and_process_peer_pkt(peer_t *p)
2014{
2015 int rc;
2016 ssize_t size;
2017 msg_t msg;
2018 double T1, T2, T3, T4;
2019 double offset;
2020 double prev_delay, delay;
2021 unsigned interval;
2022 datapoint_t *datapoint;
2023 peer_t *q;
2024
2025 offset = 0;
2026
2027
2028
2029
2030
2031
2032
2033 if (p->p_fd < 0)
2034 return;
2035
2036
2037
2038
2039
2040 recv_again:
2041 size = recv(p->p_fd, &msg, sizeof(msg), MSG_DONTWAIT);
2042 if (size < 0) {
2043 if (errno == EINTR)
2044
2045 goto recv_again;
2046 if (errno == EAGAIN)
2047
2048
2049
2050
2051 return;
2052
2053
2054
2055
2056 bb_perror_msg_and_die("recv(%s) error", p->p_dotted);
2057 }
2058
2059#if ENABLE_FEATURE_NTP_AUTH
2060 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH) {
2061 bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
2062 return;
2063 }
2064 if (p->key_entry && hashes_differ(p, &msg)) {
2065 bb_error_msg("invalid cryptographic hash received from %s", p->p_dotted);
2066 return;
2067 }
2068#else
2069 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH) {
2070 bb_error_msg("malformed packet received from %s: size %u", p->p_dotted, (int)size);
2071 return;
2072 }
2073#endif
2074
2075 if (msg.m_orgtime.int_partl != p->p_xmt_msg.m_xmttime.int_partl
2076 || msg.m_orgtime.fractionl != p->p_xmt_msg.m_xmttime.fractionl
2077 ) {
2078
2079 return;
2080 }
2081
2082
2083
2084
2085
2086 close(p->p_fd);
2087 p->p_fd = -1;
2088
2089 if ((msg.m_status & LI_ALARM) == LI_ALARM
2090 || msg.m_stratum == 0
2091 || msg.m_stratum > NTP_MAXSTRATUM
2092 ) {
2093 bb_error_msg("reply from %s: peer is unsynced", p->p_dotted);
2094
2095
2096
2097
2098
2099
2100 if (G.poll_exp < BIGPOLL)
2101 goto increase_interval;
2102 goto pick_normal_interval;
2103 }
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123 T1 = p->p_xmttime;
2124 T2 = lfp_to_d(msg.m_rectime);
2125 T3 = lfp_to_d(msg.m_xmttime);
2126 T4 = G.cur_time;
2127 delay = (T4 - T1) - (T3 - T2);
2128
2129
2130
2131
2132
2133 prev_delay = p->p_raw_delay;
2134 p->p_raw_delay = (delay < 0 ? 0.0 : delay);
2135 if (p->reachable_bits
2136 && delay > prev_delay * BAD_DELAY_GROWTH
2137 && delay > 1.0 / (8 * 1024)
2138 ) {
2139 bb_error_msg("reply from %s: delay %f is too high, ignoring", p->p_dotted, delay);
2140 goto pick_normal_interval;
2141 }
2142
2143
2144
2145
2146
2147
2148
2149 if (delay < G_precision_sec)
2150 delay = G_precision_sec;
2151 p->lastpkt_delay = delay;
2152 p->lastpkt_recv_time = T4;
2153 VERB6 bb_error_msg("%s->lastpkt_recv_time=%f", p->p_dotted, p->lastpkt_recv_time);
2154 p->lastpkt_status = msg.m_status;
2155 p->lastpkt_stratum = msg.m_stratum;
2156 p->lastpkt_rootdelay = sfp_to_d(msg.m_rootdelay);
2157 p->lastpkt_rootdisp = sfp_to_d(msg.m_rootdisp);
2158 p->lastpkt_refid = msg.m_refid;
2159
2160 p->datapoint_idx = p->reachable_bits ? (p->datapoint_idx + 1) % NUM_DATAPOINTS : 0;
2161 datapoint = &p->filter_datapoint[p->datapoint_idx];
2162 datapoint->d_recv_time = T4;
2163 datapoint->d_offset = offset = ((T2 - T1) + (T3 - T4)) / 2;
2164 datapoint->d_dispersion = LOG2D(msg.m_precision_exp) + G_precision_sec;
2165 if (!p->reachable_bits) {
2166
2167 int i;
2168 for (i = 0; i < NUM_DATAPOINTS; i++) {
2169 p->filter_datapoint[i].d_offset = offset;
2170 }
2171 }
2172
2173 p->reachable_bits |= 1;
2174 if ((MAX_VERBOSE && G.verbose) || (option_mask32 & OPT_w)) {
2175 bb_info_msg("reply from %s: offset:%+f delay:%f status:0x%02x strat:%d refid:0x%08x rootdelay:%f reach:0x%02x",
2176 p->p_dotted,
2177 offset,
2178 p->p_raw_delay,
2179 p->lastpkt_status,
2180 p->lastpkt_stratum,
2181 p->lastpkt_refid,
2182 p->lastpkt_rootdelay,
2183 p->reachable_bits
2184
2185
2186
2187 );
2188 }
2189
2190
2191 filter_datapoints(p);
2192 q = select_and_cluster();
2193 rc = 0;
2194 if (q) {
2195 if (!(option_mask32 & OPT_w)) {
2196 rc = update_local_clock(q);
2197#if 0
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209 if (fabs(q->filter_offset) >= POLLDOWN_OFFSET) {
2210 VERB4 bb_error_msg("offset:%+f > POLLDOWN_OFFSET", q->filter_offset);
2211 adjust_poll(-POLLADJ_LIMIT * 3);
2212 rc = 0;
2213 }
2214#endif
2215 }
2216 } else {
2217
2218
2219
2220 if (G.poll_exp < BIGPOLL)
2221 goto increase_interval;
2222 }
2223
2224 if (rc != 0) {
2225
2226
2227
2228
2229
2230
2231 if (rc > 0 && G.offset_to_jitter_ratio <= POLLADJ_GATE) {
2232
2233
2234 increase_interval:
2235 adjust_poll(MINPOLL);
2236 } else {
2237 VERB3 if (rc > 0)
2238 bb_error_msg("want smaller interval: offset/jitter = %u",
2239 G.offset_to_jitter_ratio);
2240 adjust_poll(-G.poll_exp * 2);
2241 }
2242 }
2243
2244
2245 pick_normal_interval:
2246 interval = poll_interval(INT_MAX);
2247 if (fabs(offset) >= BIGOFF && interval > BIGOFF_INTERVAL) {
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259 interval = BIGOFF_INTERVAL;
2260 }
2261
2262 set_next(p, interval);
2263}
2264
2265#if ENABLE_FEATURE_NTPD_SERVER
2266static NOINLINE void
2267recv_and_process_client_pkt(void )
2268{
2269 ssize_t size;
2270
2271 len_and_sockaddr *to;
2272 struct sockaddr *from;
2273 msg_t msg;
2274 uint8_t query_status;
2275 l_fixedpt_t query_xmttime;
2276
2277 to = get_sock_lsa(G_listen_fd);
2278 from = xzalloc(to->len);
2279
2280 size = recv_from_to(G_listen_fd, &msg, sizeof(msg), MSG_DONTWAIT, from, &to->u.sa, to->len);
2281
2282
2283
2284
2285
2286
2287
2288# if ENABLE_FEATURE_NTP_AUTH
2289 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH && size != NTP_MSGSIZE_SHA1_AUTH)
2290# else
2291 if (size != NTP_MSGSIZE_NOAUTH && size != NTP_MSGSIZE_MD5_AUTH)
2292# endif
2293 {
2294 char *addr;
2295 if (size < 0) {
2296 if (errno == EAGAIN)
2297 goto bail;
2298 bb_simple_perror_msg_and_die("recv");
2299 }
2300 addr = xmalloc_sockaddr2dotted_noport(from);
2301 bb_error_msg("malformed packet received from %s: size %u", addr, (int)size);
2302 free(addr);
2303 goto bail;
2304 }
2305
2306
2307 if ((msg.m_status & MODE_MASK) != MODE_CLIENT
2308 && (msg.m_status & MODE_MASK) != MODE_SYM_ACT
2309 ) {
2310 goto bail;
2311 }
2312
2313 query_status = msg.m_status;
2314 query_xmttime = msg.m_xmttime;
2315
2316
2317 memset(&msg, 0, sizeof(msg));
2318 msg.m_status = G.stratum < MAXSTRAT ? (G.ntp_status & LI_MASK) : LI_ALARM;
2319 msg.m_status |= (query_status & VERSION_MASK);
2320 msg.m_status |= ((query_status & MODE_MASK) == MODE_CLIENT) ?
2321 MODE_SERVER : MODE_SYM_PAS;
2322 msg.m_stratum = G.stratum;
2323 msg.m_ppoll = G.poll_exp;
2324 msg.m_precision_exp = G_precision_exp;
2325
2326 msg.m_rectime = d_to_lfp(G.cur_time);
2327 msg.m_xmttime = d_to_lfp(gettime1900d());
2328 if (G.peer_cnt == 0) {
2329
2330 G.reftime = G.cur_time;
2331 }
2332 msg.m_reftime = d_to_lfp(G.reftime);
2333 msg.m_orgtime = query_xmttime;
2334 msg.m_rootdelay = d_to_sfp(G.rootdelay);
2335
2336 msg.m_rootdisp = d_to_sfp(G.rootdisp);
2337
2338 msg.m_refid = G.refid;
2339
2340
2341
2342 do_sendto(G_listen_fd,
2343 &to->u.sa, from, to->len,
2344 &msg, size);
2345
2346 bail:
2347 free(to);
2348 free(from);
2349}
2350#endif
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436#if ENABLE_FEATURE_NTP_AUTH
2437static key_entry_t *
2438find_key_entry(llist_t *key_entries, unsigned id)
2439{
2440 while (key_entries) {
2441 key_entry_t *cur = (key_entry_t*) key_entries->data;
2442 if (cur->id == id)
2443 return cur;
2444 key_entries = key_entries->link;
2445 }
2446 bb_error_msg_and_die("key %u is not defined", id);
2447}
2448#endif
2449
2450
2451
2452
2453static NOINLINE void ntp_init(char **argv)
2454{
2455 unsigned opts;
2456 llist_t *peers;
2457#if ENABLE_FEATURE_NTP_AUTH
2458 llist_t *key_entries;
2459 char *key_file_path;
2460#endif
2461
2462 srand(getpid());
2463
2464
2465 G.discipline_jitter = G_precision_sec;
2466 G.stratum = MAXSTRAT;
2467 if (BURSTPOLL != 0)
2468 G.poll_exp = BURSTPOLL;
2469 G.last_script_run = G.reftime = G.last_update_recv_time = gettime1900d();
2470 G.FREQHOLD_cnt = -1;
2471
2472
2473 peers = NULL;
2474 IF_FEATURE_NTP_AUTH(key_entries = NULL;)
2475 opts = getopt32(argv, "^"
2476 "nqNx"
2477 IF_FEATURE_NTP_AUTH("k:")
2478 "wp:*S:"IF_FEATURE_NTPD_SERVER("l")
2479 IF_FEATURE_NTPD_SERVER("I:")
2480 "d"
2481 "46aAbgL"
2482 "\0"
2483 "=0"
2484 ":dd:wn"
2485 IF_FEATURE_NTPD_SERVER(":Il")
2486 IF_FEATURE_NTP_AUTH(, &key_file_path)
2487 , &peers, &G.script_name
2488 IF_FEATURE_NTPD_SERVER(, &G.if_name)
2489 , &G.verbose
2490 );
2491
2492
2493
2494
2495#if ENABLE_FEATURE_NTPD_SERVER
2496 G_listen_fd = -1;
2497 if (opts & OPT_l) {
2498 G_listen_fd = create_and_bind_dgram_or_die(NULL, 123);
2499 if (G.if_name) {
2500 if (setsockopt_bindtodevice(G_listen_fd, G.if_name))
2501 xfunc_die();
2502 }
2503 socket_want_pktinfo(G_listen_fd);
2504 setsockopt_int(G_listen_fd, IPPROTO_IP, IP_TOS, IPTOS_DSCP_AF21);
2505 }
2506#endif
2507
2508 if (opts & OPT_N)
2509 setpriority(PRIO_PROCESS, 0, -15);
2510
2511 if (!(opts & OPT_n)) {
2512 bb_daemonize_or_rexec(DAEMON_DEVNULL_STDIO, argv);
2513 logmode = LOGMODE_NONE;
2514 }
2515
2516#if ENABLE_FEATURE_NTP_AUTH
2517 if (opts & OPT_k) {
2518 char *tokens[4];
2519 parser_t *parser;
2520
2521 parser = config_open(key_file_path);
2522 while (config_read(parser, tokens, 4, 3, "# \t", PARSE_NORMAL | PARSE_MIN_DIE) == 3) {
2523 key_entry_t *key_entry;
2524 char buffer[40];
2525 smalluint hash_type;
2526 smalluint msg_size;
2527 smalluint key_length;
2528 char *key;
2529
2530 if ((tokens[1][0] | 0x20) == 'm')
2531
2532 hash_type = HASH_MD5;
2533 else
2534 if (strncasecmp(tokens[1], "sha", 3) == 0)
2535
2536 hash_type = HASH_SHA1;
2537 else
2538 bb_simple_error_msg_and_die("only MD5 and SHA1 keys supported");
2539
2540
2541
2542
2543
2544
2545
2546
2547 key_length = strnlen(tokens[2], sizeof(buffer)+1);
2548 if (key_length >= sizeof(buffer)+1) {
2549 err:
2550 bb_error_msg_and_die("malformed key at line %u", parser->lineno);
2551 }
2552 if (hash_type == HASH_MD5) {
2553 key = tokens[2];
2554 msg_size = NTP_MSGSIZE_MD5_AUTH;
2555 } else
2556 if (!(key_length & 1)) {
2557 key_length >>= 1;
2558 if (!hex2bin(buffer, tokens[2], key_length))
2559 goto err;
2560 key = buffer;
2561 msg_size = NTP_MSGSIZE_SHA1_AUTH;
2562 } else {
2563 goto err;
2564 }
2565 key_entry = xzalloc(sizeof(*key_entry) + key_length);
2566 key_entry->type = hash_type;
2567 key_entry->msg_size = msg_size;
2568 key_entry->key_length = key_length;
2569 memcpy(key_entry->key, key, key_length);
2570 key_entry->id = xatou_range(tokens[0], 1, MAX_KEY_NUMBER);
2571 llist_add_to(&key_entries, key_entry);
2572 }
2573 config_close(parser);
2574 }
2575#endif
2576 if (peers) {
2577#if ENABLE_FEATURE_NTP_AUTH
2578 while (peers) {
2579 char *peer = llist_pop(&peers);
2580 key_entry_t *key_entry = NULL;
2581 if (strncmp(peer, "keyno:", 6) == 0) {
2582 char *end;
2583 int key_id;
2584 peer += 6;
2585 end = strchr(peer, ':');
2586 if (!end) bb_show_usage();
2587 *end = '\0';
2588 key_id = xatou_range(peer, 1, MAX_KEY_NUMBER);
2589 *end = ':';
2590 key_entry = find_key_entry(key_entries, key_id);
2591 peer = end + 1;
2592 }
2593 add_peers(peer, key_entry);
2594 }
2595#else
2596 while (peers)
2597 add_peers(llist_pop(&peers), NULL);
2598#endif
2599 }
2600#if ENABLE_FEATURE_NTPD_CONF
2601 else {
2602 parser_t *parser;
2603 char *token[3 + 2*ENABLE_FEATURE_NTP_AUTH];
2604
2605 parser = config_open("/etc/ntp.conf");
2606 while (config_read(parser, token, 3 + 2*ENABLE_FEATURE_NTP_AUTH, 1, "# \t", PARSE_NORMAL)) {
2607 if (strcmp(token[0], "server") == 0 && token[1]) {
2608# if ENABLE_FEATURE_NTP_AUTH
2609 key_entry_t *key_entry = NULL;
2610 if (token[2] && token[3] && strcmp(token[2], "key") == 0) {
2611 unsigned key_id = xatou_range(token[3], 1, MAX_KEY_NUMBER);
2612 key_entry = find_key_entry(key_entries, key_id);
2613 }
2614 add_peers(token[1], key_entry);
2615# else
2616 add_peers(token[1], NULL);
2617# endif
2618 continue;
2619 }
2620 bb_error_msg("skipping %s:%u: unimplemented command '%s'",
2621 "/etc/ntp.conf", parser->lineno, token[0]
2622 );
2623 }
2624 config_close(parser);
2625 }
2626#endif
2627 if (G.peer_cnt == 0) {
2628 if (!(opts & OPT_l))
2629 bb_show_usage();
2630
2631 G.stratum = 1;
2632 }
2633
2634 if (!(opts & OPT_n))
2635 write_pidfile_std_path_and_ext("ntpd");
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646 if (opts & OPT_q) {
2647 option_mask32 |= OPT_qq;
2648 alarm(10);
2649 }
2650
2651 bb_signals(0
2652 | (1 << SIGTERM)
2653 | (1 << SIGINT)
2654 | (1 << SIGALRM)
2655 , record_signo
2656 );
2657 bb_signals(0
2658 | (1 << SIGPIPE)
2659 | (1 << SIGCHLD)
2660 , SIG_IGN
2661 );
2662
2663}
2664
2665int ntpd_main(int argc UNUSED_PARAM, char **argv) MAIN_EXTERNALLY_VISIBLE;
2666int ntpd_main(int argc UNUSED_PARAM, char **argv)
2667{
2668#undef G
2669 struct globals G;
2670 struct pollfd *pfd;
2671 peer_t **idx2peer;
2672 unsigned cnt;
2673
2674 memset(&G, 0, sizeof(G));
2675 SET_PTR_TO_GLOBALS(&G);
2676
2677 ntp_init(argv);
2678
2679
2680 cnt = G.peer_cnt + ENABLE_FEATURE_NTPD_SERVER;
2681 idx2peer = xzalloc(sizeof(idx2peer[0]) * cnt);
2682 pfd = xzalloc(sizeof(pfd[0]) * cnt);
2683
2684
2685
2686
2687
2688
2689
2690
2691 cnt = G.peer_cnt * (INITIAL_SAMPLES + 1);
2692
2693 while (!bb_got_signal) {
2694 llist_t *item;
2695 unsigned i, j;
2696 int nfds, timeout;
2697 double nextaction;
2698
2699
2700
2701 nextaction = G.last_script_run + (11*60);
2702 if (nextaction < G.cur_time + 1)
2703 nextaction = G.cur_time + 1;
2704
2705 i = 0;
2706#if ENABLE_FEATURE_NTPD_SERVER
2707 if (G_listen_fd != -1) {
2708 pfd[0].fd = G_listen_fd;
2709 pfd[0].events = POLLIN;
2710 i++;
2711 }
2712#endif
2713
2714 for (item = G.ntp_peers; item != NULL; item = item->link) {
2715 peer_t *p = (peer_t *) item->data;
2716
2717 if (p->next_action_time <= G.cur_time) {
2718 if (p->p_fd == -1) {
2719
2720 if (--cnt == 0) {
2721 VERB4 bb_simple_error_msg("disabling burst mode");
2722 G.polladj_count = 0;
2723 G.poll_exp = MINPOLL;
2724 }
2725 send_query_to_peer(p);
2726 } else {
2727
2728 close(p->p_fd);
2729 p->p_fd = -1;
2730
2731 if (G.poll_exp < BIGPOLL)
2732 adjust_poll(MINPOLL);
2733 timeout = poll_interval(NOREPLY_INTERVAL);
2734 bb_error_msg("timed out waiting for %s, reach 0x%02x, next query in %us",
2735 p->p_dotted, p->reachable_bits, timeout);
2736
2737
2738 if (p->reachable_bits == 0)
2739 resolve_peer_hostname(p);
2740
2741 set_next(p, timeout);
2742 }
2743 }
2744
2745 if (p->next_action_time < nextaction)
2746 nextaction = p->next_action_time;
2747
2748 if (p->p_fd >= 0) {
2749
2750 pfd[i].fd = p->p_fd;
2751 pfd[i].events = POLLIN;
2752 idx2peer[i] = p;
2753 i++;
2754 }
2755 }
2756
2757 timeout = nextaction - G.cur_time;
2758 if (timeout < 0)
2759 timeout = 0;
2760 timeout++;
2761
2762
2763 VERB2 {
2764 if (i > (ENABLE_FEATURE_NTPD_SERVER && G_listen_fd != -1)) {
2765
2766
2767
2768
2769
2770 nfds = poll(pfd, i, 1000);
2771 if (nfds != 0)
2772 goto did_poll;
2773 if (--timeout <= 0)
2774 goto did_poll;
2775 }
2776 bb_error_msg("poll:%us sockets:%u interval:%us", timeout, i, 1 << G.poll_exp);
2777 }
2778 nfds = poll(pfd, i, timeout * 1000);
2779 did_poll:
2780 gettime1900d();
2781 if (nfds <= 0) {
2782 double ct;
2783 int dns_error;
2784
2785 if (bb_got_signal)
2786 break;
2787
2788 if (G.cur_time - G.last_script_run > 11*60) {
2789
2790 run_script("periodic", G.last_update_offset);
2791 gettime1900d();
2792 }
2793
2794
2795
2796
2797
2798
2799 dns_error = 0;
2800 ct = G.cur_time;
2801 for (item = G.ntp_peers; item != NULL; item = item->link) {
2802 peer_t *p = (peer_t *) item->data;
2803 if (p->next_action_time <= ct && !p->p_lsa) {
2804
2805 dns_error |= (!resolve_peer_hostname(p));
2806 }
2807 }
2808 if (!dns_error)
2809 goto check_unsync;
2810
2811 gettime1900d();
2812 for (item = G.ntp_peers; item != NULL; item = item->link) {
2813 peer_t *p = (peer_t *) item->data;
2814 if (p->next_action_time <= ct && !p->p_lsa) {
2815 set_next(p, HOSTNAME_INTERVAL * p->dns_errors);
2816 }
2817 }
2818 goto check_unsync;
2819 }
2820
2821
2822 j = 0;
2823#if ENABLE_FEATURE_NTPD_SERVER
2824 if (G.listen_fd != -1) {
2825 if (pfd[0].revents ) {
2826 nfds--;
2827 recv_and_process_client_pkt();
2828 gettime1900d();
2829 }
2830 j = 1;
2831 }
2832#endif
2833 for (; nfds != 0 && j < i; j++) {
2834 if (pfd[j].revents ) {
2835
2836
2837
2838
2839
2840 if (option_mask32 & OPT_qq) {
2841 option_mask32 &= ~OPT_qq;
2842 alarm(50);
2843 }
2844 nfds--;
2845 recv_and_process_peer_pkt(idx2peer[j]);
2846 gettime1900d();
2847 }
2848 }
2849
2850 check_unsync:
2851 if (G.ntp_peers && G.stratum != MAXSTRAT) {
2852 for (item = G.ntp_peers; item != NULL; item = item->link) {
2853 peer_t *p = (peer_t *) item->data;
2854 if (p->reachable_bits)
2855 goto have_reachable_peer;
2856 }
2857
2858 clamp_pollexp_and_set_MAXSTRAT();
2859 run_script("unsync", 0.0);
2860 have_reachable_peer: ;
2861 }
2862 }
2863
2864 remove_pidfile_std_path_and_ext("ntpd");
2865 kill_myself_with_sig(bb_got_signal);
2866}
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877#if 0
2878static double
2879direct_freq(double fp_offset)
2880{
2881#ifdef KERNEL_PLL
2882
2883
2884
2885
2886 if (pll_control && kern_enable) {
2887 memset(&ntv, 0, sizeof(ntv));
2888 ntp_adjtime(&ntv);
2889#ifdef STA_NANO
2890 clock_offset = ntv.offset / 1e9;
2891#else
2892 clock_offset = ntv.offset / 1e6;
2893#endif
2894 drift_comp = FREQTOD(ntv.freq);
2895 }
2896#endif
2897 set_freq((fp_offset - clock_offset) / (current_time - clock_epoch) + drift_comp);
2898 wander_resid = 0;
2899 return drift_comp;
2900}
2901
2902static void
2903set_freq(double freq)
2904{
2905 char tbuf[80];
2906
2907 drift_comp = freq;
2908
2909#ifdef KERNEL_PLL
2910
2911
2912
2913 if (pll_control && kern_enable) {
2914 memset(&ntv, 0, sizeof(ntv));
2915 ntv.modes = MOD_FREQUENCY;
2916 ntv.freq = DTOFREQ(drift_comp);
2917 ntp_adjtime(&ntv);
2918 snprintf(tbuf, sizeof(tbuf), "kernel %.3f PPM", drift_comp * 1e6);
2919 report_event(EVNT_FSET, NULL, tbuf);
2920 } else {
2921 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2922 report_event(EVNT_FSET, NULL, tbuf);
2923 }
2924#else
2925 snprintf(tbuf, sizeof(tbuf), "ntpd %.3f PPM", drift_comp * 1e6);
2926 report_event(EVNT_FSET, NULL, tbuf);
2927#endif
2928}
2929
2930...
2931...
2932...
2933
2934#ifdef KERNEL_PLL
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950 if (pll_control && kern_enable) {
2951
2952#define MOD_BITS (MOD_OFFSET | MOD_MAXERROR | MOD_ESTERROR | MOD_STATUS | MOD_TIMECONST)
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965 memset(&ntv, 0, sizeof(ntv));
2966 if (ext_enable) {
2967 ntv.modes = MOD_STATUS;
2968 } else {
2969#ifdef STA_NANO
2970 ntv.modes = MOD_BITS | MOD_NANO;
2971#else
2972 ntv.modes = MOD_BITS;
2973#endif
2974 if (clock_offset < 0)
2975 dtemp = -.5;
2976 else
2977 dtemp = .5;
2978#ifdef STA_NANO
2979 ntv.offset = (int32)(clock_offset * 1e9 + dtemp);
2980 ntv.constant = sys_poll;
2981#else
2982 ntv.offset = (int32)(clock_offset * 1e6 + dtemp);
2983 ntv.constant = sys_poll - 4;
2984#endif
2985 ntv.esterror = (u_int32)(clock_jitter * 1e6);
2986 ntv.maxerror = (u_int32)((sys_rootdelay / 2 + sys_rootdisp) * 1e6);
2987 ntv.status = STA_PLL;
2988
2989
2990
2991
2992 if (pps_enable) {
2993 if (!(pll_status & STA_PPSTIME))
2994 report_event(EVNT_KERN,
2995 NULL, "PPS enabled");
2996 ntv.status |= STA_PPSTIME | STA_PPSFREQ;
2997 } else {
2998 if (pll_status & STA_PPSTIME)
2999 report_event(EVNT_KERN,
3000 NULL, "PPS disabled");
3001 ntv.status &= ~(STA_PPSTIME | STA_PPSFREQ);
3002 }
3003 if (sys_leap == LEAP_ADDSECOND)
3004 ntv.status |= STA_INS;
3005 else if (sys_leap == LEAP_DELSECOND)
3006 ntv.status |= STA_DEL;
3007 }
3008
3009
3010
3011
3012
3013
3014 if (ntp_adjtime(&ntv) == TIME_ERROR) {
3015 if (!(ntv.status & STA_PPSSIGNAL))
3016 report_event(EVNT_KERN, NULL,
3017 "PPS no signal");
3018 }
3019 pll_status = ntv.status;
3020#ifdef STA_NANO
3021 clock_offset = ntv.offset / 1e9;
3022#else
3023 clock_offset = ntv.offset / 1e6;
3024#endif
3025 clock_frequency = FREQTOD(ntv.freq);
3026
3027
3028
3029
3030 if (ntv.status & STA_PPSTIME) {
3031#ifdef STA_NANO
3032 clock_jitter = ntv.jitter / 1e9;
3033#else
3034 clock_jitter = ntv.jitter / 1e6;
3035#endif
3036 }
3037
3038#if defined(STA_NANO) && NTP_API == 4
3039
3040
3041
3042 if (loop_tai != sys_tai) {
3043 loop_tai = sys_tai;
3044 ntv.modes = MOD_TAI;
3045 ntv.constant = sys_tai;
3046 ntp_adjtime(&ntv);
3047 }
3048#endif
3049 }
3050#endif
3051#endif
3052