Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / ntp / ntpdate / ntpdate.c
blob9eedf1f93314d2a1a316dc2172ab761e06e5b662
1 /* $NetBSD: ntpdate.c,v 1.8 2007/06/24 16:55:14 kardel Exp $ */
3 /*
4 * ntpdate - set the time of day by polling one or more NTP servers
5 */
7 #ifdef HAVE_CONFIG_H
8 # include <config.h>
9 #endif
11 #ifdef HAVE_NETINFO
12 #include <netinfo/ni.h>
13 #endif
15 #include "ntp_machine.h"
16 #include "ntp_fp.h"
17 #include "ntp.h"
18 #include "ntp_io.h"
19 #include "ntp_unixtime.h"
20 #include "ntpdate.h"
21 #include "ntp_string.h"
22 #include "ntp_syslog.h"
23 #include "ntp_select.h"
24 #include "ntp_stdlib.h"
26 /* Don't include ISC's version of IPv6 variables and structures */
27 #define ISC_IPV6_H 1
28 #include "isc/net.h"
29 #include "isc/result.h"
30 #include "isc/sockaddr.h"
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
36 #include <stdio.h>
37 #include <signal.h>
38 #include <ctype.h>
39 #ifdef HAVE_POLL_H
40 # include <poll.h>
41 #endif
42 #ifndef SYS_WINNT
43 # ifdef HAVE_SYS_SIGNAL_H
44 # include <sys/signal.h>
45 # else
46 # include <signal.h>
47 # endif
48 # ifdef HAVE_SYS_IOCTL_H
49 # include <sys/ioctl.h>
50 # endif
51 #endif /* SYS_WINNT */
52 #ifdef HAVE_SYS_RESOURCE_H
53 # include <sys/resource.h>
54 #endif /* HAVE_SYS_RESOURCE_H */
56 #include <arpa/inet.h>
58 #ifdef SYS_VXWORKS
59 # include "ioLib.h"
60 # include "sockLib.h"
61 # include "timers.h"
63 /* select wants a zero structure ... */
64 struct timeval timeout = {0,0};
65 #elif defined(SYS_WINNT)
67 * Windows does not abort a select select call if SIGALRM goes off
68 * so a 200 ms timeout is needed
70 struct timeval timeout = {0,1000000/TIMER_HZ};
71 #else
72 struct timeval timeout = {60,0};
73 #endif
75 #ifdef HAVE_NETINFO
76 #include <netinfo/ni.h>
77 #endif
79 #include "recvbuff.h"
81 #ifdef SYS_WINNT
82 #define EPROTONOSUPPORT WSAEPROTONOSUPPORT
83 #define EAFNOSUPPORT WSAEAFNOSUPPORT
84 #define EPFNOSUPPORT WSAEPFNOSUPPORT
85 #define TARGET_RESOLUTION 1 /* Try for 1-millisecond accuracy
86 on Windows NT timers. */
87 #pragma comment(lib, "winmm")
88 isc_boolean_t ntp_port_inuse(int af, u_short port);
89 UINT wTimerRes;
90 #endif /* SYS_WINNT */
93 * Scheduling priority we run at
95 #ifndef SYS_VXWORKS
96 # define NTPDATE_PRIO (-12)
97 #else
98 # define NTPDATE_PRIO (100)
99 #endif
101 #if defined(HAVE_TIMER_SETTIME) || defined (HAVE_TIMER_CREATE)
102 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
103 static timer_t ntpdate_timerid;
104 #endif
107 * Compatibility stuff for Version 2
109 #define NTP_MAXSKW 0x28f /* 0.01 sec in fp format */
110 #define NTP_MINDIST 0x51f /* 0.02 sec in fp format */
111 #define PEER_MAXDISP (64*FP_SECOND) /* maximum dispersion (fp 64) */
112 #define NTP_INFIN 15 /* max stratum, infinity a la Bellman-Ford */
113 #define NTP_MAXWGT (8*FP_SECOND) /* maximum select weight 8 seconds */
114 #define NTP_MAXLIST 5 /* maximum select list size */
115 #define PEER_SHIFT 8 /* 8 suitable for crystal time base */
118 * for get_systime()
120 s_char sys_precision; /* local clock precision (log2 s) */
123 * Debugging flag
125 volatile int debug = 0;
128 * File descriptor masks etc. for call to select
131 int ai_fam_templ;
132 int nbsock; /* the number of sockets used */
133 SOCKET fd[MAX_AF];
134 int fd_family[MAX_AF]; /* to remember the socket family */
135 #ifdef HAVE_POLL_H
136 struct pollfd fdmask[MAX_AF];
137 #else
138 fd_set fdmask;
139 SOCKET maxfd;
140 #endif
141 int polltest = 0;
144 * Initializing flag. All async routines watch this and only do their
145 * thing when it is clear.
147 int initializing = 1;
150 * Alarm flag. Set when an alarm occurs
152 volatile int alarm_flag = 0;
155 * Simple query flag.
157 int simple_query = 0;
160 * Unprivileged port flag.
162 int unpriv_port = 0;
165 * Program name.
167 char *progname;
170 * Systemwide parameters and flags
172 int sys_samples = DEFSAMPLES; /* number of samples/server */
173 u_long sys_timeout = DEFTIMEOUT; /* timeout time, in TIMER_HZ units */
174 struct server *sys_servers; /* the server list */
175 int sys_numservers = 0; /* number of servers to poll */
176 int sys_authenticate = 0; /* true when authenticating */
177 u_int32 sys_authkey = 0; /* set to authentication key in use */
178 u_long sys_authdelay = 0; /* authentication delay */
179 int sys_version = NTP_VERSION; /* version to poll with */
182 * The current internal time
184 u_long current_time = 0;
187 * Counter for keeping track of completed servers
189 int complete_servers = 0;
192 * File of encryption keys
195 #ifndef KEYFILE
196 # ifndef SYS_WINNT
197 #define KEYFILE "/etc/ntp.keys"
198 # else
199 #define KEYFILE "%windir%\\ntp.keys"
200 # endif /* SYS_WINNT */
201 #endif /* KEYFILE */
203 #ifndef SYS_WINNT
204 const char *key_file = KEYFILE;
205 #else
206 char key_file_storage[MAX_PATH+1], *key_file ;
207 #endif /* SYS_WINNT */
210 * Miscellaneous flags
212 int verbose = 0;
213 int always_step = 0;
214 int never_step = 0;
216 int ntpdatemain P((int, char **));
218 static void transmit P((struct server *));
219 static void receive P((struct recvbuf *));
220 static void server_data P((struct server *, s_fp, l_fp *, u_fp));
221 static void clock_filter P((struct server *));
222 static struct server *clock_select P((void));
223 static int clock_adjust P((void));
224 static void addserver P((char *));
225 static struct server *findserver P((struct sockaddr_storage *));
226 void timer P((void));
227 static void init_alarm P((void));
228 #ifndef SYS_WINNT
229 static RETSIGTYPE alarming P((int));
230 #endif /* SYS_WINNT */
231 static void init_io P((void));
232 static void sendpkt P((struct sockaddr_storage *, struct pkt *, int));
233 void input_handler P((void));
235 static int l_adj_systime P((l_fp *));
236 static int l_step_systime P((l_fp *));
238 static void printserver P((struct server *, FILE *));
240 #ifdef SYS_WINNT
241 int on = 1;
242 WORD wVersionRequested;
243 WSADATA wsaData;
244 HANDLE TimerThreadHandle = NULL;
245 #endif /* SYS_WINNT */
247 #ifdef NO_MAIN_ALLOWED
248 CALL(ntpdate,"ntpdate",ntpdatemain);
250 void clear_globals()
253 * Debugging flag
255 debug = 0;
257 ntp_optind = 0;
259 * Initializing flag. All async routines watch this and only do their
260 * thing when it is clear.
262 initializing = 1;
265 * Alarm flag. Set when an alarm occurs
267 alarm_flag = 0;
270 * Simple query flag.
272 simple_query = 0;
275 * Unprivileged port flag.
277 unpriv_port = 0;
280 * Systemwide parameters and flags
282 sys_numservers = 0; /* number of servers to poll */
283 sys_authenticate = 0; /* true when authenticating */
284 sys_authkey = 0; /* set to authentication key in use */
285 sys_authdelay = 0; /* authentication delay */
286 sys_version = NTP_VERSION; /* version to poll with */
289 * The current internal time
291 current_time = 0;
294 * Counter for keeping track of completed servers
296 complete_servers = 0;
297 verbose = 0;
298 always_step = 0;
299 never_step = 0;
301 #endif
303 #ifdef HAVE_NETINFO
304 static ni_namelist *getnetinfoservers P((void));
305 #endif
308 * Main program. Initialize us and loop waiting for I/O and/or
309 * timer expiries.
311 #ifndef NO_MAIN_ALLOWED
313 main(
314 int argc,
315 char *argv[]
318 return ntpdatemain (argc, argv);
320 #endif /* NO_MAIN_ALLOWED */
323 ntpdatemain (
324 int argc,
325 char *argv[]
328 int was_alarmed;
329 int tot_recvbufs;
330 struct recvbuf *rbuf;
331 l_fp tmp;
332 int errflg;
333 int c;
334 int nfound;
336 #ifdef HAVE_NETINFO
337 ni_namelist *netinfoservers;
338 #endif
339 #ifdef SYS_WINNT
340 HANDLE process_handle;
342 wVersionRequested = MAKEWORD(1,1);
343 if (WSAStartup(wVersionRequested, &wsaData)) {
344 netsyslog(LOG_ERR, "No useable winsock.dll: %m");
345 exit(1);
348 key_file = key_file_storage;
350 if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
352 msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m\n");
354 #endif /* SYS_WINNT */
356 #ifdef NO_MAIN_ALLOWED
357 clear_globals();
358 #endif
361 /* Check to see if we have IPv6. Otherwise force the -4 flag */
362 if (isc_net_probeipv6() != ISC_R_SUCCESS) {
363 ai_fam_templ = AF_INET;
366 errflg = 0;
367 progname = argv[0];
368 syslogit = 0;
371 * Decode argument list
373 while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
374 switch (c)
376 case '4':
377 ai_fam_templ = AF_INET;
378 break;
379 case '6':
380 ai_fam_templ = AF_INET6;
381 break;
382 case 'a':
383 c = atoi(ntp_optarg);
384 sys_authenticate = 1;
385 sys_authkey = c;
386 break;
387 case 'b':
388 always_step++;
389 never_step = 0;
390 break;
391 case 'B':
392 never_step++;
393 always_step = 0;
394 break;
395 case 'd':
396 ++debug;
397 break;
398 case 'e':
399 if (!atolfp(ntp_optarg, &tmp)
400 || tmp.l_ui != 0) {
401 (void) fprintf(stderr,
402 "%s: encryption delay %s is unlikely\n",
403 progname, ntp_optarg);
404 errflg++;
405 } else {
406 sys_authdelay = tmp.l_uf;
408 break;
409 case 'k':
410 key_file = ntp_optarg;
411 break;
412 case 'o':
413 sys_version = atoi(ntp_optarg);
414 break;
415 case 'p':
416 c = atoi(ntp_optarg);
417 if (c <= 0 || c > NTP_SHIFT) {
418 (void) fprintf(stderr,
419 "%s: number of samples (%d) is invalid\n",
420 progname, c);
421 errflg++;
422 } else {
423 sys_samples = c;
425 break;
426 case 'q':
427 simple_query = 1;
428 break;
429 case 's':
430 syslogit = 1;
431 break;
432 case 't':
433 if (!atolfp(ntp_optarg, &tmp)) {
434 (void) fprintf(stderr,
435 "%s: timeout %s is undecodeable\n",
436 progname, ntp_optarg);
437 errflg++;
438 } else {
439 sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
440 + 0x8000) >> 16;
441 if (sys_timeout == 0)
442 sys_timeout = 1;
444 break;
445 case 'v':
446 verbose = 1;
447 break;
448 case 'u':
449 unpriv_port = 1;
450 break;
451 case '?':
452 ++errflg;
453 break;
454 default:
455 break;
458 if (errflg) {
459 (void) fprintf(stderr,
460 "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
461 progname);
462 exit(2);
465 if (debug || simple_query) {
466 #ifdef HAVE_SETVBUF
467 static char buf[BUFSIZ];
468 #ifdef SYS_WINNT
469 /* Win32 does not implement line buffering */
470 setvbuf(stdout, NULL, _IONBF, BUFSIZ);
471 #else
472 setvbuf(stdout, buf, _IOLBF, BUFSIZ);
473 #endif /* SYS_WINNT */
474 #else
475 setlinebuf(stdout);
476 #endif
480 * Logging. Open the syslog if we have to
482 if (syslogit) {
483 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
484 # ifndef LOG_DAEMON
485 openlog("ntpdate", LOG_PID);
486 # else
488 # ifndef LOG_NTP
489 # define LOG_NTP LOG_DAEMON
490 # endif
491 openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
492 if (debug)
493 setlogmask(LOG_UPTO(LOG_DEBUG));
494 else
495 setlogmask(LOG_UPTO(LOG_INFO));
496 # endif /* LOG_DAEMON */
497 #endif /* SYS_WINNT */
500 if (debug || verbose)
501 msyslog(LOG_NOTICE, "%s", Version);
504 * Add servers we are going to be polling
506 #ifdef HAVE_NETINFO
507 netinfoservers = getnetinfoservers();
508 #endif
510 for ( ; ntp_optind < argc; ntp_optind++)
511 addserver(argv[ntp_optind]);
513 #ifdef HAVE_NETINFO
514 if (netinfoservers) {
515 if ( netinfoservers->ni_namelist_len &&
516 *netinfoservers->ni_namelist_val ) {
517 u_int servercount = 0;
518 while (servercount < netinfoservers->ni_namelist_len) {
519 if (debug) msyslog(LOG_DEBUG,
520 "Adding time server %s from NetInfo configuration.",
521 netinfoservers->ni_namelist_val[servercount]);
522 addserver(netinfoservers->ni_namelist_val[servercount++]);
525 ni_namelist_free(netinfoservers);
526 free(netinfoservers);
528 #endif
530 if (sys_numservers == 0) {
531 msyslog(LOG_ERR, "no servers can be used, exiting");
532 exit(1);
536 * Initialize the time of day routines and the I/O subsystem
538 if (sys_authenticate) {
539 init_auth();
540 if (!authreadkeys(key_file)) {
541 msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
542 exit(1);
544 authtrust(sys_authkey, 1);
545 if (!authistrusted(sys_authkey)) {
546 msyslog(LOG_ERR, "authentication key %lu unknown",
547 (unsigned long) sys_authkey);
548 exit(1);
551 init_io();
552 init_alarm();
555 * Set the priority.
557 #ifdef SYS_VXWORKS
558 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
559 #endif
560 #if defined(HAVE_ATT_NICE)
561 nice (NTPDATE_PRIO);
562 #endif
563 #if defined(HAVE_BSD_NICE)
564 (void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
565 #endif
566 #ifdef SYS_WINNT
567 process_handle = GetCurrentProcess();
568 if (!SetPriorityClass(process_handle, (DWORD) REALTIME_PRIORITY_CLASS)) {
569 msyslog(LOG_ERR, "SetPriorityClass failed: %m");
571 #endif /* SYS_WINNT */
575 initializing = 0;
576 was_alarmed = 0;
578 while (complete_servers < sys_numservers) {
579 #ifdef HAVE_POLL_H
580 struct pollfd* rdfdes;
581 rdfdes = fdmask;
582 #else
583 fd_set rdfdes;
584 rdfdes = fdmask;
585 #endif
587 if (alarm_flag) { /* alarmed? */
588 was_alarmed = 1;
589 alarm_flag = 0;
591 tot_recvbufs = full_recvbuffs(); /* get received buffers */
593 if (!was_alarmed && tot_recvbufs == 0) {
595 * Nothing to do. Wait for something.
597 #ifdef HAVE_POLL_H
598 nfound = poll(rdfdes, (unsigned int)nbsock, timeout.tv_sec * 1000);
600 #else
601 nfound = select(maxfd, &rdfdes, (fd_set *)0,
602 (fd_set *)0, &timeout);
603 #endif
604 if (nfound > 0)
605 input_handler();
606 else if (nfound == SOCKET_ERROR)
608 #ifndef SYS_WINNT
609 if (errno != EINTR)
610 #else
611 if (WSAGetLastError() != WSAEINTR)
612 #endif
613 netsyslog(LOG_ERR,
614 #ifdef HAVE_POLL_H
615 "poll() error: %m"
616 #else
617 "select() error: %m"
618 #endif
620 } else if (errno != 0) {
621 #ifndef SYS_VXWORKS
622 netsyslog(LOG_DEBUG,
623 #ifdef HAVE_POLL_H
624 "poll(): nfound = %d, error: %m",
625 #else
626 "select(): nfound = %d, error: %m",
627 #endif
628 nfound);
629 #endif
631 if (alarm_flag) { /* alarmed? */
632 was_alarmed = 1;
633 alarm_flag = 0;
635 tot_recvbufs = full_recvbuffs(); /* get received buffers */
639 * Out here, signals are unblocked. Call receive
640 * procedure for each incoming packet.
642 rbuf = get_full_recv_buffer();
643 while (rbuf != NULL)
645 receive(rbuf);
646 freerecvbuf(rbuf);
647 rbuf = get_full_recv_buffer();
651 * Call timer to process any timeouts
653 if (was_alarmed) {
654 timer();
655 was_alarmed = 0;
659 * Go around again
664 * When we get here we've completed the polling of all servers.
665 * Adjust the clock, then exit.
667 #ifdef SYS_WINNT
668 WSACleanup();
669 #endif
670 #ifdef SYS_VXWORKS
671 close (fd);
672 timer_delete(ntpdate_timerid);
673 #endif
675 return clock_adjust();
680 * transmit - transmit a packet to the given server, or mark it completed.
681 * This is called by the timeout routine and by the receive
682 * procedure.
684 static void
685 transmit(
686 register struct server *server
689 struct pkt xpkt;
691 if (debug)
692 printf("transmit(%s)\n", stoa(&(server->srcadr)));
694 if (server->filter_nextpt < server->xmtcnt) {
695 l_fp ts;
697 * Last message to this server timed out. Shift
698 * zeros into the filter.
700 L_CLR(&ts);
701 server_data(server, 0, &ts, 0);
704 if ((int)server->filter_nextpt >= sys_samples) {
706 * Got all the data we need. Mark this guy
707 * completed and return.
709 server->event_time = 0;
710 complete_servers++;
711 return;
715 * If we're here, send another message to the server. Fill in
716 * the packet and let 'er rip.
718 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
719 sys_version, MODE_CLIENT);
720 xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
721 xpkt.ppoll = NTP_MINPOLL;
722 xpkt.precision = NTPDATE_PRECISION;
723 xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
724 xpkt.rootdispersion = htonl(NTPDATE_DISP);
725 xpkt.refid = htonl(NTPDATE_REFID);
726 L_CLR(&xpkt.reftime);
727 L_CLR(&xpkt.org);
728 L_CLR(&xpkt.rec);
731 * Determine whether to authenticate or not. If so,
732 * fill in the extended part of the packet and do it.
733 * If not, just timestamp it and send it away.
735 if (sys_authenticate) {
736 int len;
738 xpkt.exten[0] = htonl(sys_authkey);
739 get_systime(&server->xmt);
740 L_ADDUF(&server->xmt, sys_authdelay);
741 HTONL_FP(&server->xmt, &xpkt.xmt);
742 len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
743 sendpkt(&(server->srcadr), &xpkt, (int)(LEN_PKT_NOMAC + len));
745 if (debug > 1)
746 printf("transmit auth to %s\n",
747 stoa(&(server->srcadr)));
748 } else {
749 get_systime(&(server->xmt));
750 HTONL_FP(&server->xmt, &xpkt.xmt);
751 sendpkt(&(server->srcadr), &xpkt, LEN_PKT_NOMAC);
753 if (debug > 1)
754 printf("transmit to %s\n", stoa(&(server->srcadr)));
758 * Update the server timeout and transmit count
760 server->event_time = current_time + sys_timeout;
761 server->xmtcnt++;
766 * receive - receive and process an incoming frame
768 static void
769 receive(
770 struct recvbuf *rbufp
773 register struct pkt *rpkt;
774 register struct server *server;
775 register s_fp di;
776 l_fp t10, t23, tmp;
777 l_fp org;
778 l_fp rec;
779 l_fp ci;
780 int has_mac;
781 int is_authentic;
783 if (debug)
784 printf("receive(%s)\n", stoa(&rbufp->recv_srcadr));
786 * Check to see if the packet basically looks like something
787 * intended for us.
789 if (rbufp->recv_length == LEN_PKT_NOMAC)
790 has_mac = 0;
791 else if (rbufp->recv_length >= LEN_PKT_NOMAC)
792 has_mac = 1;
793 else {
794 if (debug)
795 printf("receive: packet length %d\n",
796 rbufp->recv_length);
797 return; /* funny length packet */
800 rpkt = &(rbufp->recv_pkt);
801 if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
802 PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
803 return;
806 if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
807 && PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
808 || rpkt->stratum >= STRATUM_UNSPEC) {
809 if (debug)
810 printf("receive: mode %d stratum %d\n",
811 PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
812 return;
816 * So far, so good. See if this is from a server we know.
818 server = findserver(&(rbufp->recv_srcadr));
819 if (server == NULL) {
820 if (debug)
821 printf("receive: server not found\n");
822 return;
826 * Decode the org timestamp and make sure we're getting a response
827 * to our last request.
829 NTOHL_FP(&rpkt->org, &org);
830 if (!L_ISEQU(&org, &server->xmt)) {
831 if (debug)
832 printf("receive: pkt.org and peer.xmt differ\n");
833 return;
837 * Check out the authenticity if we're doing that.
839 if (!sys_authenticate)
840 is_authentic = 1;
841 else {
842 is_authentic = 0;
844 if (debug > 3)
845 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
846 (long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
847 (long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
848 LEN_PKT_NOMAC, (int)(rbufp->recv_length - LEN_PKT_NOMAC)));
850 if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
851 authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
852 (int)(rbufp->recv_length - LEN_PKT_NOMAC)))
853 is_authentic = 1;
854 if (debug)
855 printf("receive: authentication %s\n",
856 is_authentic ? "passed" : "failed");
858 server->trust <<= 1;
859 if (!is_authentic)
860 server->trust |= 1;
863 * Looks good. Record info from the packet.
865 server->leap = PKT_LEAP(rpkt->li_vn_mode);
866 server->stratum = PKT_TO_STRATUM(rpkt->stratum);
867 server->precision = rpkt->precision;
868 server->rootdelay = ntohl(rpkt->rootdelay);
869 server->rootdispersion = ntohl(rpkt->rootdispersion);
870 server->refid = rpkt->refid;
871 NTOHL_FP(&rpkt->reftime, &server->reftime);
872 NTOHL_FP(&rpkt->rec, &rec);
873 NTOHL_FP(&rpkt->xmt, &server->org);
876 * Make sure the server is at least somewhat sane. If not, try
877 * again.
879 if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
880 transmit(server);
881 return;
885 * Calculate the round trip delay (di) and the clock offset (ci).
886 * We use the equations (reordered from those in the spec):
888 * d = (t2 - t3) - (t1 - t0)
889 * c = ((t2 - t3) + (t1 - t0)) / 2
891 t10 = server->org; /* pkt.xmt == t1 */
892 L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
894 t23 = rec; /* pkt.rec == t2 */
895 L_SUB(&t23, &org); /* pkt->org == t3 */
897 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
899 * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
900 * For large offsets this may prevent an overflow on '+'
902 ci = t10;
903 L_RSHIFT(&ci);
904 tmp = t23;
905 L_RSHIFT(&tmp);
906 L_ADD(&ci, &tmp);
909 * Calculate di in t23 in full precision, then truncate
910 * to an s_fp.
912 L_SUB(&t23, &t10);
913 di = LFPTOFP(&t23);
915 if (debug > 3)
916 printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
918 di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
919 + (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
921 if (di <= 0) { /* value still too raunchy to use? */
922 L_CLR(&ci);
923 di = 0;
924 } else {
925 di = max(di, NTP_MINDIST);
929 * Shift this data in, then transmit again.
931 server_data(server, (s_fp) di, &ci, 0);
932 transmit(server);
937 * server_data - add a sample to the server's filter registers
939 static void
940 server_data(
941 register struct server *server,
942 s_fp d,
943 l_fp *c,
944 u_fp e
947 u_short i;
949 i = server->filter_nextpt;
950 if (i < NTP_SHIFT) {
951 server->filter_delay[i] = d;
952 server->filter_offset[i] = *c;
953 server->filter_soffset[i] = LFPTOFP(c);
954 server->filter_error[i] = e;
955 server->filter_nextpt = (u_short)(i + 1);
961 * clock_filter - determine a server's delay, dispersion and offset
963 static void
964 clock_filter(
965 register struct server *server
968 register int i, j;
969 int ord[NTP_SHIFT];
972 * Sort indices into increasing delay order
974 for (i = 0; i < sys_samples; i++)
975 ord[i] = i;
977 for (i = 0; i < (sys_samples-1); i++) {
978 for (j = i+1; j < sys_samples; j++) {
979 if (server->filter_delay[ord[j]] == 0)
980 continue;
981 if (server->filter_delay[ord[i]] == 0
982 || (server->filter_delay[ord[i]]
983 > server->filter_delay[ord[j]])) {
984 register int tmp;
986 tmp = ord[i];
987 ord[i] = ord[j];
988 ord[j] = tmp;
994 * Now compute the dispersion, and assign values to delay and
995 * offset. If there are no samples in the register, delay and
996 * offset go to zero and dispersion is set to the maximum.
998 if (server->filter_delay[ord[0]] == 0) {
999 server->delay = 0;
1000 L_CLR(&server->offset);
1001 server->soffset = 0;
1002 server->dispersion = PEER_MAXDISP;
1003 } else {
1004 register s_fp d;
1006 server->delay = server->filter_delay[ord[0]];
1007 server->offset = server->filter_offset[ord[0]];
1008 server->soffset = LFPTOFP(&server->offset);
1009 server->dispersion = 0;
1010 for (i = 1; i < sys_samples; i++) {
1011 if (server->filter_delay[ord[i]] == 0)
1012 d = PEER_MAXDISP;
1013 else {
1014 d = server->filter_soffset[ord[i]]
1015 - server->filter_soffset[ord[0]];
1016 if (d < 0)
1017 d = -d;
1018 if (d > PEER_MAXDISP)
1019 d = PEER_MAXDISP;
1022 * XXX This *knows* PEER_FILTER is 1/2
1024 server->dispersion += (u_fp)(d) >> i;
1028 * We're done
1034 * clock_select - select the pick-of-the-litter clock from the samples
1035 * we've got.
1037 static struct server *
1038 clock_select(void)
1040 register struct server *server;
1041 register int i;
1042 register int nlist;
1043 register s_fp d;
1044 register int j;
1045 register int n;
1046 s_fp local_threshold;
1047 struct server *server_list[NTP_MAXCLOCK];
1048 u_fp server_badness[NTP_MAXCLOCK];
1049 struct server *sys_server;
1052 * This first chunk of code is supposed to go through all
1053 * servers we know about to find the NTP_MAXLIST servers which
1054 * are most likely to succeed. We run through the list
1055 * doing the sanity checks and trying to insert anyone who
1056 * looks okay. We are at all times aware that we should
1057 * only keep samples from the top two strata and we only need
1058 * NTP_MAXLIST of them.
1060 nlist = 0; /* none yet */
1061 for (server = sys_servers; server != NULL; server = server->next_server) {
1062 if (server->delay == 0) {
1063 if (debug)
1064 printf("%s: Server dropped: no data\n", ntoa(&server->srcadr));
1065 continue; /* no data */
1067 if (server->stratum > NTP_INFIN) {
1068 if (debug)
1069 printf("%s: Server dropped: strata too high\n", ntoa(&server->srcadr));
1070 continue; /* stratum no good */
1072 if (server->delay > NTP_MAXWGT) {
1073 if (debug)
1074 printf("%s: Server dropped: server too far away\n",
1075 ntoa(&server->srcadr));
1076 continue; /* too far away */
1078 if (server->leap == LEAP_NOTINSYNC) {
1079 if (debug)
1080 printf("%s: Server dropped: Leap not in sync\n", ntoa(&server->srcadr));
1081 continue; /* he's in trouble */
1083 if (!L_ISHIS(&server->org, &server->reftime)) {
1084 if (debug)
1085 printf("%s: Server dropped: server is very broken\n",
1086 ntoa(&server->srcadr));
1087 continue; /* very broken host */
1089 if ((server->org.l_ui - server->reftime.l_ui)
1090 >= NTP_MAXAGE) {
1091 if (debug)
1092 printf("%s: Server dropped: Server has gone too long without sync\n",
1093 ntoa(&server->srcadr));
1094 continue; /* too long without sync */
1096 if (server->trust != 0) {
1097 if (debug)
1098 printf("%s: Server dropped: Server is untrusted\n",
1099 ntoa(&server->srcadr));
1100 continue;
1104 * This one seems sane. Find where he belongs
1105 * on the list.
1107 d = server->dispersion + server->dispersion;
1108 for (i = 0; i < nlist; i++)
1109 if (server->stratum <= server_list[i]->stratum)
1110 break;
1111 for ( ; i < nlist; i++) {
1112 if (server->stratum < server_list[i]->stratum)
1113 break;
1114 if (d < (s_fp) server_badness[i])
1115 break;
1119 * If i points past the end of the list, this
1120 * guy is a loser, else stick him in.
1122 if (i >= NTP_MAXLIST)
1123 continue;
1124 for (j = nlist; j > i; j--)
1125 if (j < NTP_MAXLIST) {
1126 server_list[j] = server_list[j-1];
1127 server_badness[j]
1128 = server_badness[j-1];
1131 server_list[i] = server;
1132 server_badness[i] = d;
1133 if (nlist < NTP_MAXLIST)
1134 nlist++;
1138 * Got the five-or-less best. Cut the list where the number of
1139 * strata exceeds two.
1141 j = 0;
1142 for (i = 1; i < nlist; i++)
1143 if (server_list[i]->stratum > server_list[i-1]->stratum)
1144 if (++j == 2) {
1145 nlist = i;
1146 break;
1150 * Whew! What we should have by now is 0 to 5 candidates for
1151 * the job of syncing us. If we have none, we're out of luck.
1152 * If we have one, he's a winner. If we have more, do falseticker
1153 * detection.
1156 if (nlist == 0)
1157 sys_server = 0;
1158 else if (nlist == 1) {
1159 sys_server = server_list[0];
1160 } else {
1162 * Re-sort by stratum, bdelay estimate quality and
1163 * server.delay.
1165 for (i = 0; i < nlist-1; i++)
1166 for (j = i+1; j < nlist; j++) {
1167 if (server_list[i]->stratum
1168 < server_list[j]->stratum)
1169 break; /* already sorted by stratum */
1170 if (server_list[i]->delay
1171 < server_list[j]->delay)
1172 continue;
1173 server = server_list[i];
1174 server_list[i] = server_list[j];
1175 server_list[j] = server;
1179 * Calculate the fixed part of the dispersion limit
1181 local_threshold = (FP_SECOND >> (-(int)NTPDATE_PRECISION))
1182 + NTP_MAXSKW;
1185 * Now drop samples until we're down to one.
1187 while (nlist > 1) {
1188 for (n = 0; n < nlist; n++) {
1189 server_badness[n] = 0;
1190 for (j = 0; j < nlist; j++) {
1191 if (j == n) /* with self? */
1192 continue;
1193 d = server_list[j]->soffset
1194 - server_list[n]->soffset;
1195 if (d < 0) /* absolute value */
1196 d = -d;
1198 * XXX This code *knows* that
1199 * NTP_SELECT is 3/4
1201 for (i = 0; i < j; i++)
1202 d = (d>>1) + (d>>2);
1203 server_badness[n] += d;
1208 * We now have an array of nlist badness
1209 * coefficients. Find the badest. Find
1210 * the minimum precision while we're at
1211 * it.
1213 i = 0;
1214 n = server_list[0]->precision;;
1215 for (j = 1; j < nlist; j++) {
1216 if (server_badness[j] >= server_badness[i])
1217 i = j;
1218 if (n > server_list[j]->precision)
1219 n = server_list[j]->precision;
1223 * i is the index of the server with the worst
1224 * dispersion. If his dispersion is less than
1225 * the threshold, stop now, else delete him and
1226 * continue around again.
1228 if ( (s_fp) server_badness[i] < (local_threshold
1229 + (FP_SECOND >> (-n))))
1230 break;
1231 for (j = i + 1; j < nlist; j++)
1232 server_list[j-1] = server_list[j];
1233 nlist--;
1237 * What remains is a list of less than 5 servers. Take
1238 * the best.
1240 sys_server = server_list[0];
1244 * That's it. Return our server.
1246 return sys_server;
1251 * clock_adjust - process what we've received, and adjust the time
1252 * if we got anything decent.
1254 static int
1255 clock_adjust(void)
1257 register struct server *sp, *server;
1258 s_fp absoffset;
1259 int dostep;
1261 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1262 clock_filter(sp);
1263 server = clock_select();
1265 if (debug || simple_query) {
1266 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1267 printserver(sp, stdout);
1270 if (server == 0) {
1271 msyslog(LOG_ERR,
1272 "no server suitable for synchronization found");
1273 return(1);
1276 if (always_step) {
1277 dostep = 1;
1278 } else if (never_step) {
1279 dostep = 0;
1280 } else {
1281 absoffset = server->soffset;
1282 if (absoffset < 0)
1283 absoffset = -absoffset;
1284 dostep = (absoffset >= NTPDATE_THRESHOLD || absoffset < 0);
1287 if (dostep) {
1288 if (simple_query || debug || l_step_systime(&server->offset)){
1289 msyslog(LOG_NOTICE, "step time server %s offset %s sec",
1290 stoa(&server->srcadr),
1291 lfptoa(&server->offset, 6));
1293 } else {
1294 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1295 if (simple_query || l_adj_systime(&server->offset)) {
1296 msyslog(LOG_NOTICE, "adjust time server %s offset %s sec",
1297 stoa(&server->srcadr),
1298 lfptoa(&server->offset, 6));
1300 #else
1301 /* The NT SetSystemTimeAdjustment() call achieves slewing by
1302 * changing the clock frequency. This means that we cannot specify
1303 * it to slew the clock by a definite amount and then stop like
1304 * the Unix adjtime() routine. We can technically adjust the clock
1305 * frequency, have ntpdate sleep for a while, and then wake
1306 * up and reset the clock frequency, but this might cause some
1307 * grief if the user attempts to run ntpd immediately after
1308 * ntpdate and the socket is in use.
1310 printf("\nThe -b option is required by ntpdate on Windows NT platforms\n");
1311 exit(1);
1312 #endif /* SYS_WINNT */
1314 return(0);
1319 * is_unreachable - check to see if we have a route to given destination
1320 * (non-blocking).
1322 static int
1323 is_reachable (struct sockaddr_storage *dst)
1325 SOCKET sockfd;
1327 sockfd = socket(dst->ss_family, SOCK_DGRAM, 0);
1328 if (sockfd == -1) {
1329 return 0;
1332 if(connect(sockfd, (struct sockaddr *)dst, SOCKLEN(dst))) {
1333 closesocket(sockfd);
1334 return 0;
1336 closesocket(sockfd);
1337 return 1;
1342 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1344 * addserver - determine a server's address and allocate a new structure
1345 * for it.
1347 static void
1348 addserver(
1349 char *serv
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 strcpy(service, "ntp");
1363 /* Get host address. Looking for UDP datagram connection. */
1364 memset(&hints, 0, sizeof(hints));
1365 hints.ai_family = ai_fam_templ;
1366 hints.ai_socktype = SOCK_DGRAM;
1368 #ifdef DEBUG
1369 if (debug)
1370 printf("Looking for host %s and service %s\n", serv, service);
1371 #endif
1373 error = getaddrinfo(serv, service, &hints, &addrResult);
1374 if (error != 0) {
1375 /* Conduct more refined error analysis */
1376 if (error == EAI_FAIL || error == EAI_AGAIN){
1377 /* Name server is unusable. Exit after failing on the
1378 first server, in order to shorten the timeout caused
1379 by waiting for resolution of several servers */
1380 fprintf(stderr, "Name server cannot be used, exiting");
1381 msyslog(LOG_ERR, "name server cannot be used, reason: %s\n", gai_strerror(error));
1382 exit(1);
1384 fprintf(stderr, "Error : %s\n", gai_strerror(error));
1385 msyslog(LOG_ERR, "can't find host %s\n", serv);
1386 return;
1388 #ifdef DEBUG
1389 else if (debug) {
1390 fprintf(stderr, "host found : %s\n", stohost((struct sockaddr_storage*)addrResult->ai_addr));
1392 #endif
1394 /* We must get all returned server in case the first one fails */
1395 for (ptr = addrResult; ptr != NULL; ptr = ptr->ai_next) {
1396 if (is_reachable ((struct sockaddr_storage *)ptr->ai_addr)) {
1397 server = (struct server *)emalloc(sizeof(struct server));
1398 memset((char *)server, 0, sizeof(struct server));
1400 memset(&(server->srcadr), 0, sizeof(struct sockaddr_storage));
1401 memcpy(&(server->srcadr), ptr->ai_addr, ptr->ai_addrlen);
1402 server->event_time = ++sys_numservers;
1403 if (sys_servers == NULL)
1404 sys_servers = server;
1405 else {
1406 struct server *sp;
1408 for (sp = sys_servers; sp->next_server != NULL;
1409 sp = sp->next_server) ;
1410 sp->next_server = server;
1415 freeaddrinfo(addrResult);
1420 * findserver - find a server in the list given its address
1421 * ***(For now it isn't totally AF-Independant, to check later..)
1423 static struct server *
1424 findserver(
1425 struct sockaddr_storage *addr
1428 struct server *server;
1429 struct server *mc_server;
1430 isc_sockaddr_t laddr;
1431 isc_sockaddr_t saddr;
1433 if(addr->ss_family == AF_INET) {
1434 isc_sockaddr_fromin( &laddr, &((struct sockaddr_in*)addr)->sin_addr, 0);
1436 else {
1437 isc_sockaddr_fromin6(&laddr, &((struct sockaddr_in6*)addr)->sin6_addr, 0);
1441 mc_server = NULL;
1442 if (htons(((struct sockaddr_in*)addr)->sin_port) != NTP_PORT)
1443 return 0;
1445 for (server = sys_servers; server != NULL;
1446 server = server->next_server) {
1448 if(server->srcadr.ss_family == AF_INET) {
1449 isc_sockaddr_fromin(&saddr, &((struct sockaddr_in*)&server->srcadr)->sin_addr, 0);
1451 else {
1452 isc_sockaddr_fromin6(&saddr, &((struct sockaddr_in6*)&server->srcadr)->sin6_addr, 0);
1454 if (isc_sockaddr_eqaddr(&laddr, &saddr) == ISC_TRUE)
1455 return server;
1457 if(addr->ss_family == server->srcadr.ss_family) {
1458 if (isc_sockaddr_ismulticast(&saddr) == ISC_TRUE)
1459 mc_server = server;
1463 if (mc_server != NULL) {
1465 struct server *sp;
1467 if (mc_server->event_time != 0) {
1468 mc_server->event_time = 0;
1469 complete_servers++;
1472 server = (struct server *)emalloc(sizeof(struct server));
1473 memset((char *)server, 0, sizeof(struct server));
1475 memcpy(&server->srcadr, addr, sizeof(struct sockaddr_storage));
1477 server->event_time = ++sys_numservers;
1479 for (sp = sys_servers; sp->next_server != NULL;
1480 sp = sp->next_server) ;
1481 sp->next_server = server;
1482 transmit(server);
1484 return NULL;
1489 * timer - process a timer interrupt
1491 void
1492 timer(void)
1494 struct server *server;
1497 * Bump the current idea of the time
1499 current_time++;
1502 * Search through the server list looking for guys
1503 * who's event timers have expired. Give these to
1504 * the transmit routine.
1506 for (server = sys_servers; server != NULL;
1507 server = server->next_server) {
1508 if (server->event_time != 0
1509 && server->event_time <= current_time)
1510 transmit(server);
1516 * The code duplication in the following subroutine sucks, but
1517 * we need to appease ansi2knr.
1520 #ifndef SYS_WINNT
1522 * alarming - record the occurance of an alarm interrupt
1524 static RETSIGTYPE
1525 alarming(
1526 int sig
1529 alarm_flag++;
1531 #else
1532 void CALLBACK
1533 alarming(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1535 alarm_flag++;
1537 #endif /* SYS_WINNT */
1540 #ifdef SYS_WINNT
1541 static void
1542 callTimeEndPeriod(void)
1544 timeEndPeriod( wTimerRes );
1545 wTimerRes = 0;
1547 #endif /* SYS_WINNT */
1551 * init_alarm - set up the timer interrupt
1553 static void
1554 init_alarm(void)
1556 #ifndef SYS_WINNT
1557 # ifndef HAVE_TIMER_SETTIME
1558 struct itimerval itimer;
1559 # else
1560 struct itimerspec ntpdate_itimer;
1561 # endif
1562 #else
1563 TIMECAPS tc;
1564 UINT wTimerID;
1565 # endif /* SYS_WINNT */
1566 #if defined SYS_CYGWIN32 || defined SYS_WINNT
1567 HANDLE hToken;
1568 TOKEN_PRIVILEGES tkp;
1569 DWORD dwUser = 0;
1570 #endif /* SYS_WINNT */
1572 alarm_flag = 0;
1574 #ifndef SYS_WINNT
1575 # if defined(HAVE_TIMER_CREATE) && defined(HAVE_TIMER_SETTIME)
1576 alarm_flag = 0;
1577 /* this code was put in as setitimer() is non existant this us the
1578 * POSIX "equivalents" setup - casey
1580 /* ntpdate_timerid is global - so we can kill timer later */
1581 if (timer_create (CLOCK_REALTIME, NULL, &ntpdate_timerid) ==
1582 # ifdef SYS_VXWORKS
1583 ERROR
1584 # else
1586 # endif
1589 fprintf (stderr, "init_alarm(): timer_create (...) FAILED\n");
1590 return;
1593 /* TIMER_HZ = (5)
1594 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1595 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1597 (void) signal_no_reset(SIGALRM, alarming);
1598 ntpdate_itimer.it_interval.tv_sec = ntpdate_itimer.it_value.tv_sec = 0;
1599 ntpdate_itimer.it_interval.tv_nsec = 1000000000/TIMER_HZ;
1600 ntpdate_itimer.it_value.tv_nsec = 1000000000/(TIMER_HZ<<1);
1601 timer_settime(ntpdate_timerid, 0 /* !TIMER_ABSTIME */, &ntpdate_itimer, NULL);
1602 # else
1604 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1605 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1607 (void) signal_no_reset(SIGALRM, alarming);
1608 itimer.it_interval.tv_sec = itimer.it_value.tv_sec = 0;
1609 itimer.it_interval.tv_usec = 1000000/TIMER_HZ;
1610 itimer.it_value.tv_usec = 1000000/(TIMER_HZ<<1);
1612 setitimer(ITIMER_REAL, &itimer, (struct itimerval *)0);
1613 # endif
1614 #if defined SYS_CYGWIN32
1616 * Get privileges needed for fiddling with the clock
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);
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 #endif
1634 #else /* SYS_WINNT */
1635 _tzset();
1638 * Get privileges needed for fiddling with the clock
1641 /* get the current process token handle */
1642 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1643 msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1644 exit(1);
1646 /* get the LUID for system-time privilege. */
1647 LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1648 tkp.PrivilegeCount = 1; /* one privilege to set */
1649 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1650 /* get set-time privilege for this process. */
1651 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1652 /* cannot test return value of AdjustTokenPrivileges. */
1653 if (GetLastError() != ERROR_SUCCESS)
1654 msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1657 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1658 * Under Win/NT, expiry of timer interval leads to invocation
1659 * of a callback function (on a different thread) rather than
1660 * generating an alarm signal
1663 /* determine max and min resolution supported */
1664 if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
1665 msyslog(LOG_ERR, "timeGetDevCaps failed: %m");
1666 exit(1);
1668 wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
1669 /* establish the minimum timer resolution that we'll use */
1670 timeBeginPeriod(wTimerRes);
1671 atexit(callTimeEndPeriod);
1673 /* start the timer event */
1674 wTimerID = timeSetEvent(
1675 (UINT) (1000/TIMER_HZ), /* Delay */
1676 wTimerRes, /* Resolution */
1677 (LPTIMECALLBACK) alarming, /* Callback function */
1678 (DWORD) dwUser, /* User data */
1679 TIME_PERIODIC); /* Event type (periodic) */
1680 if (wTimerID == 0) {
1681 msyslog(LOG_ERR, "timeSetEvent failed: %m");
1682 exit(1);
1684 #endif /* SYS_WINNT */
1691 * We do asynchronous input using the SIGIO facility. A number of
1692 * recvbuf buffers are preallocated for input. In the signal
1693 * handler we poll to see if the socket is ready and read the
1694 * packets from it into the recvbuf's along with a time stamp and
1695 * an indication of the source host and the interface it was received
1696 * through. This allows us to get as accurate receive time stamps
1697 * as possible independent of other processing going on.
1699 * We allocate a number of recvbufs equal to the number of servers
1700 * plus 2. This should be plenty.
1705 * init_io - initialize I/O data and open socket
1707 static void
1708 init_io(void)
1710 struct addrinfo *res, *ressave;
1711 struct addrinfo hints;
1712 char service[5];
1713 int optval = 1;
1714 int check_ntp_port_in_use = !debug && !simple_query && !unpriv_port;
1717 * Init buffer free list and stat counters
1719 init_recvbuff(sys_numservers + 2);
1722 * Open the socket
1725 strcpy(service, "ntp");
1728 * Init hints addrinfo structure
1730 memset(&hints, 0, sizeof(hints));
1731 hints.ai_family = ai_fam_templ;
1732 hints.ai_flags = AI_PASSIVE;
1733 hints.ai_socktype = SOCK_DGRAM;
1735 if(getaddrinfo(NULL, service, &hints, &res) != 0) {
1736 msyslog(LOG_ERR, "getaddrinfo() failed: %m");
1737 exit(1);
1738 /*NOTREACHED*/
1741 #ifdef SYS_WINNT
1742 if (check_ntp_port_in_use && ntp_port_inuse(AF_INET, NTP_PORT)){
1743 netsyslog(LOG_ERR, "the NTP socket is in use, exiting: %m");
1744 exit(1);
1746 #endif
1748 /* Remember the address of the addrinfo structure chain */
1749 ressave = res;
1752 * For each structure returned, open and bind socket
1754 for(nbsock = 0; (nbsock < MAX_AF) && res ; res = res->ai_next) {
1755 /* create a datagram (UDP) socket */
1756 fd[nbsock] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1757 if (fd[nbsock] == SOCKET_ERROR) {
1758 #ifndef SYS_WINNT
1759 if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT ||
1760 errno == EPFNOSUPPORT)
1761 #else
1762 int err = WSAGetLastError();
1763 if (err == WSAEPROTONOSUPPORT || err == WSAEAFNOSUPPORT ||
1764 err == WSAEPFNOSUPPORT)
1765 #endif
1766 continue;
1767 netsyslog(LOG_ERR, "socket() failed: %m");
1768 exit(1);
1769 /*NOTREACHED*/
1771 /* set socket to reuse address */
1772 if (setsockopt(fd[nbsock], SOL_SOCKET, SO_REUSEADDR, (void*) &optval, sizeof(optval)) < 0) {
1773 netsyslog(LOG_ERR, "setsockopt() SO_REUSEADDR failed: %m");
1774 exit(1);
1775 /*NOTREACHED*/
1777 #ifdef IPV6_V6ONLY
1778 /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1779 if (res->ai_family == AF_INET6)
1780 if (setsockopt(fd[nbsock], IPPROTO_IPV6, IPV6_V6ONLY, (void*) &optval, sizeof(optval)) < 0) {
1781 netsyslog(LOG_ERR, "setsockopt() IPV6_V6ONLY failed: %m");
1782 exit(1);
1783 /*NOTREACHED*/
1785 #endif
1787 /* Remember the socket family in fd_family structure */
1788 fd_family[nbsock] = res->ai_family;
1791 * bind the socket to the NTP port
1793 if (check_ntp_port_in_use) {
1794 if (bind(fd[nbsock], res->ai_addr, SOCKLEN(res->ai_addr)) < 0) {
1795 #ifndef SYS_WINNT
1796 if (errno == EADDRINUSE)
1797 #else
1798 if (WSAGetLastError() == WSAEADDRINUSE)
1799 #endif /* SYS_WINNT */
1800 netsyslog(LOG_ERR, "the NTP socket is in use, exiting");
1801 else
1802 netsyslog(LOG_ERR, "bind() fails: %m");
1803 exit(1);
1807 #ifdef HAVE_POLL_H
1808 fdmask[nbsock].fd = fd[nbsock];
1809 fdmask[nbsock].events = POLLIN;
1810 #else
1811 FD_SET(fd[nbsock], &fdmask);
1812 if (maxfd < fd[nbsock]+1) {
1813 maxfd = fd[nbsock]+1;
1815 #endif
1818 * set non-blocking,
1820 #ifndef SYS_WINNT
1821 # ifdef SYS_VXWORKS
1823 int on = TRUE;
1825 if (ioctl(fd[nbsock],FIONBIO, &on) == ERROR) {
1826 netsyslog(LOG_ERR, "ioctl(FIONBIO) fails: %m");
1827 exit(1);
1830 # else /* not SYS_VXWORKS */
1831 # if defined(O_NONBLOCK)
1832 if (fcntl(fd[nbsock], F_SETFL, O_NONBLOCK) < 0) {
1833 netsyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1834 exit(1);
1835 /*NOTREACHED*/
1837 # else /* not O_NONBLOCK */
1838 # if defined(FNDELAY)
1839 if (fcntl(fd[nbsock], F_SETFL, FNDELAY) < 0) {
1840 netsyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1841 exit(1);
1842 /*NOTREACHED*/
1844 # else /* FNDELAY */
1845 # include "Bletch: Need non blocking I/O"
1846 # endif /* FNDELAY */
1847 # endif /* not O_NONBLOCK */
1848 # endif /* SYS_VXWORKS */
1849 #else /* SYS_WINNT */
1850 if (ioctlsocket(fd[nbsock], FIONBIO, (u_long *) &on) == SOCKET_ERROR) {
1851 netsyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m");
1852 exit(1);
1854 #endif /* SYS_WINNT */
1855 nbsock++;
1857 freeaddrinfo(ressave);
1861 * sendpkt - send a packet to the specified destination
1863 static void
1864 sendpkt(
1865 struct sockaddr_storage *dest,
1866 struct pkt *pkt,
1867 int len
1870 int i;
1871 int cc;
1872 SOCKET sock = INVALID_SOCKET;
1874 #ifdef SYS_WINNT
1875 DWORD err;
1876 #endif /* SYS_WINNT */
1878 /* Find a local family compatible socket to send ntp packet to ntp server */
1879 for(i = 0; (i < MAX_AF); i++) {
1880 if(dest->ss_family == fd_family[i]) {
1881 sock = fd[i];
1882 break;
1886 if ( sock == INVALID_SOCKET ) {
1887 netsyslog(LOG_ERR, "cannot find family compatible socket to send ntp packet");
1888 exit(1);
1889 /*NOTREACHED*/
1892 cc = sendto(sock, (char *)pkt, len, 0, (struct sockaddr *)dest,
1893 SOCKLEN(dest));
1895 if (cc == SOCKET_ERROR) {
1896 #ifndef SYS_WINNT
1897 if (errno != EWOULDBLOCK && errno != ENOBUFS)
1898 #else
1899 err = WSAGetLastError();
1900 if (err != WSAEWOULDBLOCK && err != WSAENOBUFS)
1901 #endif /* SYS_WINNT */
1902 netsyslog(LOG_ERR, "sendto(%s): %m", stohost(dest));
1908 * input_handler - receive packets asynchronously
1910 void
1911 input_handler(void)
1913 register int n;
1914 register struct recvbuf *rb;
1915 struct timeval tvzero;
1916 socklen_t fromlen;
1917 l_fp ts;
1918 int i;
1919 #ifdef HAVE_POLL_H
1920 struct pollfd fds[MAX_AF];
1921 #else
1922 fd_set fds;
1923 #endif
1924 int fdc = 0;
1927 * Do a poll to see if we have data
1929 for (;;) {
1930 tvzero.tv_sec = tvzero.tv_usec = 0;
1931 #ifdef HAVE_POLL_H
1932 memcpy(fds, fdmask, sizeof(fdmask));
1933 n = poll(fds, (unsigned int)nbsock, tvzero.tv_sec * 1000);
1936 * Determine which socket received data
1939 for(i=0; i < nbsock; i++) {
1940 if(fds[i].revents & POLLIN) {
1941 fdc = fd[i];
1942 break;
1946 #else
1947 fds = fdmask;
1948 n = select(maxfd, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
1951 * Determine which socket received data
1954 for(i=0; i < nbsock; i++) {
1955 if(FD_ISSET(fd[i], &fds)) {
1956 fdc = fd[i];
1957 break;
1961 #endif
1964 * If nothing to do, just return. If an error occurred,
1965 * complain and return. If we've got some, freeze a
1966 * timestamp.
1968 if (n == 0)
1969 return;
1970 else if (n == -1) {
1971 if (errno != EINTR)
1972 netsyslog(LOG_ERR,
1973 #ifdef HAVE_POLL_H
1974 "poll() error: %m"
1975 #else
1976 "select() error: %m"
1977 #endif
1979 return;
1981 get_systime(&ts);
1984 * Get a buffer and read the frame. If we
1985 * haven't got a buffer, or this is received
1986 * on the wild card socket, just dump the packet.
1988 if (initializing || free_recvbuffs() == 0) {
1989 char buf[100];
1992 #ifndef SYS_WINNT
1993 (void) read(fdc, buf, sizeof buf);
1994 #else
1995 /* NT's _read does not operate on nonblocking sockets
1996 * either recvfrom or ReadFile() has to be used here.
1997 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1998 * just to be different use recvfrom() here
2000 recvfrom(fdc, buf, sizeof(buf), 0, (struct sockaddr *)0, NULL);
2001 #endif /* SYS_WINNT */
2002 continue;
2005 rb = get_free_recv_buffer();
2007 fromlen = sizeof(struct sockaddr_storage);
2008 rb->recv_length = recvfrom(fdc, (char *)&rb->recv_pkt,
2009 sizeof(rb->recv_pkt), 0,
2010 (struct sockaddr *)&rb->recv_srcadr, &fromlen);
2011 if (rb->recv_length == -1) {
2012 freerecvbuf(rb);
2013 continue;
2017 * Got one. Mark how and when it got here,
2018 * put it on the full list.
2020 rb->recv_time = ts;
2021 add_full_recv_buffer(rb);
2026 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
2028 * adj_systime - do a big long slew of the system time
2030 static int
2031 l_adj_systime(
2032 l_fp *ts
2035 struct timeval adjtv, oadjtv;
2036 int isneg = 0;
2037 l_fp offset;
2038 #ifndef STEP_SLEW
2039 l_fp overshoot;
2040 #endif
2043 * Take the absolute value of the offset
2045 offset = *ts;
2046 if (L_ISNEG(&offset)) {
2047 isneg = 1;
2048 L_NEG(&offset);
2051 #ifndef STEP_SLEW
2053 * Calculate the overshoot. XXX N.B. This code *knows*
2054 * ADJ_OVERSHOOT is 1/2.
2056 overshoot = offset;
2057 L_RSHIFTU(&overshoot);
2058 if (overshoot.l_ui != 0 || (overshoot.l_uf > ADJ_MAXOVERSHOOT)) {
2059 overshoot.l_ui = 0;
2060 overshoot.l_uf = ADJ_MAXOVERSHOOT;
2062 L_ADD(&offset, &overshoot);
2063 #endif
2064 TSTOTV(&offset, &adjtv);
2066 if (isneg) {
2067 adjtv.tv_sec = -adjtv.tv_sec;
2068 adjtv.tv_usec = -adjtv.tv_usec;
2071 if (adjtv.tv_usec != 0 && !debug) {
2072 if (adjtime(&adjtv, &oadjtv) < 0) {
2073 msyslog(LOG_ERR, "Can't adjust the time of day: %m");
2074 return 0;
2077 return 1;
2079 #endif /* SYS_WINNT */
2083 * This fuction is not the same as lib/systime step_systime!!!
2085 static int
2086 l_step_systime(
2087 l_fp *ts
2090 double dtemp;
2092 #ifdef SLEWALWAYS
2093 #ifdef STEP_SLEW
2094 l_fp ftmp;
2095 int isneg;
2096 int n;
2098 if (debug) return 1;
2100 * Take the absolute value of the offset
2102 ftmp = *ts;
2103 if (L_ISNEG(&ftmp)) {
2104 L_NEG(&ftmp);
2105 isneg = 1;
2106 } else
2107 isneg = 0;
2109 if (ftmp.l_ui >= 3) { /* Step it and slew - we might win */
2110 LFPTOD(ts, dtemp);
2111 n = step_systime(dtemp);
2112 if (!n)
2113 return n;
2114 if (isneg)
2115 ts->l_ui = ~0;
2116 else
2117 ts->l_ui = ~0;
2120 * Just add adjustment into the current offset. The update
2121 * routine will take care of bringing the system clock into
2122 * line.
2124 #endif
2125 if (debug)
2126 return 1;
2127 #ifdef FORCE_NTPDATE_STEP
2128 LFPTOD(ts, dtemp);
2129 return step_systime(dtemp);
2130 #else
2131 l_adj_systime(ts);
2132 return 1;
2133 #endif
2134 #else /* SLEWALWAYS */
2135 if (debug)
2136 return 1;
2137 LFPTOD(ts, dtemp);
2138 return step_systime(dtemp);
2139 #endif /* SLEWALWAYS */
2143 /* XXX ELIMINATE printserver similar in ntptrace.c, ntpdate.c */
2145 * printserver - print detail information for a server
2147 static void
2148 printserver(
2149 register struct server *pp,
2150 FILE *fp
2153 register int i;
2154 char junk[5];
2155 char *str;
2157 if (!debug) {
2158 (void) fprintf(fp, "server %s, stratum %d, offset %s, delay %s\n",
2159 stoa(&pp->srcadr), pp->stratum,
2160 lfptoa(&pp->offset, 6), fptoa((s_fp)pp->delay, 5));
2161 return;
2164 (void) fprintf(fp, "server %s, port %d\n",
2165 stoa(&pp->srcadr), ntohs(((struct sockaddr_in*)&(pp->srcadr))->sin_port));
2167 (void) fprintf(fp, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2168 pp->stratum, pp->precision,
2169 pp->leap & 0x2 ? '1' : '0',
2170 pp->leap & 0x1 ? '1' : '0',
2171 pp->trust);
2173 if (pp->stratum == 1) {
2174 junk[4] = 0;
2175 memmove(junk, (char *)&pp->refid, 4);
2176 str = junk;
2177 } else {
2178 str = stoa(&pp->srcadr);
2180 (void) fprintf(fp,
2181 "refid [%s], delay %s, dispersion %s\n",
2182 str, fptoa((s_fp)pp->delay, 5),
2183 ufptoa(pp->dispersion, 5));
2185 (void) fprintf(fp, "transmitted %d, in filter %d\n",
2186 pp->xmtcnt, pp->filter_nextpt);
2188 (void) fprintf(fp, "reference time: %s\n",
2189 prettydate(&pp->reftime));
2190 (void) fprintf(fp, "originate timestamp: %s\n",
2191 prettydate(&pp->org));
2192 (void) fprintf(fp, "transmit timestamp: %s\n",
2193 prettydate(&pp->xmt));
2195 (void) fprintf(fp, "filter delay: ");
2196 for (i = 0; i < NTP_SHIFT; i++) {
2197 (void) fprintf(fp, " %-8.8s", fptoa(pp->filter_delay[i], 5));
2198 if (i == (NTP_SHIFT>>1)-1)
2199 (void) fprintf(fp, "\n ");
2201 (void) fprintf(fp, "\n");
2203 (void) fprintf(fp, "filter offset:");
2204 for (i = 0; i < PEER_SHIFT; i++) {
2205 (void) fprintf(fp, " %-8.8s", lfptoa(&pp->filter_offset[i], 6));
2206 if (i == (PEER_SHIFT>>1)-1)
2207 (void) fprintf(fp, "\n ");
2209 (void) fprintf(fp, "\n");
2211 (void) fprintf(fp, "delay %s, dispersion %s\n",
2212 fptoa((s_fp)pp->delay, 5), ufptoa(pp->dispersion, 5));
2214 (void) fprintf(fp, "offset %s\n\n",
2215 lfptoa(&pp->offset, 6));
2218 #if !defined(HAVE_VSPRINTF)
2220 vsprintf(
2221 char *str,
2222 const char *fmt,
2223 va_list ap
2226 FILE f;
2227 int len;
2229 f._flag = _IOWRT+_IOSTRG;
2230 f._ptr = str;
2231 f._cnt = 32767;
2232 len = _doprnt(fmt, ap, &f);
2233 *f._ptr = 0;
2234 return (len);
2236 #endif
2238 #if 0
2239 /* override function in library since SA_RESTART makes ALL syscalls restart */
2240 #ifdef SA_RESTART
2241 void
2242 signal_no_reset(
2243 int sig,
2244 void (*func)()
2247 int n;
2248 struct sigaction vec;
2250 vec.sa_handler = func;
2251 sigemptyset(&vec.sa_mask);
2252 vec.sa_flags = 0;
2254 while (1)
2256 n = sigaction(sig, &vec, NULL);
2257 if (n == -1 && errno == EINTR)
2258 continue;
2259 break;
2261 if (n == -1)
2263 perror("sigaction");
2264 exit(1);
2267 #endif
2268 #endif
2270 #ifdef HAVE_NETINFO
2271 static ni_namelist *
2272 getnetinfoservers(void)
2274 ni_status status;
2275 void *domain;
2276 ni_id confdir;
2277 ni_namelist *namelist = (ni_namelist*)malloc(sizeof(ni_namelist));
2279 /* Find a time server in NetInfo */
2280 if ((status = ni_open(NULL, ".", &domain)) != NI_OK) return NULL;
2282 while (status = ni_pathsearch(domain, &confdir, NETINFO_CONFIG_DIR) == NI_NODIR) {
2283 void *next_domain;
2284 if (ni_open(domain, "..", &next_domain) != NI_OK) break;
2285 ni_free(domain);
2286 domain = next_domain;
2288 if (status != NI_OK) return NULL;
2290 NI_INIT(namelist);
2291 if (ni_lookupprop(domain, &confdir, "server", namelist) != NI_OK) {
2292 ni_namelist_free(namelist);
2293 free(namelist);
2294 return NULL;
2297 return(namelist);
2299 #endif
2301 #ifdef SYS_WINNT
2302 isc_boolean_t ntp_port_inuse(int af, u_short port)
2305 * Check if NTP socket is already in use on this system
2306 * This is only for Windows Systems, as they tend not to fail on the real bind() below
2309 SOCKET checksocket;
2310 struct sockaddr_in checkservice;
2311 checksocket = socket(af, SOCK_DGRAM, 0);
2312 if (checksocket == INVALID_SOCKET) {
2313 return (ISC_TRUE);
2316 checkservice.sin_family = (short) AF_INET;
2317 checkservice.sin_addr.s_addr = INADDR_LOOPBACK;
2318 checkservice.sin_port = htons(port);
2320 if (bind(checksocket, (struct sockaddr *)&checkservice,
2321 sizeof(checkservice)) == SOCKET_ERROR) {
2322 if ( WSAGetLastError() == WSAEADDRINUSE ){
2323 closesocket(checksocket);
2324 return (ISC_TRUE);
2327 closesocket(checksocket);
2328 return (ISC_FALSE);
2330 #endif