1 /*
2 * ntpdate - set the time of day by polling one or more NTP servers
3 */
4
5 #ifdef HAVE_CONFIG_H
6 # include <config.h>
7 #endif
8
9 #ifdef HAVE_NETINFO
10 #include <netinfo/ni.h>
11 #endif
12
13 #include "ntp_machine.h"
14 #include "ntp_fp.h"
15 #include "ntp.h"
16 #include "ntp_io.h"
17 #include "timevalops.h"
18 #include "ntpdate.h"
19 #include "ntp_string.h"
20 #include "ntp_syslog.h"
21 #include "ntp_select.h"
22 #include "ntp_stdlib.h"
23 #include <ssl_applink.c>
24
25 #include "isc/net.h"
26 #include "isc/result.h"
27 #include "isc/sockaddr.h"
28
29 #ifdef HAVE_UNISTD_H
30 # include <unistd.h>
31 #endif
32
33 #include <stdio.h>
34 #include <signal.h>
35 #include <ctype.h>
36 #ifdef HAVE_POLL_H
37 # include <poll.h>
38 #endif
39 #ifdef HAVE_SYS_SIGNAL_H
40 # include <sys/signal.h>
41 #endif
42 #ifdef HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
44 #endif
45 #ifdef HAVE_SYS_RESOURCE_H
46 # include <sys/resource.h>
47 #endif
48
49 #include <arpa/inet.h>
50
51 #ifdef SYS_VXWORKS
52 # include "ioLib.h"
53 # include "sockLib.h"
54 # include "timers.h"
55
56 /* select wants a zero structure ... */
57 struct timeval timeout = {0,0};
58 #elif defined(SYS_WINNT)
59 /*
60 * Windows does not abort a select select call if SIGALRM goes off
61 * so a 200 ms timeout is needed (TIMER_HZ is 5).
62 */
63 struct sock_timeval timeout = {0,1000000/TIMER_HZ};
64 #else
65 struct timeval timeout = {60,0};
66 #endif
67
68 #ifdef HAVE_NETINFO
69 #include <netinfo/ni.h>
70 #endif
71
72 #include "recvbuff.h"
73
74 #ifdef SYS_WINNT
75 #define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
76 on Windows NT timers. */
77 #pragma comment(lib, "winmm")
78 isc_boolean_t ntp_port_inuse(int af, u_short port);
79 UINT wTimerRes;
80 #endif /* SYS_WINNT */
81
82 /*
83 * Scheduling priority we run at
84 */
85 #ifndef SYS_VXWORKS
86 # define NTPDATE_PRIO (-12)
87 #else
88 # define NTPDATE_PRIO (100)
89 #endif
90
91 #ifdef HAVE_TIMER_CREATE
92 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
93 static timer_t ntpdate_timerid;
94 #endif
95
96 /*
97 * Compatibility stuff for Version 2
98 */
99 #define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
100 #define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
101 #define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
102 #define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
103 #define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
104 #define NTP_MAXLIST 5 /* maximum select list size */
105 #define PEER_SHIFT 8 /* 8 suitable for crystal time base */
106
107 /*
108 * for get_systime()
109 */
110 s_char sys_precision; /* local clock precision (log2 s) */
111
112 /*
113 * File descriptor masks etc. for call to select
114 */
115
116 int ai_fam_templ;
117 int nbsock; /* the number of sockets used */
118 SOCKET fd[MAX_AF];
119 int fd_family[MAX_AF]; /* to remember the socket family */
120 #ifdef HAVE_POLL_H
121 struct pollfd fdmask[MAX_AF];
122 #else
123 fd_set fdmask;
124 SOCKET maxfd;
125 #endif
126 int polltest = 0;
127
128 /*
129 * Initializing flag. All async routines watch this and only do their
130 * thing when it is clear.
131 */
132 int initializing = 1;
133
134 /*
135 * Alarm flag. Set when an alarm occurs
136 */
137 volatile int alarm_flag = 0;
138
139 /*
140 * Simple query flag.
141 */
142 int simple_query = 0;
143
144 /*
145 * Unprivileged port flag.
146 */
147 int unpriv_port = 0;
148
149 /*
150 * Program name.
151 */
152 char const *progname;
153
154 /*
155 * Systemwide parameters and flags
156 */
157 int sys_samples = 0; /* number of samples/server, will be modified later */
158 u_long sys_timeout = DEFTIMEOUT; /* timeout time, in TIMER_HZ units */
159 struct server *sys_servers; /* the server list */
160 int sys_numservers = 0; /* number of servers to poll */
161 int sys_authenticate = 0; /* true when authenticating */
162 u_int32 sys_authkey = 0; /* set to authentication key in use */
163 u_long sys_authdelay = 0; /* authentication delay */
164 int sys_version = NTP_VERSION; /* version to poll with */
165
166 /*
167 * The current internal time
168 */
169 u_long current_time = 0;
170
171 /*
172 * Counter for keeping track of completed servers
173 */
174 int complete_servers = 0;
175
176 /*
177 * File of encryption keys
178 */
179
180 #ifndef KEYFILE
181 # ifndef SYS_WINNT
182 #define KEYFILE "/etc/ntp.keys"
183 # else
184 #define KEYFILE "%windir%\\ntp.keys"
185 # endif /* SYS_WINNT */
186 #endif /* KEYFILE */
187
188 #ifndef SYS_WINNT
189 const char *key_file = KEYFILE;
190 #else
191 char key_file_storage[MAX_PATH+1], *key_file ;
192 #endif /* SYS_WINNT */
193
194 /*
195 * Miscellaneous flags
196 */
197 int verbose = 0;
198 int always_step = 0;
199 int never_step = 0;
200
201 int ntpdatemain (int, char **);
202
203 static void transmit (struct server *);
204 static void receive (struct recvbuf *);
205 static void server_data (struct server *, s_fp, l_fp *, u_fp);
206 static void clock_filter (struct server *);
207 static struct server *clock_select (void);
208 static int clock_adjust (void);
209 static void addserver (char *);
210 static struct server *findserver (sockaddr_u *);
211 void timer (void);
212 static void init_alarm (void);
213 #ifndef SYS_WINNT
214 static RETSIGTYPE alarming (int);
215 #endif /* SYS_WINNT */
216 static void init_io (void);
217 static void sendpkt (sockaddr_u *, struct pkt *, int);
218 void input_handler (void);
219
220 static int l_adj_systime (l_fp *);
221 static int l_step_systime (l_fp *);
222
223 static void print_server (struct server *, FILE *);
224
225 #ifdef SYS_WINNT
226 int on = 1;
227 WORD wVersionRequested;
228 WSADATA wsaData;
229 #endif /* SYS_WINNT */
230
231 #ifdef NO_MAIN_ALLOWED
232 CALL(ntpdate,"ntpdate",ntpdatemain);
233
clear_globals()234 void clear_globals()
235 {
236 /*
237 * Debugging flag
238 */
239 debug = 0;
240
241 ntp_optind = 0;
242 /*
243 * Initializing flag. All async routines watch this and only do their
244 * thing when it is clear.
245 */
246 initializing = 1;
247
248 /*
249 * Alarm flag. Set when an alarm occurs
250 */
251 alarm_flag = 0;
252
253 /*
254 * Simple query flag.
255 */
256 simple_query = 0;
257
258 /*
259 * Unprivileged port flag.
260 */
261 unpriv_port = 0;
262
263 /*
264 * Systemwide parameters and flags
265 */
266 sys_numservers = 0; /* number of servers to poll */
267 sys_authenticate = 0; /* true when authenticating */
268 sys_authkey = 0; /* set to authentication key in use */
269 sys_authdelay = 0; /* authentication delay */
270 sys_version = NTP_VERSION; /* version to poll with */
271
272 /*
273 * The current internal time
274 */
275 current_time = 0;
276
277 /*
278 * Counter for keeping track of completed servers
279 */
280 complete_servers = 0;
281 verbose = 0;
282 always_step = 0;
283 never_step = 0;
284 }
285 #endif
286
287 #ifdef HAVE_NETINFO
288 static ni_namelist *getnetinfoservers (void);
289 #endif
290
291 /*
292 * Main program. Initialize us and loop waiting for I/O and/or
293 * timer expiries.
294 */
295 #ifndef NO_MAIN_ALLOWED
296 int
main(int argc,char * argv[])297 main(
298 int argc,
299 char *argv[]
300 )
301 {
302 msyslog(LOG_NOTICE,"ntpdate is deprecated and "
303 "scheduled for removal in ntp 4.4, use ntpd -q instead");
304 return ntpdatemain (argc, argv);
305 }
306 #endif /* NO_MAIN_ALLOWED */
307
308 int
ntpdatemain(int argc,char * argv[])309 ntpdatemain (
310 int argc,
311 char *argv[]
312 )
313 {
314 int was_alarmed;
315 int tot_recvbufs;
316 struct recvbuf *rbuf;
317 l_fp tmp;
318 int errflg;
319 int c;
320 int nfound;
321
322 #ifdef HAVE_NETINFO
323 ni_namelist *netinfoservers;
324 #endif
325 #ifdef SYS_WINNT
326 key_file = key_file_storage;
327
328 if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
329 msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m");
330
331 ssl_applink();
332 #endif /* SYS_WINNT */
333
334 #ifdef NO_MAIN_ALLOWED
335 clear_globals();
336 #endif
337
338 init_lib(); /* sets up ipv4_works, ipv6_works */
339
340 /* Check to see if we have IPv6. Otherwise default to IPv4 */
341 if (!ipv6_works)
342 ai_fam_templ = AF_INET;
343
344 #ifdef HAVE_NETINFO
345 errflg = 0; /* servers can come from netinfo */
346 #else
347 errflg = (argc < 2); /* need at least server on cmdline */
348 #endif
349 progname = argv[0];
350 syslogit = 0;
351
352 /*
353 * Decode argument list
354 */
355 while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
356 switch (c)
357 {
358 case '4':
359 ai_fam_templ = AF_INET;
360 break;
361 case '6':
362 ai_fam_templ = AF_INET6;
363 break;
364 case 'a':
365 c = atoi(ntp_optarg);
366 sys_authenticate = 1;
367 sys_authkey = c;
368 break;
369 case 'b':
370 always_step++;
371 never_step = 0;
372 break;
373 case 'B':
374 never_step++;
375 always_step = 0;
376 break;
377 case 'd':
378 ++debug;
379 break;
380 case 'e':
381 if (!atolfp(ntp_optarg, &tmp)
382 || tmp.l_ui != 0) {
383 (void) fprintf(stderr,
384 "%s: encryption delay %s is unlikely\n",
385 progname, ntp_optarg);
386 errflg++;
387 } else {
388 sys_authdelay = tmp.l_uf;
389 }
390 break;
391 case 'k':
392 key_file = ntp_optarg;
393 break;
394 case 'o':
395 sys_version = atoi(ntp_optarg);
396 break;
397 case 'p':
398 c = atoi(ntp_optarg);
399 if (c <= 0 || c > NTP_SHIFT) {
400 (void) fprintf(stderr,
401 "%s: number of samples (%d) is invalid\n",
402 progname, c);
403 errflg++;
404 } else {
405 sys_samples = c;
406 }
407 break;
408 case 'q':
409 simple_query = 1;
410 break;
411 case 's':
412 syslogit = 1;
413 break;
414 case 't':
415 if (!atolfp(ntp_optarg, &tmp)) {
416 (void) fprintf(stderr,
417 "%s: timeout %s is undecodeable\n",
418 progname, ntp_optarg);
419 errflg++;
420 } else {
421 sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
422 + 0x8000) >> 16;
423 sys_timeout = max(sys_timeout, MINTIMEOUT);
424 }
425 break;
426 case 'v':
427 verbose = 1;
428 break;
429 case 'u':
430 unpriv_port = 1;
431 break;
432 case '?':
433 ++errflg;
434 break;
435 default:
436 break;
437 }
438
439 if (errflg) {
440 (void) fprintf(stderr,
441 "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
442 progname);
443 exit(2);
444 }
445
446 /*
447 * If number of Samples (-p) not specified by user:
448 * - if a simple_query (-q) just ONE will do
449 * - otherwise the normal is DEFSAMPLES
450 */
451 if (sys_samples == 0)
452 sys_samples = (simple_query ? 1 : DEFSAMPLES);
453
454 if (debug || simple_query) {
455 #ifdef HAVE_SETVBUF
456 static char buf[BUFSIZ];
457 setvbuf(stdout, buf, _IOLBF, BUFSIZ);
458 #else
459 setlinebuf(stdout);
460 #endif
461 }
462
463 /*
464 * Logging. Open the syslog if we have to
465 */
466 if (syslogit) {
467 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
468 # ifndef LOG_DAEMON
469 openlog("ntpdate", LOG_PID);
470 # else
471
472 # ifndef LOG_NTP
473 # define LOG_NTP LOG_DAEMON
474 # endif
475 openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
476 if (debug)
477 setlogmask(LOG_UPTO(LOG_DEBUG));
478 else
479 setlogmask(LOG_UPTO(LOG_INFO));
480 # endif /* LOG_DAEMON */
481 #endif /* SYS_WINNT */
482 }
483
484 if (debug || verbose)
485 msyslog(LOG_NOTICE, "%s", Version);
486
487 /*
488 * Add servers we are going to be polling
489 */
490 #ifdef HAVE_NETINFO
491 netinfoservers = getnetinfoservers();
492 #endif
493
494 for ( ; ntp_optind < argc; ntp_optind++)
495 addserver(argv[ntp_optind]);
496
497 #ifdef HAVE_NETINFO
498 if (netinfoservers) {
499 if ( netinfoservers->ni_namelist_len &&
500 *netinfoservers->ni_namelist_val ) {
501 u_int servercount = 0;
502 while (servercount < netinfoservers->ni_namelist_len) {
503 if (debug) msyslog(LOG_DEBUG,
504 "Adding time server %s from NetInfo configuration.",
505 netinfoservers->ni_namelist_val[servercount]);
506 addserver(netinfoservers->ni_namelist_val[servercount++]);
507 }
508 }
509 ni_namelist_free(netinfoservers);
510 free(netinfoservers);
511 }
512 #endif
513
514 if (sys_numservers == 0) {
515 msyslog(LOG_ERR, "no servers can be used, exiting");
516 exit(1);
517 }
518
519 /*
520 * Initialize the time of day routines and the I/O subsystem
521 */
522 if (sys_authenticate) {
523 init_auth();
524 if (!authreadkeys(key_file)) {
525 msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
526 exit(1);
527 }
528 authtrust(sys_authkey, 1);
529 if (!authistrusted(sys_authkey)) {
530 msyslog(LOG_ERR, "authentication key %lu unknown",
531 (unsigned long) sys_authkey);
532 exit(1);
533 }
534 }
535 init_io();
536 init_alarm();
537
538 /*
539 * Set the priority.
540 */
541 #ifdef SYS_VXWORKS
542 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
543 #endif
544 #if defined(HAVE_ATT_NICE)
545 nice (NTPDATE_PRIO);
546 #endif
547 #if defined(HAVE_BSD_NICE)
548 (void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
549 #endif
550
551
552 initializing = 0;
553 was_alarmed = 0;
554
555 while (complete_servers < sys_numservers) {
556 #ifdef HAVE_POLL_H
557 struct pollfd* rdfdes;
558 rdfdes = fdmask;
559 #else
560 fd_set rdfdes;
561 rdfdes = fdmask;
562 #endif
563
564 if (alarm_flag) { /* alarmed? */
565 was_alarmed = 1;
566 alarm_flag = 0;
567 }
568 tot_recvbufs = full_recvbuffs(); /* get received buffers */
569
570 if (!was_alarmed && tot_recvbufs == 0) {
571 /*
572 * Nothing to do. Wait for something.
573 */
574 #ifdef HAVE_POLL_H
575 nfound = poll(rdfdes, (unsigned int)nbsock, timeout.tv_sec * 1000);
576
577 #else
578 nfound = select(maxfd, &rdfdes, NULL, NULL,
579 &timeout);
580 #endif
581 if (nfound > 0)
582 input_handler();
583 else if (nfound == SOCKET_ERROR)
584 {
585 #ifndef SYS_WINNT
586 if (errno != EINTR)
587 #else
588 if (WSAGetLastError() != WSAEINTR)
589 #endif
590 msyslog(LOG_ERR,
591 #ifdef HAVE_POLL_H
592 "poll() error: %m"
593 #else
594 "select() error: %m"
595 #endif
596 );
597 } else if (errno != 0) {
598 #ifndef SYS_VXWORKS
599 msyslog(LOG_DEBUG,
600 #ifdef HAVE_POLL_H
601 "poll(): nfound = %d, error: %m",
602 #else
603 "select(): nfound = %d, error: %m",
604 #endif
605 nfound);
606 #endif
607 }
608 if (alarm_flag) { /* alarmed? */
609 was_alarmed = 1;
610 alarm_flag = 0;
611 }
612 tot_recvbufs = full_recvbuffs(); /* get received buffers */
613 }
614
615 /*
616 * Out here, signals are unblocked. Call receive
617 * procedure for each incoming packet.
618 */
619 rbuf = get_full_recv_buffer();
620 while (rbuf != NULL)
621 {
622 receive(rbuf);
623 freerecvbuf(rbuf);
624 rbuf = get_full_recv_buffer();
625 }
626
627 /*
628 * Call timer to process any timeouts
629 */
630 if (was_alarmed) {
631 timer();
632 was_alarmed = 0;
633 }
634
635 /*
636 * Go around again
637 */
638 }
639
640 /*
641 * When we get here we've completed the polling of all servers.
642 * Adjust the clock, then exit.
643 */
644 #ifdef SYS_WINNT
645 WSACleanup();
646 #endif
647 #ifdef SYS_VXWORKS
648 close (fd);
649 timer_delete(ntpdate_timerid);
650 #endif
651
652 return clock_adjust();
653 }
654
655
656 /*
657 * transmit - transmit a packet to the given server, or mark it completed.
658 * This is called by the timeout routine and by the receive
659 * procedure.
660 */
661 static void
transmit(register struct server * server)662 transmit(
663 register struct server *server
664 )
665 {
666 struct pkt xpkt;
667
668 if (server->filter_nextpt < server->xmtcnt) {
669 l_fp ts;
670 /*
671 * Last message to this server timed out. Shift
672 * zeros into the filter.
673 */
674 L_CLR(&ts);
675 server_data(server, 0, &ts, 0);
676 }
677
678 if ((int)server->filter_nextpt >= sys_samples) {
679 /*
680 * Got all the data we need. Mark this guy
681 * completed and return.
682 */
683 server->event_time = 0;
684 complete_servers++;
685 return;
686 }
687
688 if (debug)
689 printf("transmit(%s)\n", stoa(&server->srcadr));
690
691 /*
692 * If we're here, send another message to the server. Fill in
693 * the packet and let 'er rip.
694 */
695 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
696 sys_version, MODE_CLIENT);
697 xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
698 xpkt.ppoll = NTP_MINPOLL;
699 xpkt.precision = NTPDATE_PRECISION;
700 xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
701 xpkt.rootdisp = htonl(NTPDATE_DISP);
702 xpkt.refid = htonl(NTPDATE_REFID);
703 L_CLR(&xpkt.reftime);
704 L_CLR(&xpkt.org);
705 L_CLR(&xpkt.rec);
706
707 /*
708 * Determine whether to authenticate or not. If so,
709 * fill in the extended part of the packet and do it.
710 * If not, just timestamp it and send it away.
711 */
712 if (sys_authenticate) {
713 size_t len;
714
715 xpkt.exten[0] = htonl(sys_authkey);
716 get_systime(&server->xmt);
717 L_ADDUF(&server->xmt, sys_authdelay);
718 HTONL_FP(&server->xmt, &xpkt.xmt);
719 len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
720 sendpkt(&server->srcadr, &xpkt, (int)(LEN_PKT_NOMAC + len));
721
722 if (debug > 1)
723 printf("transmit auth to %s\n",
724 stoa(&server->srcadr));
725 } else {
726 get_systime(&(server->xmt));
727 HTONL_FP(&server->xmt, &xpkt.xmt);
728 sendpkt(&server->srcadr, &xpkt, LEN_PKT_NOMAC);
729
730 if (debug > 1)
731 printf("transmit to %s\n", stoa(&server->srcadr));
732 }
733
734 /*
735 * Update the server timeout and transmit count
736 */
737 server->event_time = current_time + sys_timeout;
738 server->xmtcnt++;
739 }
740
741
742 /*
743 * receive - receive and process an incoming frame
744 */
745 static void
receive(struct recvbuf * rbufp)746 receive(
747 struct recvbuf *rbufp
748 )
749 {
750 register struct pkt *rpkt;
751 register struct server *server;
752 register s_fp di;
753 l_fp t10, t23, tmp;
754 l_fp org;
755 l_fp rec;
756 l_fp ci;
757 int has_mac;
758 int is_authentic;
759
760 if (debug)
761 printf("receive(%s)\n", stoa(&rbufp->recv_srcadr));
762 /*
763 * Check to see if the packet basically looks like something
764 * intended for us.
765 */
766 if (rbufp->recv_length == LEN_PKT_NOMAC)
767 has_mac = 0;
768 else if (rbufp->recv_length >= (int)LEN_PKT_NOMAC)
769 has_mac = 1;
770 else {
771 if (debug)
772 printf("receive: packet length %d\n",
773 rbufp->recv_length);
774 return; /* funny length packet */
775 }
776
777 rpkt = &(rbufp->recv_pkt);
778 if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
779 PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
780 return;
781 }
782
783 if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
784 && PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
785 || rpkt->stratum >= STRATUM_UNSPEC) {
786 if (debug)
787 printf("receive: mode %d stratum %d\n",
788 PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
789 return;
790 }
791
792 /*
793 * So far, so good. See if this is from a server we know.
794 */
795 server = findserver(&(rbufp->recv_srcadr));
796 if (server == NULL) {
797 if (debug)
798 printf("receive: server not found\n");
799 return;
800 }
801
802 /*
803 * Decode the org timestamp and make sure we're getting a response
804 * to our last request.
805 */
806 NTOHL_FP(&rpkt->org, &org);
807 if (!L_ISEQU(&org, &server->xmt)) {
808 if (debug)
809 printf("receive: pkt.org and peer.xmt differ\n");
810 return;
811 }
812
813 /*
814 * Check out the authenticity if we're doing that.
815 */
816 if (!sys_authenticate)
817 is_authentic = 1;
818 else {
819 is_authentic = 0;
820
821 if (debug > 3)
822 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
823 (long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
824 (long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
825 LEN_PKT_NOMAC, (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)));
826
827 if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
828 authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
829 (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)))
830 is_authentic = 1;
831 if (debug)
832 printf("receive: authentication %s\n",
833 is_authentic ? "passed" : "failed");
834 }
835 server->trust <<= 1;
836 if (!is_authentic)
837 server->trust |= 1;
838
839 /*
840 * Check for a KoD (rate limiting) response, cease and decist.
841 */
842 if (LEAP_NOTINSYNC == PKT_LEAP(rpkt->li_vn_mode) &&
843 STRATUM_PKT_UNSPEC == rpkt->stratum &&
844 !memcmp("RATE", &rpkt->refid, 4)) {
845 msyslog(LOG_ERR, "%s rate limit response from server.",
846 stoa(&rbufp->recv_srcadr));
847 server->event_time = 0;
848 complete_servers++;
849 return;
850 }
851
852 /*
853 * Looks good. Record info from the packet.
854 */
855 server->leap = PKT_LEAP(rpkt->li_vn_mode);
856 server->stratum = PKT_TO_STRATUM(rpkt->stratum);
857 server->precision = rpkt->precision;
858 server->rootdelay = ntohl(rpkt->rootdelay);
859 server->rootdisp = ntohl(rpkt->rootdisp);
860 server->refid = rpkt->refid;
861 NTOHL_FP(&rpkt->reftime, &server->reftime);
862 NTOHL_FP(&rpkt->rec, &rec);
863 NTOHL_FP(&rpkt->xmt, &server->org);
864
865 /*
866 * Make sure the server is at least somewhat sane. If not, try
867 * again.
868 */
869 if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
870 server->event_time = current_time + sys_timeout;
871 return;
872 }
873
874 /*
875 * Calculate the round trip delay (di) and the clock offset (ci).
876 * We use the equations (reordered from those in the spec):
877 *
878 * d = (t2 - t3) - (t1 - t0)
879 * c = ((t2 - t3) + (t1 - t0)) / 2
880 */
881 t10 = server->org; /* pkt.xmt == t1 */
882 L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
883
884 t23 = rec; /* pkt.rec == t2 */
885 L_SUB(&t23, &org); /* pkt->org == t3 */
886
887 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
888 /*
889 * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
890 * For large offsets this may prevent an overflow on '+'
891 */
892 ci = t10;
893 L_RSHIFT(&ci);
894 tmp = t23;
895 L_RSHIFT(&tmp);
896 L_ADD(&ci, &tmp);
897
898 /*
899 * Calculate di in t23 in full precision, then truncate
900 * to an s_fp.
901 */
902 L_SUB(&t23, &t10);
903 di = LFPTOFP(&t23);
904
905 if (debug > 3)
906 printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
907
908 di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
909 + (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
910
911 if (di <= 0) { /* value still too raunchy to use? */
912 L_CLR(&ci);
913 di = 0;
914 } else {
915 di = max(di, NTP_MINDIST);
916 }
917
918 /*
919 * Shift this data in, then schedule another transmit.
920 */
921 server_data(server, (s_fp) di, &ci, 0);
922
923 if ((int)server->filter_nextpt >= sys_samples) {
924 /*
925 * Got all the data we need. Mark this guy
926 * completed and return.
927 */
928 server->event_time = 0;
929 complete_servers++;
930 return;
931 }
932
933 server->event_time = current_time + sys_timeout;
934 }
935
936
937 /*
938 * server_data - add a sample to the server's filter registers
939 */
940 static void
server_data(register struct server * server,s_fp d,l_fp * c,u_fp e)941 server_data(
942 register struct server *server,
943 s_fp d,
944 l_fp *c,
945 u_fp e
946 )
947 {
948 u_short i;
949
950 i = server->filter_nextpt;
951 if (i < NTP_SHIFT) {
952 server->filter_delay[i] = d;
953 server->filter_offset[i] = *c;
954 server->filter_soffset[i] = LFPTOFP(c);
955 server->filter_error[i] = e;
956 server->filter_nextpt = (u_short)(i + 1);
957 }
958 }
959
960
961 /*
962 * clock_filter - determine a server's delay, dispersion and offset
963 */
964 static void
clock_filter(register struct server * server)965 clock_filter(
966 register struct server *server
967 )
968 {
969 register int i, j;
970 int ord[NTP_SHIFT];
971
972 INSIST((0 < sys_samples) && (sys_samples <= NTP_SHIFT));
973
974 /*
975 * Sort indices into increasing delay order
976 */
977 for (i = 0; i < sys_samples; i++)
978 ord[i] = i;
979
980 for (i = 0; i < (sys_samples-1); i++) {
981 for (j = i+1; j < sys_samples; j++) {
982 if (server->filter_delay[ord[j]] == 0)
983 continue;
984 if (server->filter_delay[ord[i]] == 0
985 || (server->filter_delay[ord[i]]
986 > server->filter_delay[ord[j]])) {
987 register int tmp;
988
989 tmp = ord[i];
990 ord[i] = ord[j];
991 ord[j] = tmp;
992 }
993 }
994 }
995
996 /*
997 * Now compute the dispersion, and assign values to delay and
998 * offset. If there are no samples in the register, delay and
999 * offset go to zero and dispersion is set to the maximum.
1000 */
1001 if (server->filter_delay[ord[0]] == 0) {
1002 server->delay = 0;
1003 L_CLR(&server->offset);
1004 server->soffset = 0;
1005 server->dispersion = PEER_MAXDISP;
1006 } else {
1007 register s_fp d;
1008
1009 server->delay = server->filter_delay[ord[0]];
1010 server->offset = server->filter_offset[ord[0]];
1011 server->soffset = LFPTOFP(&server->offset);
1012 server->dispersion = 0;
1013 for (i = 1; i < sys_samples; i++) {
1014 if (server->filter_delay[ord[i]] == 0)
1015 d = PEER_MAXDISP;
1016 else {
1017 d = server->filter_soffset[ord[i]]
1018 - server->filter_soffset[ord[0]];
1019 if (d < 0)
1020 d = -d;
1021 if (d > PEER_MAXDISP)
1022 d = PEER_MAXDISP;
1023 }
1024 /*
1025 * XXX This *knows* PEER_FILTER is 1/2
1026 */
1027 server->dispersion += (u_fp)(d) >> i;
1028 }
1029 }
1030 /*
1031 * We're done
1032 */
1033 }
1034
1035
1036 /*
1037 * clock_select - select the pick-of-the-litter clock from the samples
1038 * we've got.
1039 */
1040 static struct server *
clock_select(void)1041 clock_select(void)
1042 {
1043 struct server *server;
1044 u_int nlist;
1045 s_fp d;
1046 u_int count;
1047 u_int i;
1048 u_int j;
1049 u_int k;
1050 int n;
1051 s_fp local_threshold;
1052 struct server *server_list[NTP_MAXCLOCK];
1053 u_fp server_badness[NTP_MAXCLOCK];
1054 struct server *sys_server;
1055
1056 /*
1057 * This first chunk of code is supposed to go through all
1058 * servers we know about to find the NTP_MAXLIST servers which
1059 * are most likely to succeed. We run through the list
1060 * doing the sanity checks and trying to insert anyone who
1061 * looks okay. We are at all times aware that we should
1062 * only keep samples from the top two strata and we only need
1063 * NTP_MAXLIST of them.
1064 */
1065 nlist = 0; /* none yet */
1066 for (server = sys_servers; server != NULL; server = server->next_server) {
1067 if (server->stratum == 0) {
1068 if (debug)
1069 printf("%s: Server dropped: no data\n", ntoa(&server->srcadr));
1070 continue; /* no data */
1071 }
1072 if (server->stratum > NTP_INFIN) {
1073 if (debug)
1074 printf("%s: Server dropped: strata too high\n", ntoa(&server->srcadr));
1075 continue; /* stratum no good */
1076 }
1077 if (server->delay > NTP_MAXWGT) {
1078 if (debug)
1079 printf("%s: Server dropped: server too far away\n",
1080 ntoa(&server->srcadr));
1081 continue; /* too far away */
1082 }
1083 if (server->leap == LEAP_NOTINSYNC) {
1084 if (debug)
1085 printf("%s: Server dropped: leap not in sync\n", ntoa(&server->srcadr));
1086 continue; /* he's in trouble */
1087 }
1088 if (!L_ISHIS(&server->org, &server->reftime)) {
1089 if (debug)
1090 printf("%s: Server dropped: server is very broken\n",
1091 ntoa(&server->srcadr));
1092 continue; /* very broken host */
1093 }
1094 if ((server->org.l_ui - server->reftime.l_ui)
1095 >= NTP_MAXAGE) {
1096 if (debug)
1097 printf("%s: Server dropped: server has gone too long without sync\n",
1098 ntoa(&server->srcadr));
1099 continue; /* too long without sync */
1100 }
1101 if (server->trust != 0) {
1102 if (debug)
1103 printf("%s: Server dropped: Server is untrusted\n",
1104 ntoa(&server->srcadr));
1105 continue;
1106 }
1107
1108 /*
1109 * This one seems sane. Find where he belongs
1110 * on the list.
1111 */
1112 d = server->dispersion + server->dispersion;
1113 for (i = 0; i < nlist; i++)
1114 if (server->stratum <= server_list[i]->stratum)
1115 break;
1116 for ( ; i < nlist; i++) {
1117 if (server->stratum < server_list[i]->stratum)
1118 break;
1119 if (d < (s_fp) server_badness[i])
1120 break;
1121 }
1122
1123 /*
1124 * If i points past the end of the list, this
1125 * guy is a loser, else stick him in.
1126 */
1127 if (i >= NTP_MAXLIST)
1128 continue;
1129 for (j = nlist; j > i; j--)
1130 if (j < NTP_MAXLIST) {
1131 server_list[j] = server_list[j-1];
1132 server_badness[j]
1133 = server_badness[j-1];
1134 }
1135
1136 server_list[i] = server;
1137 server_badness[i] = d;
1138 if (nlist < NTP_MAXLIST)
1139 nlist++;
1140 }
1141
1142 /*
1143 * Got the five-or-less best. Cut the list where the number of
1144 * strata exceeds two.
1145 */
1146 count = 0;
1147 for (i = 1; i < nlist; i++)
1148 if (server_list[i]->stratum > server_list[i-1]->stratum) {
1149 count++;
1150 if (2 == count) {
1151 nlist = i;
1152 break;
1153 }
1154 }
1155
1156 /*
1157 * Whew! What we should have by now is 0 to 5 candidates for
1158 * the job of syncing us. If we have none, we're out of luck.
1159 * If we have one, he's a winner. If we have more, do falseticker
1160 * detection.
1161 */
1162
1163 if (0 == nlist)
1164 sys_server = NULL;
1165 else if (1 == nlist) {
1166 sys_server = server_list[0];
1167 } else {
1168 /*
1169 * Re-sort by stratum, bdelay estimate quality and
1170 * server.delay.
1171 */
1172 for (i = 0; i < nlist-1; i++)
1173 for (j = i+1; j < nlist; j++) {
1174 if (server_list[i]->stratum <
1175 server_list[j]->stratum)
1176 /* already sorted by stratum */
1177 break;
1178 if (server_list[i]->delay <
1179 server_list[j]->delay)
1180 continue;
1181 server = server_list[i];
1182 server_list[i] = server_list[j];
1183 server_list[j] = server;
1184 }
1185
1186 /*
1187 * Calculate the fixed part of the dispersion limit
1188 */
1189 local_threshold = (FP_SECOND >> (-(int)NTPDATE_PRECISION))
1190 + NTP_MAXSKW;
1191
1192 /*
1193 * Now drop samples until we're down to one.
1194 */
1195 while (nlist > 1) {
1196 for (k = 0; k < nlist; k++) {
1197 server_badness[k] = 0;
1198 for (j = 0; j < nlist; j++) {
1199 if (j == k) /* with self? */
1200 continue;
1201 d = server_list[j]->soffset -
1202 server_list[k]->soffset;
1203 if (d < 0) /* abs value */
1204 d = -d;
1205 /*
1206 * XXX This code *knows* that
1207 * NTP_SELECT is 3/4
1208 */
1209 for (i = 0; i < j; i++)
1210 d = (d>>1) + (d>>2);
1211 server_badness[k] += d;
1212 }
1213 }
1214
1215 /*
1216 * We now have an array of nlist badness
1217 * coefficients. Find the badest. Find
1218 * the minimum precision while we're at
1219 * it.
1220 */
1221 i = 0;
1222 n = server_list[0]->precision;;
1223 for (j = 1; j < nlist; j++) {
1224 if (server_badness[j] >= server_badness[i])
1225 i = j;
1226 if (n > server_list[j]->precision)
1227 n = server_list[j]->precision;
1228 }
1229
1230 /*
1231 * i is the index of the server with the worst
1232 * dispersion. If his dispersion is less than
1233 * the threshold, stop now, else delete him and
1234 * continue around again.
1235 */
1236 if ( (s_fp) server_badness[i] < (local_threshold
1237 + (FP_SECOND >> (-n))))
1238 break;
1239 for (j = i + 1; j < nlist; j++)
1240 server_list[j-1] = server_list[j];
1241 nlist--;
1242 }
1243
1244 /*
1245 * What remains is a list of less than 5 servers. Take
1246 * the best.
1247 */
1248 sys_server = server_list[0];
1249 }
1250
1251 /*
1252 * That's it. Return our server.
1253 */
1254 return sys_server;
1255 }
1256
1257
1258 /*
1259 * clock_adjust - process what we've received, and adjust the time
1260 * if we got anything decent.
1261 */
1262 static int
clock_adjust(void)1263 clock_adjust(void)
1264 {
1265 register struct server *sp, *server;
1266 int dostep;
1267
1268 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1269 clock_filter(sp);
1270 server = clock_select();
1271
1272 if (debug || simple_query) {
1273 if (debug)
1274 printf ("\n");
1275 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1276 print_server(sp, stdout);
1277 }
1278
1279 if (server == 0) {
1280 msyslog(LOG_ERR,
1281 "no server suitable for synchronization found");
1282 return(1);
1283 }
1284
1285 if (always_step) {
1286 dostep = 1;
1287 } else if (never_step) {
1288 dostep = 0;
1289 } else {
1290 /* [Bug 3023] get absolute difference, avoiding signed
1291 * integer overflow like hell.
1292 */
1293 u_fp absoffset;
1294 if (server->soffset < 0)
1295 absoffset = 1u + (u_fp)(-(server->soffset + 1));
1296 else
1297 absoffset = (u_fp)server->soffset;
1298 dostep = (absoffset >= NTPDATE_THRESHOLD);
1299 }
1300
1301 if (dostep) {
1302 if (simple_query || l_step_systime(&server->offset)){
1303 msyslog(LOG_NOTICE, "step time server %s offset %s sec",
1304 stoa(&server->srcadr),
1305 lfptoa(&server->offset, 6));
1306 }
1307 } else {
1308 if (simple_query || l_adj_systime(&server->offset)) {
1309 msyslog(LOG_NOTICE, "adjust time server %s offset %s sec",
1310 stoa(&server->srcadr),
1311 lfptoa(&server->offset, 6));
1312 }
1313 }
1314 return(0);
1315 }
1316
1317
1318 /*
1319 * is_unreachable - check to see if we have a route to given destination
1320 * (non-blocking).
1321 */
1322 static int
is_reachable(sockaddr_u * dst)1323 is_reachable (sockaddr_u *dst)
1324 {
1325 SOCKET sockfd;
1326
1327 sockfd = socket(AF(dst), SOCK_DGRAM, 0);
1328 if (sockfd == -1) {
1329 return 0;
1330 }
1331
1332 if (connect(sockfd, &dst->sa, SOCKLEN(dst))) {
1333 closesocket(sockfd);
1334 return 0;
1335 }
1336 closesocket(sockfd);
1337 return 1;
1338 }
1339
1340
1341
1342 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1343 /*
1344 * addserver - determine a server's address and allocate a new structure
1345 * for it.
1346 */
1347 static void
addserver(char * serv)1348 addserver(
1349 char *serv
1350 )
1351 {
1352 register struct server *server;
1353 /* Address infos structure to store result of getaddrinfo */
1354 struct addrinfo *addrResult, *ptr;
1355 /* Address infos structure to store hints for getaddrinfo */
1356 struct addrinfo hints;
1357 /* Error variable for getaddrinfo */
1358 int error;
1359 /* Service name */
1360 char service[5];
1361 sockaddr_u addr;
1362
1363 strlcpy(service, "ntp", sizeof(service));
1364
1365 /* Get host address. Looking for UDP datagram connection. */
1366 ZERO(hints);
1367 hints.ai_family = ai_fam_templ;
1368 hints.ai_socktype = SOCK_DGRAM;
1369
1370 #ifdef DEBUG
1371 if (debug)
1372 printf("Looking for host %s and service %s\n", serv, service);
1373 #endif
1374
1375 error = getaddrinfo(serv, service, &hints, &addrResult);
1376 if (error == EAI_SERVICE) {
1377 strlcpy(service, "123", sizeof(service));
1378 error = getaddrinfo(serv, service, &hints, &addrResult);
1379 }
1380 if (error != 0) {
1381 /* Conduct more refined error analysis */
1382 if (error == EAI_FAIL || error == EAI_AGAIN){
1383 /* Name server is unusable. Exit after failing on the
1384 first server, in order to shorten the timeout caused
1385 by waiting for resolution of several servers */
1386 fprintf(stderr, "Exiting, name server cannot be used: %s (%d)",
1387 gai_strerror(error), error);
1388 msyslog(LOG_ERR, "name server cannot be used: %s (%d)",
1389 gai_strerror(error), error);
1390 exit(1);
1391 }
1392 fprintf(stderr, "Error resolving %s: %s (%d)\n", serv,
1393 gai_strerror(error), error);
1394 msyslog(LOG_ERR, "Can't find host %s: %s (%d)", serv,
1395 gai_strerror(error), error);
1396 return;
1397 }
1398 #ifdef DEBUG
1399 if (debug) {
1400 ZERO(addr);
1401 INSIST(addrResult->ai_addrlen <= sizeof(addr));
1402 memcpy(&addr, addrResult->ai_addr, addrResult->ai_addrlen);
1403 fprintf(stderr, "host found : %s\n", stohost(&addr));
1404 }
1405 #endif
1406
1407 /* We must get all returned server in case the first one fails */
1408 for (ptr = addrResult; ptr != NULL; ptr = ptr->ai_next) {
1409 ZERO(addr);
1410 INSIST(ptr->ai_addrlen <= sizeof(addr));
1411 memcpy(&addr, ptr->ai_addr, ptr->ai_addrlen);
1412 if (is_reachable(&addr)) {
1413 server = emalloc_zero(sizeof(*server));
1414 memcpy(&server->srcadr, ptr->ai_addr, ptr->ai_addrlen);
1415 server->event_time = ++sys_numservers;
1416 if (sys_servers == NULL)
1417 sys_servers = server;
1418 else {
1419 struct server *sp;
1420
1421 for (sp = sys_servers; sp->next_server != NULL;
1422 sp = sp->next_server)
1423 /* empty */;
1424 sp->next_server = server;
1425 }
1426 }
1427 }
1428
1429 freeaddrinfo(addrResult);
1430 }
1431
1432
1433 /*
1434 * findserver - find a server in the list given its address
1435 * ***(For now it isn't totally AF-Independant, to check later..)
1436 */
1437 static struct server *
findserver(sockaddr_u * addr)1438 findserver(
1439 sockaddr_u *addr
1440 )
1441 {
1442 struct server *server;
1443 struct server *mc_server;
1444
1445 mc_server = NULL;
1446 if (SRCPORT(addr) != NTP_PORT)
1447 return 0;
1448
1449 for (server = sys_servers; server != NULL;
1450 server = server->next_server) {
1451 if (SOCK_EQ(addr, &server->srcadr))
1452 return server;
1453
1454 if (AF(addr) == AF(&server->srcadr)) {
1455 if (IS_MCAST(&server->srcadr))
1456 mc_server = server;
1457 }
1458 }
1459
1460 if (mc_server != NULL) {
1461
1462 struct server *sp;
1463
1464 if (mc_server->event_time != 0) {
1465 mc_server->event_time = 0;
1466 complete_servers++;
1467 }
1468
1469 server = emalloc_zero(sizeof(*server));
1470
1471 server->srcadr = *addr;
1472
1473 server->event_time = ++sys_numservers;
1474
1475 for (sp = sys_servers; sp->next_server != NULL;
1476 sp = sp->next_server)
1477 /* empty */;
1478 sp->next_server = server;
1479 transmit(server);
1480 }
1481 return NULL;
1482 }
1483
1484
1485 /*
1486 * timer - process a timer interrupt
1487 */
1488 void
timer(void)1489 timer(void)
1490 {
1491 struct server *server;
1492
1493 /*
1494 * Bump the current idea of the time
1495 */
1496 current_time++;
1497
1498 /*
1499 * Search through the server list looking for guys
1500 * who's event timers have expired. Give these to
1501 * the transmit routine.
1502 */
1503 for (server = sys_servers; server != NULL;
1504 server = server->next_server) {
1505 if (server->event_time != 0
1506 && server->event_time <= current_time)
1507 transmit(server);
1508 }
1509 }
1510
1511
1512 /*
1513 * The code duplication in the following subroutine sucks, but
1514 * we need to appease ansi2knr.
1515 */
1516
1517 #ifndef SYS_WINNT
1518 /*
1519 * alarming - record the occurance of an alarm interrupt
1520 */
1521 static RETSIGTYPE
alarming(int sig)1522 alarming(
1523 int sig
1524 )
1525 {
1526 alarm_flag++;
1527 }
1528 #else /* SYS_WINNT follows */
1529 void CALLBACK
alarming(UINT uTimerID,UINT uMsg,DWORD dwUser,DWORD dw1,DWORD dw2)1530 alarming(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1531 {
1532 UNUSED_ARG(uTimerID); UNUSED_ARG(uMsg); UNUSED_ARG(dwUser);
1533 UNUSED_ARG(dw1); UNUSED_ARG(dw2);
1534
1535 alarm_flag++;
1536 }
1537
1538 static void
callTimeEndPeriod(void)1539 callTimeEndPeriod(void)
1540 {
1541 timeEndPeriod( wTimerRes );
1542 wTimerRes = 0;
1543 }
1544 #endif /* SYS_WINNT */
1545
1546
1547 /*
1548 * init_alarm - set up the timer interrupt
1549 */
1550 static void
init_alarm(void)1551 init_alarm(void)
1552 {
1553 #ifndef SYS_WINNT
1554 # ifdef HAVE_TIMER_CREATE
1555 struct itimerspec its;
1556 # else
1557 struct itimerval itv;
1558 # endif
1559 #else /* SYS_WINNT follows */
1560 TIMECAPS tc;
1561 UINT wTimerID;
1562 HANDLE hToken;
1563 TOKEN_PRIVILEGES tkp;
1564 DWORD dwUser = 0;
1565 #endif /* SYS_WINNT */
1566
1567 alarm_flag = 0;
1568
1569 #ifndef SYS_WINNT
1570 # ifdef HAVE_TIMER_CREATE
1571 alarm_flag = 0;
1572 /* this code was put in as setitimer() is non existant this us the
1573 * POSIX "equivalents" setup - casey
1574 */
1575 /* ntpdate_timerid is global - so we can kill timer later */
1576 if (timer_create (CLOCK_REALTIME, NULL, &ntpdate_timerid) ==
1577 # ifdef SYS_VXWORKS
1578 ERROR
1579 # else
1580 -1
1581 # endif
1582 )
1583 {
1584 fprintf (stderr, "init_alarm(): timer_create (...) FAILED\n");
1585 return;
1586 }
1587
1588 /* TIMER_HZ = (5)
1589 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1590 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1591 */
1592 signal_no_reset(SIGALRM, alarming);
1593 its.it_interval.tv_sec = 0;
1594 its.it_value.tv_sec = 0;
1595 its.it_interval.tv_nsec = 1000000000/TIMER_HZ;
1596 its.it_value.tv_nsec = 1000000000/(TIMER_HZ<<1);
1597 timer_settime(ntpdate_timerid, 0 /* !TIMER_ABSTIME */, &its, NULL);
1598 # else /* !HAVE_TIMER_CREATE follows */
1599 /*
1600 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1601 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1602 */
1603 signal_no_reset(SIGALRM, alarming);
1604 itv.it_interval.tv_sec = 0;
1605 itv.it_value.tv_sec = 0;
1606 itv.it_interval.tv_usec = 1000000/TIMER_HZ;
1607 itv.it_value.tv_usec = 1000000/(TIMER_HZ<<1);
1608
1609 setitimer(ITIMER_REAL, &itv, NULL);
1610 # endif /* !HAVE_TIMER_CREATE */
1611 #else /* SYS_WINNT follows */
1612 _tzset();
1613
1614 if (!simple_query && !debug) {
1615 /*
1616 * Get privileges needed for fiddling with the clock
1617 */
1618
1619 /* get the current process token handle */
1620 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1621 msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1622 exit(1);
1623 }
1624 /* get the LUID for system-time privilege. */
1625 LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1626 tkp.PrivilegeCount = 1; /* one privilege to set */
1627 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1628 /* get set-time privilege for this process. */
1629 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1630 /* cannot test return value of AdjustTokenPrivileges. */
1631 if (GetLastError() != ERROR_SUCCESS)
1632 msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1633 }
1634
1635 /*
1636 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1637 * Under Win/NT, expiry of timer interval leads to invocation
1638 * of a callback function (on a different thread) rather than
1639 * generating an alarm signal
1640 */
1641
1642 /* determine max and min resolution supported */
1643 if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
1644 msyslog(LOG_ERR, "timeGetDevCaps failed: %m");
1645 exit(1);
1646 }
1647 wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
1648 /* establish the minimum timer resolution that we'll use */
1649 timeBeginPeriod(wTimerRes);
1650 atexit(callTimeEndPeriod);
1651
1652 /* start the timer event */
1653 wTimerID = timeSetEvent(
1654 (UINT) (1000/TIMER_HZ), /* Delay */
1655 wTimerRes, /* Resolution */
1656 (LPTIMECALLBACK) alarming, /* Callback function */
1657 (DWORD) dwUser, /* User data */
1658 TIME_PERIODIC); /* Event type (periodic) */
1659 if (wTimerID == 0) {
1660 msyslog(LOG_ERR, "timeSetEvent failed: %m");
1661 exit(1);
1662 }
1663 #endif /* SYS_WINNT */
1664 }
1665
1666
1667
1668
1669 /*
1670 * We do asynchronous input using the SIGIO facility. A number of
1671 * recvbuf buffers are preallocated for input. In the signal
1672 * handler we poll to see if the socket is ready and read the
1673 * packets from it into the recvbuf's along with a time stamp and
1674 * an indication of the source host and the interface it was received
1675 * through. This allows us to get as accurate receive time stamps
1676 * as possible independent of other processing going on.
1677 *
1678 * We allocate a number of recvbufs equal to the number of servers
1679 * plus 2. This should be plenty.
1680 */
1681
1682
1683 /*
1684 * init_io - initialize I/O data and open socket
1685 */
1686 static void
init_io(void)1687 init_io(void)
1688 {
1689 struct addrinfo *res, *ressave;
1690 struct addrinfo hints;
1691 sockaddr_u addr;
1692 char service[5];
1693 int rc;
1694 int optval = 1;
1695 int check_ntp_port_in_use = !debug && !simple_query && !unpriv_port;
1696
1697 /*
1698 * Init buffer free list and stat counters
1699 */
1700 init_recvbuff(sys_numservers + 2);
1701
1702 /*
1703 * Open the socket
1704 */
1705
1706 strlcpy(service, "ntp", sizeof(service));
1707
1708 /*
1709 * Init hints addrinfo structure
1710 */
1711 ZERO(hints);
1712 hints.ai_family = ai_fam_templ;
1713 hints.ai_flags = AI_PASSIVE;
1714 hints.ai_socktype = SOCK_DGRAM;
1715
1716 rc = getaddrinfo(NULL, service, &hints, &res);
1717 if (rc == EAI_SERVICE) {
1718 strlcpy(service, "123", sizeof(service));
1719 rc = getaddrinfo(NULL, service, &hints, &res);
1720 }
1721 if (rc != 0) {
1722 msyslog(LOG_ERR, "getaddrinfo() failed: %m");
1723 exit(1);
1724 /*NOTREACHED*/
1725 }
1726
1727 #ifdef SYS_WINNT
1728 if (check_ntp_port_in_use && ntp_port_inuse(AF_INET, NTP_PORT)){
1729 msyslog(LOG_ERR, "the NTP socket is in use, exiting: %m");
1730 exit(1);
1731 }
1732 #endif
1733
1734 /* Remember the address of the addrinfo structure chain */
1735 ressave = res;
1736
1737 /*
1738 * For each structure returned, open and bind socket
1739 */
1740 for(nbsock = 0; (nbsock < MAX_AF) && res ; res = res->ai_next) {
1741 /* create a datagram (UDP) socket */
1742 fd[nbsock] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1743 if (fd[nbsock] == SOCKET_ERROR) {
1744 #ifndef SYS_WINNT
1745 if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT ||
1746 errno == EPFNOSUPPORT)
1747 #else
1748 int err = WSAGetLastError();
1749 if (err == WSAEPROTONOSUPPORT || err == WSAEAFNOSUPPORT ||
1750 err == WSAEPFNOSUPPORT)
1751 #endif
1752 continue;
1753 msyslog(LOG_ERR, "socket() failed: %m");
1754 exit(1);
1755 /*NOTREACHED*/
1756 }
1757 /* set socket to reuse address */
1758 if (setsockopt(fd[nbsock], SOL_SOCKET, SO_REUSEADDR, (void*) &optval, sizeof(optval)) < 0) {
1759 msyslog(LOG_ERR, "setsockopt() SO_REUSEADDR failed: %m");
1760 exit(1);
1761 /*NOTREACHED*/
1762 }
1763 #ifdef IPV6_V6ONLY
1764 /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1765 if (res->ai_family == AF_INET6)
1766 if (setsockopt(fd[nbsock], IPPROTO_IPV6, IPV6_V6ONLY, (void*) &optval, sizeof(optval)) < 0) {
1767 msyslog(LOG_ERR, "setsockopt() IPV6_V6ONLY failed: %m");
1768 }
1769 #endif
1770
1771 /* Remember the socket family in fd_family structure */
1772 fd_family[nbsock] = res->ai_family;
1773
1774 /*
1775 * bind the socket to the NTP port
1776 */
1777 if (check_ntp_port_in_use) {
1778 ZERO(addr);
1779 INSIST(res->ai_addrlen <= sizeof(addr));
1780 memcpy(&addr, res->ai_addr, res->ai_addrlen);
1781 rc = bind(fd[nbsock], &addr.sa, SOCKLEN(&addr));
1782 if (rc < 0) {
1783 if (EADDRINUSE == socket_errno())
1784 msyslog(LOG_ERR, "the NTP socket is in use, exiting");
1785 else
1786 msyslog(LOG_ERR, "bind() fails: %m");
1787 exit(1);
1788 }
1789 }
1790
1791 #ifdef HAVE_POLL_H
1792 fdmask[nbsock].fd = fd[nbsock];
1793 fdmask[nbsock].events = POLLIN;
1794 #else
1795 FD_SET(fd[nbsock], &fdmask);
1796 if (maxfd < fd[nbsock]+1) {
1797 maxfd = fd[nbsock]+1;
1798 }
1799 #endif
1800
1801 /*
1802 * set non-blocking,
1803 */
1804 #ifndef SYS_WINNT
1805 # ifdef SYS_VXWORKS
1806 {
1807 int on = TRUE;
1808
1809 if (ioctl(fd[nbsock],FIONBIO, &on) == ERROR) {
1810 msyslog(LOG_ERR, "ioctl(FIONBIO) fails: %m");
1811 exit(1);
1812 }
1813 }
1814 # else /* not SYS_VXWORKS */
1815 # if defined(O_NONBLOCK)
1816 if (fcntl(fd[nbsock], F_SETFL, O_NONBLOCK) < 0) {
1817 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1818 exit(1);
1819 /*NOTREACHED*/
1820 }
1821 # else /* not O_NONBLOCK */
1822 # if defined(FNDELAY)
1823 if (fcntl(fd[nbsock], F_SETFL, FNDELAY) < 0) {
1824 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1825 exit(1);
1826 /*NOTREACHED*/
1827 }
1828 # else /* FNDELAY */
1829 # include "Bletch: Need non blocking I/O"
1830 # endif /* FNDELAY */
1831 # endif /* not O_NONBLOCK */
1832 # endif /* SYS_VXWORKS */
1833 #else /* SYS_WINNT */
1834 if (ioctlsocket(fd[nbsock], FIONBIO, (u_long *) &on) == SOCKET_ERROR) {
1835 msyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m");
1836 exit(1);
1837 }
1838 #endif /* SYS_WINNT */
1839 nbsock++;
1840 }
1841 freeaddrinfo(ressave);
1842 }
1843
1844 /*
1845 * sendpkt - send a packet to the specified destination
1846 */
1847 static void
sendpkt(sockaddr_u * dest,struct pkt * pkt,int len)1848 sendpkt(
1849 sockaddr_u *dest,
1850 struct pkt *pkt,
1851 int len
1852 )
1853 {
1854 int i;
1855 int cc;
1856 SOCKET sock = INVALID_SOCKET;
1857
1858 #ifdef SYS_WINNT
1859 DWORD err;
1860 #endif /* SYS_WINNT */
1861
1862 /* Find a local family compatible socket to send ntp packet to ntp server */
1863 for(i = 0; (i < MAX_AF); i++) {
1864 if(AF(dest) == fd_family[i]) {
1865 sock = fd[i];
1866 break;
1867 }
1868 }
1869
1870 if (INVALID_SOCKET == sock) {
1871 msyslog(LOG_ERR, "cannot find family compatible socket to send ntp packet");
1872 exit(1);
1873 /*NOTREACHED*/
1874 }
1875
1876 cc = sendto(sock, (char *)pkt, len, 0, (struct sockaddr *)dest,
1877 SOCKLEN(dest));
1878
1879 if (SOCKET_ERROR == cc) {
1880 #ifndef SYS_WINNT
1881 if (errno != EWOULDBLOCK && errno != ENOBUFS)
1882 #else
1883 err = WSAGetLastError();
1884 if (err != WSAEWOULDBLOCK && err != WSAENOBUFS)
1885 #endif /* SYS_WINNT */
1886 msyslog(LOG_ERR, "sendto(%s): %m", stohost(dest));
1887 }
1888 }
1889
1890
1891 /*
1892 * input_handler - receive packets asynchronously
1893 */
1894 void
input_handler(void)1895 input_handler(void)
1896 {
1897 register int n;
1898 register struct recvbuf *rb;
1899 struct sock_timeval tvzero;
1900 GETSOCKNAME_SOCKLEN_TYPE fromlen;
1901 l_fp ts;
1902 int i;
1903 #ifdef HAVE_POLL_H
1904 struct pollfd fds[MAX_AF];
1905 #else
1906 fd_set fds;
1907 #endif
1908 SOCKET fdc = 0;
1909
1910 /*
1911 * Do a poll to see if we have data
1912 */
1913 for (;;) {
1914 tvzero.tv_sec = tvzero.tv_usec = 0;
1915 #ifdef HAVE_POLL_H
1916 memcpy(fds, fdmask, sizeof(fdmask));
1917 n = poll(fds, (unsigned int)nbsock, tvzero.tv_sec * 1000);
1918
1919 /*
1920 * Determine which socket received data
1921 */
1922
1923 for(i=0; i < nbsock; i++) {
1924 if(fds[i].revents & POLLIN) {
1925 fdc = fd[i];
1926 break;
1927 }
1928 }
1929
1930 #else
1931 fds = fdmask;
1932 n = select(maxfd, &fds, NULL, NULL, &tvzero);
1933
1934 /*
1935 * Determine which socket received data
1936 */
1937
1938 for(i=0; i < nbsock; i++) {
1939 if(FD_ISSET(fd[i], &fds)) {
1940 fdc = fd[i];
1941 break;
1942 }
1943 }
1944
1945 #endif
1946
1947 /*
1948 * If nothing to do, just return. If an error occurred,
1949 * complain and return. If we've got some, freeze a
1950 * timestamp.
1951 */
1952 if (n == 0)
1953 return;
1954 else if (n == -1) {
1955 if (errno != EINTR)
1956 msyslog(LOG_ERR,
1957 #ifdef HAVE_POLL_H
1958 "poll() error: %m"
1959 #else
1960 "select() error: %m"
1961 #endif
1962 );
1963 return;
1964 }
1965 get_systime(&ts);
1966
1967 /*
1968 * Get a buffer and read the frame. If we
1969 * haven't got a buffer, or this is received
1970 * on the wild card socket, just dump the packet.
1971 */
1972 if (initializing || free_recvbuffs() == 0) {
1973 char buf[100];
1974
1975
1976 #ifndef SYS_WINNT
1977 (void) read(fdc, buf, sizeof buf);
1978 #else
1979 /* NT's _read does not operate on nonblocking sockets
1980 * either recvfrom or ReadFile() has to be used here.
1981 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1982 * just to be different use recvfrom() here
1983 */
1984 recvfrom(fdc, buf, sizeof(buf), 0, (struct sockaddr *)0, NULL);
1985 #endif /* SYS_WINNT */
1986 continue;
1987 }
1988
1989 rb = get_free_recv_buffer(TRUE);
1990
1991 fromlen = sizeof(rb->recv_srcadr);
1992 rb->recv_length = recvfrom(fdc, (char *)&rb->recv_pkt,
1993 sizeof(rb->recv_pkt), 0,
1994 (struct sockaddr *)&rb->recv_srcadr, &fromlen);
1995 if (rb->recv_length == -1) {
1996 freerecvbuf(rb);
1997 continue;
1998 }
1999
2000 /*
2001 * Got one. Mark how and when it got here,
2002 * put it on the full list.
2003 */
2004 rb->recv_time = ts;
2005 add_full_recv_buffer(rb);
2006 }
2007 }
2008
2009
2010 /*
2011 * adj_systime - do a big long slew of the system time
2012 */
2013 static int
l_adj_systime(l_fp * ts)2014 l_adj_systime(
2015 l_fp *ts
2016 )
2017 {
2018 struct timeval adjtv;
2019 int isneg = 0;
2020 l_fp offset;
2021 #ifndef STEP_SLEW
2022 l_fp overshoot;
2023 #endif
2024
2025 /*
2026 * Take the absolute value of the offset
2027 */
2028 offset = *ts;
2029 if (L_ISNEG(&offset)) {
2030 isneg = 1;
2031 L_NEG(&offset);
2032 }
2033
2034 #ifndef STEP_SLEW
2035 /*
2036 * Calculate the overshoot. XXX N.B. This code *knows*
2037 * ADJ_OVERSHOOT is 1/2.
2038 */
2039 overshoot = offset;
2040 L_RSHIFTU(&overshoot);
2041 if (overshoot.l_ui != 0 || (overshoot.l_uf > ADJ_MAXOVERSHOOT)) {
2042 overshoot.l_ui = 0;
2043 overshoot.l_uf = ADJ_MAXOVERSHOOT;
2044 }
2045 L_ADD(&offset, &overshoot);
2046 #endif
2047 TSTOTV(&offset, &adjtv);
2048
2049 if (isneg) {
2050 adjtv.tv_sec = -adjtv.tv_sec;
2051 adjtv.tv_usec = -adjtv.tv_usec;
2052 }
2053
2054 if (!debug && (adjtv.tv_usec != 0)) {
2055 /* A time correction needs to be applied. */
2056 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
2057 /* Slew the time on systems that support this. */
2058 struct timeval oadjtv;
2059 if (adjtime(&adjtv, &oadjtv) < 0) {
2060 msyslog(LOG_ERR, "Can't adjust the time of day: %m");
2061 exit(1);
2062 }
2063 #else /* SYS_WINNT or SYS_CYGWIN32 is defined */
2064 /*
2065 * The NT SetSystemTimeAdjustment() call achieves slewing by
2066 * changing the clock frequency. This means that we cannot specify
2067 * it to slew the clock by a definite amount and then stop like
2068 * the Unix adjtime() routine. We can technically adjust the clock
2069 * frequency, have ntpdate sleep for a while, and then wake
2070 * up and reset the clock frequency, but this might cause some
2071 * grief if the user attempts to run ntpd immediately after
2072 * ntpdate and the socket is in use.
2073 */
2074 printf("\nSlewing the system time is not supported on Windows. Use the -b option to step the time.\n");
2075 #endif /* defined SYS_WINNT || defined SYS_CYGWIN32 */
2076 }
2077 return 1;
2078 }
2079
2080
2081 /*
2082 * This fuction is not the same as lib/systime step_systime!!!
2083 */
2084 static int
l_step_systime(l_fp * ts)2085 l_step_systime(
2086 l_fp *ts
2087 )
2088 {
2089 double dtemp;
2090
2091 #ifdef SLEWALWAYS
2092 #ifdef STEP_SLEW
2093 l_fp ftmp;
2094 int isneg;
2095 int n;
2096
2097 if (debug)
2098 return 1;
2099
2100 /*
2101 * Take the absolute value of the offset
2102 */
2103 ftmp = *ts;
2104
2105 if (L_ISNEG(&ftmp)) {
2106 L_NEG(&ftmp);
2107 isneg = 1;
2108 } else
2109 isneg = 0;
2110
2111 if (ftmp.l_ui >= 3) { /* Step it and slew - we might win */
2112 LFPTOD(ts, dtemp);
2113 n = step_systime(dtemp);
2114 if (n == 0)
2115 return 0;
2116 if (isneg) /* WTF! */
2117 ts->l_ui = ~0;
2118 else
2119 ts->l_ui = ~0;
2120 }
2121 /*
2122 * Just add adjustment into the current offset. The update
2123 * routine will take care of bringing the system clock into
2124 * line.
2125 */
2126 #endif
2127 if (debug)
2128 return 1;
2129 #ifdef FORCE_NTPDATE_STEP
2130 LFPTOD(ts, dtemp);
2131 return step_systime(dtemp);
2132 #else
2133 l_adj_systime(ts);
2134 return 1;
2135 #endif
2136 #else /* SLEWALWAYS */
2137 if (debug)
2138 return 1;
2139 LFPTOD(ts, dtemp);
2140 return step_systime(dtemp);
2141 #endif /* SLEWALWAYS */
2142 }
2143
2144
2145 /* XXX ELIMINATE print_server similar in ntptrace.c, ntpdate.c */
2146 /*
2147 * print_server - print detail information for a server
2148 */
2149 static void
print_server(register struct server * pp,FILE * fp)2150 print_server(
2151 register struct server *pp,
2152 FILE *fp
2153 )
2154 {
2155 register int i;
2156 char junk[5];
2157 const char *str;
2158
2159 if (pp->stratum == 0) /* Nothing received => nothing to print */
2160 return;
2161
2162 if (!debug) {
2163 (void) fprintf(fp, "server %s, stratum %d, offset %s, delay %s\n",
2164 stoa(&pp->srcadr), pp->stratum,
2165 lfptoa(&pp->offset, 6), fptoa((s_fp)pp->delay, 5));
2166 return;
2167 }
2168
2169 (void) fprintf(fp, "server %s, port %d\n",
2170 stoa(&pp->srcadr), ntohs(((struct sockaddr_in*)&(pp->srcadr))->sin_port));
2171
2172 (void) fprintf(fp, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2173 pp->stratum, pp->precision,
2174 pp->leap & 0x2 ? '1' : '0',
2175 pp->leap & 0x1 ? '1' : '0',
2176 pp->trust);
2177
2178 if (REFID_ISTEXT(pp->stratum)) {
2179 str = (char *) &pp->refid;
2180 for (i=0; i<4 && str[i]; i++) {
2181 junk[i] = (isprint(str[i]) ? str[i] : '.');
2182 }
2183 junk[i] = 0; // force terminating 0
2184 str = junk;
2185 } else {
2186 str = numtoa(pp->refid);
2187 }
2188 (void) fprintf(fp,
2189 "refid [%s], root delay %s, root dispersion %s\n",
2190 str, fptoa((s_fp)pp->rootdelay, 6),
2191 ufptoa(pp->rootdisp, 6));
2192
2193 if (pp->xmtcnt != pp->filter_nextpt)
2194 (void) fprintf(fp, "transmitted %d, in filter %d\n",
2195 pp->xmtcnt, pp->filter_nextpt);
2196
2197 (void) fprintf(fp, "reference time: %s\n",
2198 prettydate(&pp->reftime));
2199 (void) fprintf(fp, "originate timestamp: %s\n",
2200 prettydate(&pp->org));
2201 (void) fprintf(fp, "transmit timestamp: %s\n",
2202 prettydate(&pp->xmt));
2203
2204 if (sys_samples > 1) {
2205 (void) fprintf(fp, "filter delay: ");
2206 for (i = 0; i < NTP_SHIFT; i++) {
2207 if (i == (NTP_SHIFT>>1))
2208 (void) fprintf(fp, "\n ");
2209 (void) fprintf(fp, " %-10.10s",
2210 (i<sys_samples ? fptoa(pp->filter_delay[i], 5) : "----"));
2211 }
2212 (void) fprintf(fp, "\n");
2213
2214 (void) fprintf(fp, "filter offset:");
2215 for (i = 0; i < PEER_SHIFT; i++) {
2216 if (i == (PEER_SHIFT>>1))
2217 (void) fprintf(fp, "\n ");
2218 (void) fprintf(fp, " %-10.10s",
2219 (i<sys_samples ? lfptoa(&pp->filter_offset[i], 6): "----"));
2220 }
2221 (void) fprintf(fp, "\n");
2222 }
2223
2224 (void) fprintf(fp, "delay %s, dispersion %s, ",
2225 fptoa((s_fp)pp->delay, 5), ufptoa(pp->dispersion, 5));
2226
2227 (void) fprintf(fp, "offset %s\n\n",
2228 lfptoa(&pp->offset, 6));
2229 }
2230
2231
2232 #ifdef HAVE_NETINFO
2233 static ni_namelist *
getnetinfoservers(void)2234 getnetinfoservers(void)
2235 {
2236 ni_status status;
2237 void *domain;
2238 ni_id confdir;
2239 ni_namelist *namelist = emalloc(sizeof(ni_namelist));
2240
2241 /* Find a time server in NetInfo */
2242 if ((status = ni_open(NULL, ".", &domain)) != NI_OK) return NULL;
2243
2244 while (status = ni_pathsearch(domain, &confdir, NETINFO_CONFIG_DIR) == NI_NODIR) {
2245 void *next_domain;
2246 if (ni_open(domain, "..", &next_domain) != NI_OK) break;
2247 ni_free(domain);
2248 domain = next_domain;
2249 }
2250 if (status != NI_OK) return NULL;
2251
2252 NI_INIT(namelist);
2253 if (ni_lookupprop(domain, &confdir, "server", namelist) != NI_OK) {
2254 ni_namelist_free(namelist);
2255 free(namelist);
2256 return NULL;
2257 }
2258
2259 return(namelist);
2260 }
2261 #endif
2262
2263 #ifdef SYS_WINNT
ntp_port_inuse(int af,u_short port)2264 isc_boolean_t ntp_port_inuse(int af, u_short port)
2265 {
2266 /*
2267 * Check if NTP socket is already in use on this system
2268 * This is only for Windows Systems, as they tend not to fail on the real bind() below
2269 */
2270
2271 SOCKET checksocket;
2272 struct sockaddr_in checkservice;
2273 checksocket = socket(af, SOCK_DGRAM, 0);
2274 if (checksocket == INVALID_SOCKET) {
2275 return (ISC_TRUE);
2276 }
2277
2278 checkservice.sin_family = (short) AF_INET;
2279 checkservice.sin_addr.s_addr = INADDR_LOOPBACK;
2280 checkservice.sin_port = htons(port);
2281
2282 if (bind(checksocket, (struct sockaddr *)&checkservice,
2283 sizeof(checkservice)) == SOCKET_ERROR) {
2284 if ( WSAGetLastError() == WSAEADDRINUSE ){
2285 closesocket(checksocket);
2286 return (ISC_TRUE);
2287 }
2288 }
2289 closesocket(checksocket);
2290 return (ISC_FALSE);
2291 }
2292 #endif
2293