-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathntpdate.c
2250 lines (1987 loc) · 49.1 KB
/
ntpdate.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
/*
* ntpdate - set the time of day by polling one or more NTP servers
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#ifdef HAVE_NETINFO
#include <netinfo/ni.h>
#endif
#include "ntp_machine.h"
#include "ntp_fp.h"
#include "ntp.h"
#include "ntp_io.h"
#include "timevalops.h"
#include "ntpdate.h"
#include "ntp_string.h"
#include "ntp_syslog.h"
#include "ntp_select.h"
#include "ntp_stdlib.h"
#include <ssl_applink.c>
#include "isc/net.h"
#include "isc/result.h"
#include "isc/sockaddr.h"
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#include <stdio.h>
#include <signal.h>
#include <ctype.h>
#ifdef HAVE_POLL_H
# include <poll.h>
#endif
#ifdef HAVE_SYS_SIGNAL_H
# include <sys/signal.h>
#endif
#ifdef HAVE_SYS_IOCTL_H
# include <sys/ioctl.h>
#endif
#ifdef HAVE_SYS_RESOURCE_H
# include <sys/resource.h>
#endif
#include <arpa/inet.h>
#ifdef SYS_VXWORKS
# include "ioLib.h"
# include "sockLib.h"
# include "timers.h"
/* select wants a zero structure ... */
struct timeval timeout = {0,0};
#elif defined(SYS_WINNT)
/*
* Windows does not abort a select select call if SIGALRM goes off
* so a 200 ms timeout is needed (TIMER_HZ is 5).
*/
struct sock_timeval timeout = {0,1000000/TIMER_HZ};
#else
struct timeval timeout = {60,0};
#endif
#ifdef HAVE_NETINFO
#include <netinfo/ni.h>
#endif
#include "recvbuff.h"
#ifdef SYS_WINNT
#define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
on Windows NT timers. */
#pragma comment(lib, "winmm")
isc_boolean_t ntp_port_inuse(int af, u_short port);
UINT wTimerRes;
#endif /* SYS_WINNT */
/*
* Scheduling priority we run at
*/
#ifndef SYS_VXWORKS
# define NTPDATE_PRIO (-12)
#else
# define NTPDATE_PRIO (100)
#endif
#ifdef HAVE_TIMER_CREATE
/* POSIX TIMERS - vxWorks doesn't have itimer - casey */
static timer_t ntpdate_timerid;
#endif
/*
* Compatibility stuff for Version 2
*/
#define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
#define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
#define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
#define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
#define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
#define NTP_MAXLIST 5 /* maximum select list size */
#define PEER_SHIFT 8 /* 8 suitable for crystal time base */
/*
* for get_systime()
*/
s_char sys_precision; /* local clock precision (log2 s) */
/*
* File descriptor masks etc. for call to select
*/
int ai_fam_templ;
int nbsock; /* the number of sockets used */
SOCKET fd[MAX_AF];
int fd_family[MAX_AF]; /* to remember the socket family */
#ifdef HAVE_POLL_H
struct pollfd fdmask[MAX_AF];
#else
fd_set fdmask;
SOCKET maxfd;
#endif
int polltest = 0;
/*
* Initializing flag. All async routines watch this and only do their
* thing when it is clear.
*/
int initializing = 1;
/*
* Alarm flag. Set when an alarm occurs
*/
volatile int alarm_flag = 0;
/*
* Simple query flag.
*/
int simple_query = 0;
/*
* Unprivileged port flag.
*/
int unpriv_port = 0;
/*
* Program name.
*/
char const *progname;
/*
* Systemwide parameters and flags
*/
int sys_samples = DEFSAMPLES; /* number of samples/server */
u_long sys_timeout = DEFTIMEOUT; /* timeout time, in TIMER_HZ units */
struct server *sys_servers; /* the server list */
int sys_numservers = 0; /* number of servers to poll */
int sys_authenticate = 0; /* true when authenticating */
u_int32 sys_authkey = 0; /* set to authentication key in use */
u_long sys_authdelay = 0; /* authentication delay */
int sys_version = NTP_VERSION; /* version to poll with */
/*
* The current internal time
*/
u_long current_time = 0;
/*
* Counter for keeping track of completed servers
*/
int complete_servers = 0;
/*
* File of encryption keys
*/
#ifndef KEYFILE
# ifndef SYS_WINNT
#define KEYFILE "/etc/ntp.keys"
# else
#define KEYFILE "%windir%\\ntp.keys"
# endif /* SYS_WINNT */
#endif /* KEYFILE */
#ifndef SYS_WINNT
const char *key_file = KEYFILE;
#else
char key_file_storage[MAX_PATH+1], *key_file ;
#endif /* SYS_WINNT */
/*
* Miscellaneous flags
*/
int verbose = 0;
int always_step = 0;
int never_step = 0;
int ntpdatemain (int, char **);
static void transmit (struct server *);
static void receive (struct recvbuf *);
static void server_data (struct server *, s_fp, l_fp *, u_fp);
static void clock_filter (struct server *);
static struct server *clock_select (void);
static int clock_adjust (void);
static void addserver (char *);
static struct server *findserver (sockaddr_u *);
void timer (void);
static void init_alarm (void);
#ifndef SYS_WINNT
static RETSIGTYPE alarming (int);
#endif /* SYS_WINNT */
static void init_io (void);
static void sendpkt (sockaddr_u *, struct pkt *, int);
void input_handler (void);
static int l_adj_systime (l_fp *);
static int l_step_systime (l_fp *);
static void printserver (struct server *, FILE *);
#ifdef SYS_WINNT
int on = 1;
WORD wVersionRequested;
WSADATA wsaData;
#endif /* SYS_WINNT */
#ifdef NO_MAIN_ALLOWED
CALL(ntpdate,"ntpdate",ntpdatemain);
void clear_globals()
{
/*
* Debugging flag
*/
debug = 0;
ntp_optind = 0;
/*
* Initializing flag. All async routines watch this and only do their
* thing when it is clear.
*/
initializing = 1;
/*
* Alarm flag. Set when an alarm occurs
*/
alarm_flag = 0;
/*
* Simple query flag.
*/
simple_query = 0;
/*
* Unprivileged port flag.
*/
unpriv_port = 0;
/*
* Systemwide parameters and flags
*/
sys_numservers = 0; /* number of servers to poll */
sys_authenticate = 0; /* true when authenticating */
sys_authkey = 0; /* set to authentication key in use */
sys_authdelay = 0; /* authentication delay */
sys_version = NTP_VERSION; /* version to poll with */
/*
* The current internal time
*/
current_time = 0;
/*
* Counter for keeping track of completed servers
*/
complete_servers = 0;
verbose = 0;
always_step = 0;
never_step = 0;
}
#endif
#ifdef HAVE_NETINFO
static ni_namelist *getnetinfoservers (void);
#endif
/*
* Main program. Initialize us and loop waiting for I/O and/or
* timer expiries.
*/
#ifndef NO_MAIN_ALLOWED
int
main(
int argc,
char *argv[]
)
{
return ntpdatemain (argc, argv);
}
#endif /* NO_MAIN_ALLOWED */
int
ntpdatemain (
int argc,
char *argv[]
)
{
int was_alarmed;
int tot_recvbufs;
struct recvbuf *rbuf;
l_fp tmp;
int errflg;
int c;
int nfound;
#ifdef HAVE_NETINFO
ni_namelist *netinfoservers;
#endif
#ifdef SYS_WINNT
key_file = key_file_storage;
if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m");
ssl_applink();
#endif /* SYS_WINNT */
#ifdef NO_MAIN_ALLOWED
clear_globals();
#endif
init_lib(); /* sets up ipv4_works, ipv6_works */
/* Check to see if we have IPv6. Otherwise default to IPv4 */
if (!ipv6_works)
ai_fam_templ = AF_INET;
errflg = 0;
progname = argv[0];
syslogit = 0;
/*
* Decode argument list
*/
while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
switch (c)
{
case '4':
ai_fam_templ = AF_INET;
break;
case '6':
ai_fam_templ = AF_INET6;
break;
case 'a':
c = atoi(ntp_optarg);
sys_authenticate = 1;
sys_authkey = c;
break;
case 'b':
always_step++;
never_step = 0;
break;
case 'B':
never_step++;
always_step = 0;
break;
case 'd':
++debug;
break;
case 'e':
if (!atolfp(ntp_optarg, &tmp)
|| tmp.l_ui != 0) {
(void) fprintf(stderr,
"%s: encryption delay %s is unlikely\n",
progname, ntp_optarg);
errflg++;
} else {
sys_authdelay = tmp.l_uf;
}
break;
case 'k':
key_file = ntp_optarg;
break;
case 'o':
sys_version = atoi(ntp_optarg);
break;
case 'p':
c = atoi(ntp_optarg);
if (c <= 0 || c > NTP_SHIFT) {
(void) fprintf(stderr,
"%s: number of samples (%d) is invalid\n",
progname, c);
errflg++;
} else {
sys_samples = c;
}
break;
case 'q':
simple_query = 1;
break;
case 's':
syslogit = 1;
break;
case 't':
if (!atolfp(ntp_optarg, &tmp)) {
(void) fprintf(stderr,
"%s: timeout %s is undecodeable\n",
progname, ntp_optarg);
errflg++;
} else {
sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
+ 0x8000) >> 16;
sys_timeout = max(sys_timeout, MINTIMEOUT);
}
break;
case 'v':
verbose = 1;
break;
case 'u':
unpriv_port = 1;
break;
case '?':
++errflg;
break;
default:
break;
}
if (errflg) {
(void) fprintf(stderr,
"usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
progname);
exit(2);
}
if (debug || simple_query) {
#ifdef HAVE_SETVBUF
static char buf[BUFSIZ];
setvbuf(stdout, buf, _IOLBF, BUFSIZ);
#else
setlinebuf(stdout);
#endif
}
/*
* Logging. Open the syslog if we have to
*/
if (syslogit) {
#if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
# ifndef LOG_DAEMON
openlog("ntpdate", LOG_PID);
# else
# ifndef LOG_NTP
# define LOG_NTP LOG_DAEMON
# endif
openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
if (debug)
setlogmask(LOG_UPTO(LOG_DEBUG));
else
setlogmask(LOG_UPTO(LOG_INFO));
# endif /* LOG_DAEMON */
#endif /* SYS_WINNT */
}
if (debug || verbose)
msyslog(LOG_NOTICE, "%s", Version);
/*
* Add servers we are going to be polling
*/
#ifdef HAVE_NETINFO
netinfoservers = getnetinfoservers();
#endif
for ( ; ntp_optind < argc; ntp_optind++)
addserver(argv[ntp_optind]);
#ifdef HAVE_NETINFO
if (netinfoservers) {
if ( netinfoservers->ni_namelist_len &&
*netinfoservers->ni_namelist_val ) {
u_int servercount = 0;
while (servercount < netinfoservers->ni_namelist_len) {
if (debug) msyslog(LOG_DEBUG,
"Adding time server %s from NetInfo configuration.",
netinfoservers->ni_namelist_val[servercount]);
addserver(netinfoservers->ni_namelist_val[servercount++]);
}
}
ni_namelist_free(netinfoservers);
free(netinfoservers);
}
#endif
if (sys_numservers == 0) {
msyslog(LOG_ERR, "no servers can be used, exiting");
exit(1);
}
/*
* Initialize the time of day routines and the I/O subsystem
*/
if (sys_authenticate) {
init_auth();
if (!authreadkeys(key_file)) {
msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
exit(1);
}
authtrust(sys_authkey, 1);
if (!authistrusted(sys_authkey)) {
msyslog(LOG_ERR, "authentication key %lu unknown",
(unsigned long) sys_authkey);
exit(1);
}
}
init_io();
init_alarm();
/*
* Set the priority.
*/
#ifdef SYS_VXWORKS
taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
#endif
#if defined(HAVE_ATT_NICE)
nice (NTPDATE_PRIO);
#endif
#if defined(HAVE_BSD_NICE)
(void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
#endif
initializing = 0;
was_alarmed = 0;
while (complete_servers < sys_numservers) {
#ifdef HAVE_POLL_H
struct pollfd* rdfdes;
rdfdes = fdmask;
#else
fd_set rdfdes;
rdfdes = fdmask;
#endif
if (alarm_flag) { /* alarmed? */
was_alarmed = 1;
alarm_flag = 0;
}
tot_recvbufs = full_recvbuffs(); /* get received buffers */
if (!was_alarmed && tot_recvbufs == 0) {
/*
* Nothing to do. Wait for something.
*/
#ifdef HAVE_POLL_H
nfound = poll(rdfdes, (unsigned int)nbsock, timeout.tv_sec * 1000);
#else
nfound = select(maxfd, &rdfdes, NULL, NULL,
&timeout);
#endif
if (nfound > 0)
input_handler();
else if (nfound == SOCKET_ERROR)
{
#ifndef SYS_WINNT
if (errno != EINTR)
#else
if (WSAGetLastError() != WSAEINTR)
#endif
msyslog(LOG_ERR,
#ifdef HAVE_POLL_H
"poll() error: %m"
#else
"select() error: %m"
#endif
);
} else if (errno != 0) {
#ifndef SYS_VXWORKS
msyslog(LOG_DEBUG,
#ifdef HAVE_POLL_H
"poll(): nfound = %d, error: %m",
#else
"select(): nfound = %d, error: %m",
#endif
nfound);
#endif
}
if (alarm_flag) { /* alarmed? */
was_alarmed = 1;
alarm_flag = 0;
}
tot_recvbufs = full_recvbuffs(); /* get received buffers */
}
/*
* Out here, signals are unblocked. Call receive
* procedure for each incoming packet.
*/
rbuf = get_full_recv_buffer();
while (rbuf != NULL)
{
receive(rbuf);
freerecvbuf(rbuf);
rbuf = get_full_recv_buffer();
}
/*
* Call timer to process any timeouts
*/
if (was_alarmed) {
timer();
was_alarmed = 0;
}
/*
* Go around again
*/
}
/*
* When we get here we've completed the polling of all servers.
* Adjust the clock, then exit.
*/
#ifdef SYS_WINNT
WSACleanup();
#endif
#ifdef SYS_VXWORKS
close (fd);
timer_delete(ntpdate_timerid);
#endif
return clock_adjust();
}
/*
* transmit - transmit a packet to the given server, or mark it completed.
* This is called by the timeout routine and by the receive
* procedure.
*/
static void
transmit(
register struct server *server
)
{
struct pkt xpkt;
if (debug)
printf("transmit(%s)\n", stoa(&server->srcadr));
if (server->filter_nextpt < server->xmtcnt) {
l_fp ts;
/*
* Last message to this server timed out. Shift
* zeros into the filter.
*/
L_CLR(&ts);
server_data(server, 0, &ts, 0);
}
if ((int)server->filter_nextpt >= sys_samples) {
/*
* Got all the data we need. Mark this guy
* completed and return.
*/
server->event_time = 0;
complete_servers++;
return;
}
/*
* If we're here, send another message to the server. Fill in
* the packet and let 'er rip.
*/
xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
sys_version, MODE_CLIENT);
xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
xpkt.ppoll = NTP_MINPOLL;
xpkt.precision = NTPDATE_PRECISION;
xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
xpkt.rootdisp = htonl(NTPDATE_DISP);
xpkt.refid = htonl(NTPDATE_REFID);
L_CLR(&xpkt.reftime);
L_CLR(&xpkt.org);
L_CLR(&xpkt.rec);
/*
* Determine whether to authenticate or not. If so,
* fill in the extended part of the packet and do it.
* If not, just timestamp it and send it away.
*/
if (sys_authenticate) {
size_t len;
xpkt.exten[0] = htonl(sys_authkey);
get_systime(&server->xmt);
L_ADDUF(&server->xmt, sys_authdelay);
HTONL_FP(&server->xmt, &xpkt.xmt);
len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
sendpkt(&server->srcadr, &xpkt, (int)(LEN_PKT_NOMAC + len));
if (debug > 1)
printf("transmit auth to %s\n",
stoa(&server->srcadr));
} else {
get_systime(&(server->xmt));
HTONL_FP(&server->xmt, &xpkt.xmt);
sendpkt(&server->srcadr, &xpkt, LEN_PKT_NOMAC);
if (debug > 1)
printf("transmit to %s\n", stoa(&server->srcadr));
}
/*
* Update the server timeout and transmit count
*/
server->event_time = current_time + sys_timeout;
server->xmtcnt++;
}
/*
* receive - receive and process an incoming frame
*/
static void
receive(
struct recvbuf *rbufp
)
{
register struct pkt *rpkt;
register struct server *server;
register s_fp di;
l_fp t10, t23, tmp;
l_fp org;
l_fp rec;
l_fp ci;
int has_mac;
int is_authentic;
if (debug)
printf("receive(%s)\n", stoa(&rbufp->recv_srcadr));
/*
* Check to see if the packet basically looks like something
* intended for us.
*/
if (rbufp->recv_length == LEN_PKT_NOMAC)
has_mac = 0;
else if (rbufp->recv_length >= (int)LEN_PKT_NOMAC)
has_mac = 1;
else {
if (debug)
printf("receive: packet length %d\n",
rbufp->recv_length);
return; /* funny length packet */
}
rpkt = &(rbufp->recv_pkt);
if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
return;
}
if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
&& PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
|| rpkt->stratum >= STRATUM_UNSPEC) {
if (debug)
printf("receive: mode %d stratum %d\n",
PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
return;
}
/*
* So far, so good. See if this is from a server we know.
*/
server = findserver(&(rbufp->recv_srcadr));
if (server == NULL) {
if (debug)
printf("receive: server not found\n");
return;
}
/*
* Decode the org timestamp and make sure we're getting a response
* to our last request.
*/
NTOHL_FP(&rpkt->org, &org);
if (!L_ISEQU(&org, &server->xmt)) {
if (debug)
printf("receive: pkt.org and peer.xmt differ\n");
return;
}
/*
* Check out the authenticity if we're doing that.
*/
if (!sys_authenticate)
is_authentic = 1;
else {
is_authentic = 0;
if (debug > 3)
printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
(long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
(long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
LEN_PKT_NOMAC, (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)));
if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
(size_t)(rbufp->recv_length - LEN_PKT_NOMAC)))
is_authentic = 1;
if (debug)
printf("receive: authentication %s\n",
is_authentic ? "passed" : "failed");
}
server->trust <<= 1;
if (!is_authentic)
server->trust |= 1;
/*
* Check for a KoD (rate limiting) response, cease and decist.
*/
if (LEAP_NOTINSYNC == PKT_LEAP(rpkt->li_vn_mode) &&
STRATUM_PKT_UNSPEC == rpkt->stratum &&
!memcmp("RATE", &rpkt->refid, 4)) {
msyslog(LOG_ERR, "%s rate limit response from server.",
stoa(&rbufp->recv_srcadr));
server->event_time = 0;
complete_servers++;
return;
}
/*
* Looks good. Record info from the packet.
*/
server->leap = PKT_LEAP(rpkt->li_vn_mode);
server->stratum = PKT_TO_STRATUM(rpkt->stratum);
server->precision = rpkt->precision;
server->rootdelay = ntohl(rpkt->rootdelay);
server->rootdisp = ntohl(rpkt->rootdisp);
server->refid = rpkt->refid;
NTOHL_FP(&rpkt->reftime, &server->reftime);
NTOHL_FP(&rpkt->rec, &rec);
NTOHL_FP(&rpkt->xmt, &server->org);
/*
* Make sure the server is at least somewhat sane. If not, try
* again.
*/
if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
server->event_time = current_time + sys_timeout;
return;
}
/*
* Calculate the round trip delay (di) and the clock offset (ci).
* We use the equations (reordered from those in the spec):
*
* d = (t2 - t3) - (t1 - t0)
* c = ((t2 - t3) + (t1 - t0)) / 2
*/
t10 = server->org; /* pkt.xmt == t1 */
L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
t23 = rec; /* pkt.rec == t2 */
L_SUB(&t23, &org); /* pkt->org == t3 */
/* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
/*
* Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
* For large offsets this may prevent an overflow on '+'
*/
ci = t10;
L_RSHIFT(&ci);
tmp = t23;
L_RSHIFT(&tmp);
L_ADD(&ci, &tmp);
/*
* Calculate di in t23 in full precision, then truncate
* to an s_fp.
*/
L_SUB(&t23, &t10);
di = LFPTOFP(&t23);
if (debug > 3)
printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
+ (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
if (di <= 0) { /* value still too raunchy to use? */
L_CLR(&ci);
di = 0;
} else {
di = max(di, NTP_MINDIST);
}
/*
* Shift this data in, then schedule another transmit.
*/
server_data(server, (s_fp) di, &ci, 0);
if ((int)server->filter_nextpt >= sys_samples) {
/*
* Got all the data we need. Mark this guy
* completed and return.
*/
server->event_time = 0;
complete_servers++;
return;
}
server->event_time = current_time + sys_timeout;
}
/*
* server_data - add a sample to the server's filter registers
*/
static void
server_data(
register struct server *server,
s_fp d,
l_fp *c,
u_fp e
)
{
u_short i;
i = server->filter_nextpt;
if (i < NTP_SHIFT) {
server->filter_delay[i] = d;
server->filter_offset[i] = *c;
server->filter_soffset[i] = LFPTOFP(c);
server->filter_error[i] = e;
server->filter_nextpt = (u_short)(i + 1);
}
}
/*
* clock_filter - determine a server's delay, dispersion and offset
*/
static void
clock_filter(
register struct server *server
)
{
register int i, j;
int ord[NTP_SHIFT];
/*
* Sort indices into increasing delay order
*/
for (i = 0; i < sys_samples; i++)
ord[i] = i;
for (i = 0; i < (sys_samples-1); i++) {
for (j = i+1; j < sys_samples; j++) {
if (server->filter_delay[ord[j]] == 0)
continue;
if (server->filter_delay[ord[i]] == 0
|| (server->filter_delay[ord[i]]
> server->filter_delay[ord[j]])) {
register int tmp;
tmp = ord[i];
ord[i] = ord[j];
ord[j] = tmp;
}
}
}
/*
* Now compute the dispersion, and assign values to delay and
* offset. If there are no samples in the register, delay and
* offset go to zero and dispersion is set to the maximum.
*/
if (server->filter_delay[ord[0]] == 0) {
server->delay = 0;
L_CLR(&server->offset);
server->soffset = 0;
server->dispersion = PEER_MAXDISP;
} else {
register s_fp d;
server->delay = server->filter_delay[ord[0]];
server->offset = server->filter_offset[ord[0]];
server->soffset = LFPTOFP(&server->offset);
server->dispersion = 0;
for (i = 1; i < sys_samples; i++) {
if (server->filter_delay[ord[i]] == 0)
d = PEER_MAXDISP;
else {