2 * ntpdate - set the time of day by polling one or more NTP servers
10 #include <netinfo/ni.h>
13 #include "ntp_machine.h"
17 #include "timevalops.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>
26 #include "isc/result.h"
27 #include "isc/sockaddr.h"
39 #ifdef HAVE_SYS_SIGNAL_H
40 # include <sys/signal.h>
42 #ifdef HAVE_SYS_IOCTL_H
43 # include <sys/ioctl.h>
45 #ifdef HAVE_SYS_RESOURCE_H
46 # include <sys/resource.h>
49 #include <arpa/inet.h>
56 /* select wants a zero structure ... */
57 struct timeval timeout = {0,0};
58 #elif defined(SYS_WINNT)
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).
63 struct sock_timeval timeout = {0,1000000/TIMER_HZ};
65 struct timeval timeout = {60,0};
69 #include <netinfo/ni.h>
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);
80 #endif /* SYS_WINNT */
83 * Scheduling priority we run at
86 # define NTPDATE_PRIO (-12)
88 # define NTPDATE_PRIO (100)
91 #ifdef HAVE_TIMER_CREATE
92 /* POSIX TIMERS - vxWorks doesn't have itimer - casey */
93 static timer_t ntpdate_timerid;
97 * Compatibility stuff for Version 2
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 */
110 s_char sys_precision; /* local clock precision (log2 s) */
113 * File descriptor masks etc. for call to select
117 int nbsock; /* the number of sockets used */
119 int fd_family[MAX_AF]; /* to remember the socket family */
121 struct pollfd fdmask[MAX_AF];
129 * Initializing flag. All async routines watch this and only do their
130 * thing when it is clear.
132 int initializing = 1;
135 * Alarm flag. Set when an alarm occurs
137 volatile int alarm_flag = 0;
142 int simple_query = 0;
145 * Unprivileged port flag.
152 char const *progname;
155 * Systemwide parameters and flags
157 int sys_samples = DEFSAMPLES; /* number of samples/server */
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 */
167 * The current internal time
169 u_long current_time = 0;
172 * Counter for keeping track of completed servers
174 int complete_servers = 0;
177 * File of encryption keys
182 #define KEYFILE "/etc/ntp.keys"
184 #define KEYFILE "%windir%\\ntp.keys"
185 # endif /* SYS_WINNT */
189 const char *key_file = KEYFILE;
191 char key_file_storage[MAX_PATH+1], *key_file ;
192 #endif /* SYS_WINNT */
195 * Miscellaneous flags
201 int ntpdatemain (int, char **);
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 *);
212 static void init_alarm (void);
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);
220 static int l_adj_systime (l_fp *);
221 static int l_step_systime (l_fp *);
223 static void printserver (struct server *, FILE *);
227 WORD wVersionRequested;
229 #endif /* SYS_WINNT */
231 #ifdef NO_MAIN_ALLOWED
232 CALL(ntpdate,"ntpdate",ntpdatemain);
243 * Initializing flag. All async routines watch this and only do their
244 * thing when it is clear.
249 * Alarm flag. Set when an alarm occurs
259 * Unprivileged port flag.
264 * Systemwide parameters and flags
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 */
273 * The current internal time
278 * Counter for keeping track of completed servers
280 complete_servers = 0;
288 static ni_namelist *getnetinfoservers (void);
292 * Main program. Initialize us and loop waiting for I/O and/or
295 #ifndef NO_MAIN_ALLOWED
302 return ntpdatemain (argc, argv);
304 #endif /* NO_MAIN_ALLOWED */
314 struct recvbuf *rbuf;
321 ni_namelist *netinfoservers;
324 key_file = key_file_storage;
326 if (!ExpandEnvironmentStrings(KEYFILE, key_file, MAX_PATH))
327 msyslog(LOG_ERR, "ExpandEnvironmentStrings(KEYFILE) failed: %m");
330 #endif /* SYS_WINNT */
332 #ifdef NO_MAIN_ALLOWED
336 init_lib(); /* sets up ipv4_works, ipv6_works */
338 /* Check to see if we have IPv6. Otherwise default to IPv4 */
340 ai_fam_templ = AF_INET;
347 * Decode argument list
349 while ((c = ntp_getopt(argc, argv, "46a:bBde:k:o:p:qst:uv")) != EOF)
353 ai_fam_templ = AF_INET;
356 ai_fam_templ = AF_INET6;
359 c = atoi(ntp_optarg);
360 sys_authenticate = 1;
375 if (!atolfp(ntp_optarg, &tmp)
377 (void) fprintf(stderr,
378 "%s: encryption delay %s is unlikely\n",
379 progname, ntp_optarg);
382 sys_authdelay = tmp.l_uf;
386 key_file = ntp_optarg;
389 sys_version = atoi(ntp_optarg);
392 c = atoi(ntp_optarg);
393 if (c <= 0 || c > NTP_SHIFT) {
394 (void) fprintf(stderr,
395 "%s: number of samples (%d) is invalid\n",
409 if (!atolfp(ntp_optarg, &tmp)) {
410 (void) fprintf(stderr,
411 "%s: timeout %s is undecodeable\n",
412 progname, ntp_optarg);
415 sys_timeout = ((LFPTOFP(&tmp) * TIMER_HZ)
417 sys_timeout = max(sys_timeout, MINTIMEOUT);
434 (void) fprintf(stderr,
435 "usage: %s [-46bBdqsuv] [-a key#] [-e delay] [-k file] [-p samples] [-o version#] [-t timeo] server ...\n",
440 if (debug || simple_query) {
442 static char buf[BUFSIZ];
443 setvbuf(stdout, buf, _IOLBF, BUFSIZ);
450 * Logging. Open the syslog if we have to
453 #if !defined (SYS_WINNT) && !defined (SYS_VXWORKS) && !defined SYS_CYGWIN32
455 openlog("ntpdate", LOG_PID);
459 # define LOG_NTP LOG_DAEMON
461 openlog("ntpdate", LOG_PID | LOG_NDELAY, LOG_NTP);
463 setlogmask(LOG_UPTO(LOG_DEBUG));
465 setlogmask(LOG_UPTO(LOG_INFO));
466 # endif /* LOG_DAEMON */
467 #endif /* SYS_WINNT */
470 if (debug || verbose)
471 msyslog(LOG_NOTICE, "%s", Version);
474 * Add servers we are going to be polling
477 netinfoservers = getnetinfoservers();
480 for ( ; ntp_optind < argc; ntp_optind++)
481 addserver(argv[ntp_optind]);
484 if (netinfoservers) {
485 if ( netinfoservers->ni_namelist_len &&
486 *netinfoservers->ni_namelist_val ) {
487 u_int servercount = 0;
488 while (servercount < netinfoservers->ni_namelist_len) {
489 if (debug) msyslog(LOG_DEBUG,
490 "Adding time server %s from NetInfo configuration.",
491 netinfoservers->ni_namelist_val[servercount]);
492 addserver(netinfoservers->ni_namelist_val[servercount++]);
495 ni_namelist_free(netinfoservers);
496 free(netinfoservers);
500 if (sys_numservers == 0) {
501 msyslog(LOG_ERR, "no servers can be used, exiting");
506 * Initialize the time of day routines and the I/O subsystem
508 if (sys_authenticate) {
510 if (!authreadkeys(key_file)) {
511 msyslog(LOG_ERR, "no key file <%s>, exiting", key_file);
514 authtrust(sys_authkey, 1);
515 if (!authistrusted(sys_authkey)) {
516 msyslog(LOG_ERR, "authentication key %lu unknown",
517 (unsigned long) sys_authkey);
528 taskPrioritySet( taskIdSelf(), NTPDATE_PRIO);
530 #if defined(HAVE_ATT_NICE)
533 #if defined(HAVE_BSD_NICE)
534 (void) setpriority(PRIO_PROCESS, 0, NTPDATE_PRIO);
541 while (complete_servers < sys_numservers) {
543 struct pollfd* rdfdes;
550 if (alarm_flag) { /* alarmed? */
554 tot_recvbufs = full_recvbuffs(); /* get received buffers */
556 if (!was_alarmed && tot_recvbufs == 0) {
558 * Nothing to do. Wait for something.
561 nfound = poll(rdfdes, (unsigned int)nbsock, timeout.tv_sec * 1000);
564 nfound = select(maxfd, &rdfdes, NULL, NULL,
569 else if (nfound == SOCKET_ERROR)
574 if (WSAGetLastError() != WSAEINTR)
583 } else if (errno != 0) {
587 "poll(): nfound = %d, error: %m",
589 "select(): nfound = %d, error: %m",
594 if (alarm_flag) { /* alarmed? */
598 tot_recvbufs = full_recvbuffs(); /* get received buffers */
602 * Out here, signals are unblocked. Call receive
603 * procedure for each incoming packet.
605 rbuf = get_full_recv_buffer();
610 rbuf = get_full_recv_buffer();
614 * Call timer to process any timeouts
627 * When we get here we've completed the polling of all servers.
628 * Adjust the clock, then exit.
635 timer_delete(ntpdate_timerid);
638 return clock_adjust();
643 * transmit - transmit a packet to the given server, or mark it completed.
644 * This is called by the timeout routine and by the receive
649 register struct server *server
655 printf("transmit(%s)\n", stoa(&server->srcadr));
657 if (server->filter_nextpt < server->xmtcnt) {
660 * Last message to this server timed out. Shift
661 * zeros into the filter.
664 server_data(server, 0, &ts, 0);
667 if ((int)server->filter_nextpt >= sys_samples) {
669 * Got all the data we need. Mark this guy
670 * completed and return.
672 server->event_time = 0;
678 * If we're here, send another message to the server. Fill in
679 * the packet and let 'er rip.
681 xpkt.li_vn_mode = PKT_LI_VN_MODE(LEAP_NOTINSYNC,
682 sys_version, MODE_CLIENT);
683 xpkt.stratum = STRATUM_TO_PKT(STRATUM_UNSPEC);
684 xpkt.ppoll = NTP_MINPOLL;
685 xpkt.precision = NTPDATE_PRECISION;
686 xpkt.rootdelay = htonl(NTPDATE_DISTANCE);
687 xpkt.rootdisp = htonl(NTPDATE_DISP);
688 xpkt.refid = htonl(NTPDATE_REFID);
689 L_CLR(&xpkt.reftime);
694 * Determine whether to authenticate or not. If so,
695 * fill in the extended part of the packet and do it.
696 * If not, just timestamp it and send it away.
698 if (sys_authenticate) {
701 xpkt.exten[0] = htonl(sys_authkey);
702 get_systime(&server->xmt);
703 L_ADDUF(&server->xmt, sys_authdelay);
704 HTONL_FP(&server->xmt, &xpkt.xmt);
705 len = authencrypt(sys_authkey, (u_int32 *)&xpkt, LEN_PKT_NOMAC);
706 sendpkt(&server->srcadr, &xpkt, (int)(LEN_PKT_NOMAC + len));
709 printf("transmit auth to %s\n",
710 stoa(&server->srcadr));
712 get_systime(&(server->xmt));
713 HTONL_FP(&server->xmt, &xpkt.xmt);
714 sendpkt(&server->srcadr, &xpkt, LEN_PKT_NOMAC);
717 printf("transmit to %s\n", stoa(&server->srcadr));
721 * Update the server timeout and transmit count
723 server->event_time = current_time + sys_timeout;
729 * receive - receive and process an incoming frame
733 struct recvbuf *rbufp
736 register struct pkt *rpkt;
737 register struct server *server;
747 printf("receive(%s)\n", stoa(&rbufp->recv_srcadr));
749 * Check to see if the packet basically looks like something
752 if (rbufp->recv_length == LEN_PKT_NOMAC)
754 else if (rbufp->recv_length >= (int)LEN_PKT_NOMAC)
758 printf("receive: packet length %d\n",
760 return; /* funny length packet */
763 rpkt = &(rbufp->recv_pkt);
764 if (PKT_VERSION(rpkt->li_vn_mode) < NTP_OLDVERSION ||
765 PKT_VERSION(rpkt->li_vn_mode) > NTP_VERSION) {
769 if ((PKT_MODE(rpkt->li_vn_mode) != MODE_SERVER
770 && PKT_MODE(rpkt->li_vn_mode) != MODE_PASSIVE)
771 || rpkt->stratum >= STRATUM_UNSPEC) {
773 printf("receive: mode %d stratum %d\n",
774 PKT_MODE(rpkt->li_vn_mode), rpkt->stratum);
779 * So far, so good. See if this is from a server we know.
781 server = findserver(&(rbufp->recv_srcadr));
782 if (server == NULL) {
784 printf("receive: server not found\n");
789 * Decode the org timestamp and make sure we're getting a response
790 * to our last request.
792 NTOHL_FP(&rpkt->org, &org);
793 if (!L_ISEQU(&org, &server->xmt)) {
795 printf("receive: pkt.org and peer.xmt differ\n");
800 * Check out the authenticity if we're doing that.
802 if (!sys_authenticate)
808 printf("receive: rpkt keyid=%ld sys_authkey=%ld decrypt=%ld\n",
809 (long int)ntohl(rpkt->exten[0]), (long int)sys_authkey,
810 (long int)authdecrypt(sys_authkey, (u_int32 *)rpkt,
811 LEN_PKT_NOMAC, (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)));
813 if (has_mac && ntohl(rpkt->exten[0]) == sys_authkey &&
814 authdecrypt(sys_authkey, (u_int32 *)rpkt, LEN_PKT_NOMAC,
815 (size_t)(rbufp->recv_length - LEN_PKT_NOMAC)))
818 printf("receive: authentication %s\n",
819 is_authentic ? "passed" : "failed");
826 * Check for a KoD (rate limiting) response, cease and decist.
828 if (LEAP_NOTINSYNC == PKT_LEAP(rpkt->li_vn_mode) &&
829 STRATUM_PKT_UNSPEC == rpkt->stratum &&
830 !memcmp("RATE", &rpkt->refid, 4)) {
831 msyslog(LOG_ERR, "%s rate limit response from server.",
832 stoa(&rbufp->recv_srcadr));
833 server->event_time = 0;
839 * Looks good. Record info from the packet.
841 server->leap = PKT_LEAP(rpkt->li_vn_mode);
842 server->stratum = PKT_TO_STRATUM(rpkt->stratum);
843 server->precision = rpkt->precision;
844 server->rootdelay = ntohl(rpkt->rootdelay);
845 server->rootdisp = ntohl(rpkt->rootdisp);
846 server->refid = rpkt->refid;
847 NTOHL_FP(&rpkt->reftime, &server->reftime);
848 NTOHL_FP(&rpkt->rec, &rec);
849 NTOHL_FP(&rpkt->xmt, &server->org);
852 * Make sure the server is at least somewhat sane. If not, try
855 if (L_ISZERO(&rec) || !L_ISHIS(&server->org, &rec)) {
856 server->event_time = current_time + sys_timeout;
861 * Calculate the round trip delay (di) and the clock offset (ci).
862 * We use the equations (reordered from those in the spec):
864 * d = (t2 - t3) - (t1 - t0)
865 * c = ((t2 - t3) + (t1 - t0)) / 2
867 t10 = server->org; /* pkt.xmt == t1 */
868 L_SUB(&t10, &rbufp->recv_time); /* recv_time == t0*/
870 t23 = rec; /* pkt.rec == t2 */
871 L_SUB(&t23, &org); /* pkt->org == t3 */
873 /* now have (t2 - t3) and (t0 - t1). Calculate (ci) and (di) */
875 * Calculate (ci) = ((t1 - t0) / 2) + ((t2 - t3) / 2)
876 * For large offsets this may prevent an overflow on '+'
885 * Calculate di in t23 in full precision, then truncate
892 printf("offset: %s, delay %s\n", lfptoa(&ci, 6), fptoa(di, 5));
894 di += (FP_SECOND >> (-(int)NTPDATE_PRECISION))
895 + (FP_SECOND >> (-(int)server->precision)) + NTP_MAXSKW;
897 if (di <= 0) { /* value still too raunchy to use? */
901 di = max(di, NTP_MINDIST);
905 * Shift this data in, then schedule another transmit.
907 server_data(server, (s_fp) di, &ci, 0);
909 if ((int)server->filter_nextpt >= sys_samples) {
911 * Got all the data we need. Mark this guy
912 * completed and return.
914 server->event_time = 0;
919 server->event_time = current_time + sys_timeout;
924 * server_data - add a sample to the server's filter registers
928 register struct server *server,
936 i = server->filter_nextpt;
938 server->filter_delay[i] = d;
939 server->filter_offset[i] = *c;
940 server->filter_soffset[i] = LFPTOFP(c);
941 server->filter_error[i] = e;
942 server->filter_nextpt = (u_short)(i + 1);
948 * clock_filter - determine a server's delay, dispersion and offset
952 register struct server *server
959 * Sort indices into increasing delay order
961 for (i = 0; i < sys_samples; i++)
964 for (i = 0; i < (sys_samples-1); i++) {
965 for (j = i+1; j < sys_samples; j++) {
966 if (server->filter_delay[ord[j]] == 0)
968 if (server->filter_delay[ord[i]] == 0
969 || (server->filter_delay[ord[i]]
970 > server->filter_delay[ord[j]])) {
981 * Now compute the dispersion, and assign values to delay and
982 * offset. If there are no samples in the register, delay and
983 * offset go to zero and dispersion is set to the maximum.
985 if (server->filter_delay[ord[0]] == 0) {
987 L_CLR(&server->offset);
989 server->dispersion = PEER_MAXDISP;
993 server->delay = server->filter_delay[ord[0]];
994 server->offset = server->filter_offset[ord[0]];
995 server->soffset = LFPTOFP(&server->offset);
996 server->dispersion = 0;
997 for (i = 1; i < sys_samples; i++) {
998 if (server->filter_delay[ord[i]] == 0)
1001 d = server->filter_soffset[ord[i]]
1002 - server->filter_soffset[ord[0]];
1005 if (d > PEER_MAXDISP)
1009 * XXX This *knows* PEER_FILTER is 1/2
1011 server->dispersion += (u_fp)(d) >> i;
1021 * clock_select - select the pick-of-the-litter clock from the samples
1024 static struct server *
1027 struct server *server;
1035 s_fp local_threshold;
1036 struct server *server_list[NTP_MAXCLOCK];
1037 u_fp server_badness[NTP_MAXCLOCK];
1038 struct server *sys_server;
1041 * This first chunk of code is supposed to go through all
1042 * servers we know about to find the NTP_MAXLIST servers which
1043 * are most likely to succeed. We run through the list
1044 * doing the sanity checks and trying to insert anyone who
1045 * looks okay. We are at all times aware that we should
1046 * only keep samples from the top two strata and we only need
1047 * NTP_MAXLIST of them.
1049 nlist = 0; /* none yet */
1050 for (server = sys_servers; server != NULL; server = server->next_server) {
1051 if (server->delay == 0) {
1053 printf("%s: Server dropped: no data\n", ntoa(&server->srcadr));
1054 continue; /* no data */
1056 if (server->stratum > NTP_INFIN) {
1058 printf("%s: Server dropped: strata too high\n", ntoa(&server->srcadr));
1059 continue; /* stratum no good */
1061 if (server->delay > NTP_MAXWGT) {
1063 printf("%s: Server dropped: server too far away\n",
1064 ntoa(&server->srcadr));
1065 continue; /* too far away */
1067 if (server->leap == LEAP_NOTINSYNC) {
1069 printf("%s: Server dropped: Leap not in sync\n", ntoa(&server->srcadr));
1070 continue; /* he's in trouble */
1072 if (!L_ISHIS(&server->org, &server->reftime)) {
1074 printf("%s: Server dropped: server is very broken\n",
1075 ntoa(&server->srcadr));
1076 continue; /* very broken host */
1078 if ((server->org.l_ui - server->reftime.l_ui)
1081 printf("%s: Server dropped: Server has gone too long without sync\n",
1082 ntoa(&server->srcadr));
1083 continue; /* too long without sync */
1085 if (server->trust != 0) {
1087 printf("%s: Server dropped: Server is untrusted\n",
1088 ntoa(&server->srcadr));
1093 * This one seems sane. Find where he belongs
1096 d = server->dispersion + server->dispersion;
1097 for (i = 0; i < nlist; i++)
1098 if (server->stratum <= server_list[i]->stratum)
1100 for ( ; i < nlist; i++) {
1101 if (server->stratum < server_list[i]->stratum)
1103 if (d < (s_fp) server_badness[i])
1108 * If i points past the end of the list, this
1109 * guy is a loser, else stick him in.
1111 if (i >= NTP_MAXLIST)
1113 for (j = nlist; j > i; j--)
1114 if (j < NTP_MAXLIST) {
1115 server_list[j] = server_list[j-1];
1117 = server_badness[j-1];
1120 server_list[i] = server;
1121 server_badness[i] = d;
1122 if (nlist < NTP_MAXLIST)
1127 * Got the five-or-less best. Cut the list where the number of
1128 * strata exceeds two.
1131 for (i = 1; i < nlist; i++)
1132 if (server_list[i]->stratum > server_list[i-1]->stratum) {
1141 * Whew! What we should have by now is 0 to 5 candidates for
1142 * the job of syncing us. If we have none, we're out of luck.
1143 * If we have one, he's a winner. If we have more, do falseticker
1149 else if (1 == nlist) {
1150 sys_server = server_list[0];
1153 * Re-sort by stratum, bdelay estimate quality and
1156 for (i = 0; i < nlist-1; i++)
1157 for (j = i+1; j < nlist; j++) {
1158 if (server_list[i]->stratum <
1159 server_list[j]->stratum)
1160 /* already sorted by stratum */
1162 if (server_list[i]->delay <
1163 server_list[j]->delay)
1165 server = server_list[i];
1166 server_list[i] = server_list[j];
1167 server_list[j] = server;
1171 * Calculate the fixed part of the dispersion limit
1173 local_threshold = (FP_SECOND >> (-(int)NTPDATE_PRECISION))
1177 * Now drop samples until we're down to one.
1180 for (k = 0; k < nlist; k++) {
1181 server_badness[k] = 0;
1182 for (j = 0; j < nlist; j++) {
1183 if (j == k) /* with self? */
1185 d = server_list[j]->soffset -
1186 server_list[k]->soffset;
1187 if (d < 0) /* abs value */
1190 * XXX This code *knows* that
1193 for (i = 0; i < j; i++)
1194 d = (d>>1) + (d>>2);
1195 server_badness[k] += d;
1200 * We now have an array of nlist badness
1201 * coefficients. Find the badest. Find
1202 * the minimum precision while we're at
1206 n = server_list[0]->precision;;
1207 for (j = 1; j < nlist; j++) {
1208 if (server_badness[j] >= server_badness[i])
1210 if (n > server_list[j]->precision)
1211 n = server_list[j]->precision;
1215 * i is the index of the server with the worst
1216 * dispersion. If his dispersion is less than
1217 * the threshold, stop now, else delete him and
1218 * continue around again.
1220 if ( (s_fp) server_badness[i] < (local_threshold
1221 + (FP_SECOND >> (-n))))
1223 for (j = i + 1; j < nlist; j++)
1224 server_list[j-1] = server_list[j];
1229 * What remains is a list of less than 5 servers. Take
1232 sys_server = server_list[0];
1236 * That's it. Return our server.
1243 * clock_adjust - process what we've received, and adjust the time
1244 * if we got anything decent.
1249 register struct server *sp, *server;
1253 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1255 server = clock_select();
1257 if (debug || simple_query) {
1258 for (sp = sys_servers; sp != NULL; sp = sp->next_server)
1259 printserver(sp, stdout);
1264 "no server suitable for synchronization found");
1270 } else if (never_step) {
1273 absoffset = server->soffset;
1275 absoffset = -absoffset;
1276 dostep = (absoffset >= NTPDATE_THRESHOLD || absoffset < 0);
1280 if (simple_query || debug || l_step_systime(&server->offset)){
1281 msyslog(LOG_NOTICE, "step time server %s offset %s sec",
1282 stoa(&server->srcadr),
1283 lfptoa(&server->offset, 6));
1287 if (simple_query || l_adj_systime(&server->offset)) {
1288 msyslog(LOG_NOTICE, "adjust time server %s offset %s sec",
1289 stoa(&server->srcadr),
1290 lfptoa(&server->offset, 6));
1293 /* The NT SetSystemTimeAdjustment() call achieves slewing by
1294 * changing the clock frequency. This means that we cannot specify
1295 * it to slew the clock by a definite amount and then stop like
1296 * the Unix adjtime() routine. We can technically adjust the clock
1297 * frequency, have ntpdate sleep for a while, and then wake
1298 * up and reset the clock frequency, but this might cause some
1299 * grief if the user attempts to run ntpd immediately after
1300 * ntpdate and the socket is in use.
1302 printf("\nThe -b option is required by ntpdate on Windows NT platforms\n");
1304 #endif /* SYS_WINNT */
1311 * is_unreachable - check to see if we have a route to given destination
1315 is_reachable (sockaddr_u *dst)
1319 sockfd = socket(AF(dst), SOCK_DGRAM, 0);
1324 if (connect(sockfd, &dst->sa, SOCKLEN(dst))) {
1325 closesocket(sockfd);
1328 closesocket(sockfd);
1334 /* XXX ELIMINATE: merge BIG slew into adj_systime in lib/systime.c */
1336 * addserver - determine a server's address and allocate a new structure
1344 register struct server *server;
1345 /* Address infos structure to store result of getaddrinfo */
1346 struct addrinfo *addrResult, *ptr;
1347 /* Address infos structure to store hints for getaddrinfo */
1348 struct addrinfo hints;
1349 /* Error variable for getaddrinfo */
1355 strlcpy(service, "ntp", sizeof(service));
1357 /* Get host address. Looking for UDP datagram connection. */
1359 hints.ai_family = ai_fam_templ;
1360 hints.ai_socktype = SOCK_DGRAM;
1364 printf("Looking for host %s and service %s\n", serv, service);
1367 error = getaddrinfo(serv, service, &hints, &addrResult);
1369 /* Conduct more refined error analysis */
1370 if (error == EAI_FAIL || error == EAI_AGAIN){
1371 /* Name server is unusable. Exit after failing on the
1372 first server, in order to shorten the timeout caused
1373 by waiting for resolution of several servers */
1374 fprintf(stderr, "Exiting, name server cannot be used: %s (%d)",
1375 gai_strerror(error), error);
1376 msyslog(LOG_ERR, "name server cannot be used: %s (%d)",
1377 gai_strerror(error), error);
1380 fprintf(stderr, "Error resolving %s: %s (%d)\n", serv,
1381 gai_strerror(error), error);
1382 msyslog(LOG_ERR, "Can't find host %s: %s (%d)", serv,
1383 gai_strerror(error), error);
1389 INSIST(addrResult->ai_addrlen <= sizeof(addr));
1390 memcpy(&addr, addrResult->ai_addr, addrResult->ai_addrlen);
1391 fprintf(stderr, "host found : %s\n", stohost(&addr));
1395 /* We must get all returned server in case the first one fails */
1396 for (ptr = addrResult; ptr != NULL; ptr = ptr->ai_next) {
1398 INSIST(ptr->ai_addrlen <= sizeof(addr));
1399 memcpy(&addr, ptr->ai_addr, ptr->ai_addrlen);
1400 if (is_reachable(&addr)) {
1401 server = emalloc_zero(sizeof(*server));
1402 memcpy(&server->srcadr, ptr->ai_addr, ptr->ai_addrlen);
1403 server->event_time = ++sys_numservers;
1404 if (sys_servers == NULL)
1405 sys_servers = server;
1409 for (sp = sys_servers; sp->next_server != NULL;
1410 sp = sp->next_server)
1412 sp->next_server = server;
1417 freeaddrinfo(addrResult);
1422 * findserver - find a server in the list given its address
1423 * ***(For now it isn't totally AF-Independant, to check later..)
1425 static struct server *
1430 struct server *server;
1431 struct server *mc_server;
1434 if (SRCPORT(addr) != NTP_PORT)
1437 for (server = sys_servers; server != NULL;
1438 server = server->next_server) {
1439 if (SOCK_EQ(addr, &server->srcadr))
1442 if (AF(addr) == AF(&server->srcadr)) {
1443 if (IS_MCAST(&server->srcadr))
1448 if (mc_server != NULL) {
1452 if (mc_server->event_time != 0) {
1453 mc_server->event_time = 0;
1457 server = emalloc_zero(sizeof(*server));
1459 server->srcadr = *addr;
1461 server->event_time = ++sys_numservers;
1463 for (sp = sys_servers; sp->next_server != NULL;
1464 sp = sp->next_server)
1466 sp->next_server = server;
1474 * timer - process a timer interrupt
1479 struct server *server;
1482 * Bump the current idea of the time
1487 * Search through the server list looking for guys
1488 * who's event timers have expired. Give these to
1489 * the transmit routine.
1491 for (server = sys_servers; server != NULL;
1492 server = server->next_server) {
1493 if (server->event_time != 0
1494 && server->event_time <= current_time)
1501 * The code duplication in the following subroutine sucks, but
1502 * we need to appease ansi2knr.
1507 * alarming - record the occurance of an alarm interrupt
1516 #else /* SYS_WINNT follows */
1518 alarming(UINT uTimerID, UINT uMsg, DWORD dwUser, DWORD dw1, DWORD dw2)
1520 UNUSED_ARG(uTimerID); UNUSED_ARG(uMsg); UNUSED_ARG(dwUser);
1521 UNUSED_ARG(dw1); UNUSED_ARG(dw2);
1527 callTimeEndPeriod(void)
1529 timeEndPeriod( wTimerRes );
1532 #endif /* SYS_WINNT */
1536 * init_alarm - set up the timer interrupt
1542 # ifdef HAVE_TIMER_CREATE
1543 struct itimerspec its;
1545 struct itimerval itv;
1547 #else /* SYS_WINNT follows */
1551 TOKEN_PRIVILEGES tkp;
1553 #endif /* SYS_WINNT */
1558 # ifdef HAVE_TIMER_CREATE
1560 /* this code was put in as setitimer() is non existant this us the
1561 * POSIX "equivalents" setup - casey
1563 /* ntpdate_timerid is global - so we can kill timer later */
1564 if (timer_create (CLOCK_REALTIME, NULL, &ntpdate_timerid) ==
1572 fprintf (stderr, "init_alarm(): timer_create (...) FAILED\n");
1577 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1578 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1580 signal_no_reset(SIGALRM, alarming);
1581 its.it_interval.tv_sec = 0;
1582 its.it_value.tv_sec = 0;
1583 its.it_interval.tv_nsec = 1000000000/TIMER_HZ;
1584 its.it_value.tv_nsec = 1000000000/(TIMER_HZ<<1);
1585 timer_settime(ntpdate_timerid, 0 /* !TIMER_ABSTIME */, &its, NULL);
1586 # else /* !HAVE_TIMER_CREATE follows */
1588 * Set up the alarm interrupt. The first comes 1/(2*TIMER_HZ)
1589 * seconds from now and they continue on every 1/TIMER_HZ seconds.
1591 signal_no_reset(SIGALRM, alarming);
1592 itv.it_interval.tv_sec = 0;
1593 itv.it_value.tv_sec = 0;
1594 itv.it_interval.tv_usec = 1000000/TIMER_HZ;
1595 itv.it_value.tv_usec = 1000000/(TIMER_HZ<<1);
1597 setitimer(ITIMER_REAL, &itv, NULL);
1598 # endif /* !HAVE_TIMER_CREATE */
1599 #else /* SYS_WINNT follows */
1603 * Get privileges needed for fiddling with the clock
1606 /* get the current process token handle */
1607 if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) {
1608 msyslog(LOG_ERR, "OpenProcessToken failed: %m");
1611 /* get the LUID for system-time privilege. */
1612 LookupPrivilegeValue(NULL, SE_SYSTEMTIME_NAME, &tkp.Privileges[0].Luid);
1613 tkp.PrivilegeCount = 1; /* one privilege to set */
1614 tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1615 /* get set-time privilege for this process. */
1616 AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,(PTOKEN_PRIVILEGES) NULL, 0);
1617 /* cannot test return value of AdjustTokenPrivileges. */
1618 if (GetLastError() != ERROR_SUCCESS)
1619 msyslog(LOG_ERR, "AdjustTokenPrivileges failed: %m");
1622 * Set up timer interrupts for every 2**EVENT_TIMEOUT seconds
1623 * Under Win/NT, expiry of timer interval leads to invocation
1624 * of a callback function (on a different thread) rather than
1625 * generating an alarm signal
1628 /* determine max and min resolution supported */
1629 if(timeGetDevCaps(&tc, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
1630 msyslog(LOG_ERR, "timeGetDevCaps failed: %m");
1633 wTimerRes = min(max(tc.wPeriodMin, TARGET_RESOLUTION), tc.wPeriodMax);
1634 /* establish the minimum timer resolution that we'll use */
1635 timeBeginPeriod(wTimerRes);
1636 atexit(callTimeEndPeriod);
1638 /* start the timer event */
1639 wTimerID = timeSetEvent(
1640 (UINT) (1000/TIMER_HZ), /* Delay */
1641 wTimerRes, /* Resolution */
1642 (LPTIMECALLBACK) alarming, /* Callback function */
1643 (DWORD) dwUser, /* User data */
1644 TIME_PERIODIC); /* Event type (periodic) */
1645 if (wTimerID == 0) {
1646 msyslog(LOG_ERR, "timeSetEvent failed: %m");
1649 #endif /* SYS_WINNT */
1656 * We do asynchronous input using the SIGIO facility. A number of
1657 * recvbuf buffers are preallocated for input. In the signal
1658 * handler we poll to see if the socket is ready and read the
1659 * packets from it into the recvbuf's along with a time stamp and
1660 * an indication of the source host and the interface it was received
1661 * through. This allows us to get as accurate receive time stamps
1662 * as possible independent of other processing going on.
1664 * We allocate a number of recvbufs equal to the number of servers
1665 * plus 2. This should be plenty.
1670 * init_io - initialize I/O data and open socket
1675 struct addrinfo *res, *ressave;
1676 struct addrinfo hints;
1681 int check_ntp_port_in_use = !debug && !simple_query && !unpriv_port;
1684 * Init buffer free list and stat counters
1686 init_recvbuff(sys_numservers + 2);
1692 strlcpy(service, "ntp", sizeof(service));
1695 * Init hints addrinfo structure
1698 hints.ai_family = ai_fam_templ;
1699 hints.ai_flags = AI_PASSIVE;
1700 hints.ai_socktype = SOCK_DGRAM;
1702 if (getaddrinfo(NULL, service, &hints, &res) != 0) {
1703 msyslog(LOG_ERR, "getaddrinfo() failed: %m");
1709 if (check_ntp_port_in_use && ntp_port_inuse(AF_INET, NTP_PORT)){
1710 msyslog(LOG_ERR, "the NTP socket is in use, exiting: %m");
1715 /* Remember the address of the addrinfo structure chain */
1719 * For each structure returned, open and bind socket
1721 for(nbsock = 0; (nbsock < MAX_AF) && res ; res = res->ai_next) {
1722 /* create a datagram (UDP) socket */
1723 fd[nbsock] = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
1724 if (fd[nbsock] == SOCKET_ERROR) {
1726 if (errno == EPROTONOSUPPORT || errno == EAFNOSUPPORT ||
1727 errno == EPFNOSUPPORT)
1729 int err = WSAGetLastError();
1730 if (err == WSAEPROTONOSUPPORT || err == WSAEAFNOSUPPORT ||
1731 err == WSAEPFNOSUPPORT)
1734 msyslog(LOG_ERR, "socket() failed: %m");
1738 /* set socket to reuse address */
1739 if (setsockopt(fd[nbsock], SOL_SOCKET, SO_REUSEADDR, (void*) &optval, sizeof(optval)) < 0) {
1740 msyslog(LOG_ERR, "setsockopt() SO_REUSEADDR failed: %m");
1745 /* Restricts AF_INET6 socket to IPv6 communications (see RFC 2553bis-03) */
1746 if (res->ai_family == AF_INET6)
1747 if (setsockopt(fd[nbsock], IPPROTO_IPV6, IPV6_V6ONLY, (void*) &optval, sizeof(optval)) < 0) {
1748 msyslog(LOG_ERR, "setsockopt() IPV6_V6ONLY failed: %m");
1754 /* Remember the socket family in fd_family structure */
1755 fd_family[nbsock] = res->ai_family;
1758 * bind the socket to the NTP port
1760 if (check_ntp_port_in_use) {
1762 INSIST(res->ai_addrlen <= sizeof(addr));
1763 memcpy(&addr, res->ai_addr, res->ai_addrlen);
1764 rc = bind(fd[nbsock], &addr.sa, SOCKLEN(&addr));
1766 if (EADDRINUSE == socket_errno())
1767 msyslog(LOG_ERR, "the NTP socket is in use, exiting");
1769 msyslog(LOG_ERR, "bind() fails: %m");
1775 fdmask[nbsock].fd = fd[nbsock];
1776 fdmask[nbsock].events = POLLIN;
1778 FD_SET(fd[nbsock], &fdmask);
1779 if (maxfd < fd[nbsock]+1) {
1780 maxfd = fd[nbsock]+1;
1792 if (ioctl(fd[nbsock],FIONBIO, &on) == ERROR) {
1793 msyslog(LOG_ERR, "ioctl(FIONBIO) fails: %m");
1797 # else /* not SYS_VXWORKS */
1798 # if defined(O_NONBLOCK)
1799 if (fcntl(fd[nbsock], F_SETFL, O_NONBLOCK) < 0) {
1800 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1804 # else /* not O_NONBLOCK */
1805 # if defined(FNDELAY)
1806 if (fcntl(fd[nbsock], F_SETFL, FNDELAY) < 0) {
1807 msyslog(LOG_ERR, "fcntl(FNDELAY|FASYNC) fails: %m");
1811 # else /* FNDELAY */
1812 # include "Bletch: Need non blocking I/O"
1813 # endif /* FNDELAY */
1814 # endif /* not O_NONBLOCK */
1815 # endif /* SYS_VXWORKS */
1816 #else /* SYS_WINNT */
1817 if (ioctlsocket(fd[nbsock], FIONBIO, (u_long *) &on) == SOCKET_ERROR) {
1818 msyslog(LOG_ERR, "ioctlsocket(FIONBIO) fails: %m");
1821 #endif /* SYS_WINNT */
1824 freeaddrinfo(ressave);
1828 * sendpkt - send a packet to the specified destination
1839 SOCKET sock = INVALID_SOCKET;
1843 #endif /* SYS_WINNT */
1845 /* Find a local family compatible socket to send ntp packet to ntp server */
1846 for(i = 0; (i < MAX_AF); i++) {
1847 if(AF(dest) == fd_family[i]) {
1853 if (INVALID_SOCKET == sock) {
1854 msyslog(LOG_ERR, "cannot find family compatible socket to send ntp packet");
1859 cc = sendto(sock, (char *)pkt, len, 0, (struct sockaddr *)dest,
1862 if (SOCKET_ERROR == cc) {
1864 if (errno != EWOULDBLOCK && errno != ENOBUFS)
1866 err = WSAGetLastError();
1867 if (err != WSAEWOULDBLOCK && err != WSAENOBUFS)
1868 #endif /* SYS_WINNT */
1869 msyslog(LOG_ERR, "sendto(%s): %m", stohost(dest));
1875 * input_handler - receive packets asynchronously
1881 register struct recvbuf *rb;
1882 struct sock_timeval tvzero;
1883 GETSOCKNAME_SOCKLEN_TYPE fromlen;
1887 struct pollfd fds[MAX_AF];
1894 * Do a poll to see if we have data
1897 tvzero.tv_sec = tvzero.tv_usec = 0;
1899 memcpy(fds, fdmask, sizeof(fdmask));
1900 n = poll(fds, (unsigned int)nbsock, tvzero.tv_sec * 1000);
1903 * Determine which socket received data
1906 for(i=0; i < nbsock; i++) {
1907 if(fds[i].revents & POLLIN) {
1915 n = select(maxfd, &fds, NULL, NULL, &tvzero);
1918 * Determine which socket received data
1921 for(i=0; i < nbsock; i++) {
1922 if(FD_ISSET(fd[i], &fds)) {
1931 * If nothing to do, just return. If an error occurred,
1932 * complain and return. If we've got some, freeze a
1943 "select() error: %m"
1951 * Get a buffer and read the frame. If we
1952 * haven't got a buffer, or this is received
1953 * on the wild card socket, just dump the packet.
1955 if (initializing || free_recvbuffs() == 0) {
1960 (void) read(fdc, buf, sizeof buf);
1962 /* NT's _read does not operate on nonblocking sockets
1963 * either recvfrom or ReadFile() has to be used here.
1964 * ReadFile is used in [ntpd]ntp_intres() and ntpdc,
1965 * just to be different use recvfrom() here
1967 recvfrom(fdc, buf, sizeof(buf), 0, (struct sockaddr *)0, NULL);
1968 #endif /* SYS_WINNT */
1972 rb = get_free_recv_buffer();
1974 fromlen = sizeof(rb->recv_srcadr);
1975 rb->recv_length = recvfrom(fdc, (char *)&rb->recv_pkt,
1976 sizeof(rb->recv_pkt), 0,
1977 (struct sockaddr *)&rb->recv_srcadr, &fromlen);
1978 if (rb->recv_length == -1) {
1984 * Got one. Mark how and when it got here,
1985 * put it on the full list.
1988 add_full_recv_buffer(rb);
1993 #if !defined SYS_WINNT && !defined SYS_CYGWIN32
1995 * adj_systime - do a big long slew of the system time
2002 struct timeval adjtv, oadjtv;
2010 * Take the absolute value of the offset
2013 if (L_ISNEG(&offset)) {
2020 * Calculate the overshoot. XXX N.B. This code *knows*
2021 * ADJ_OVERSHOOT is 1/2.
2024 L_RSHIFTU(&overshoot);
2025 if (overshoot.l_ui != 0 || (overshoot.l_uf > ADJ_MAXOVERSHOOT)) {
2027 overshoot.l_uf = ADJ_MAXOVERSHOOT;
2029 L_ADD(&offset, &overshoot);
2031 TSTOTV(&offset, &adjtv);
2034 adjtv.tv_sec = -adjtv.tv_sec;
2035 adjtv.tv_usec = -adjtv.tv_usec;
2038 if (adjtv.tv_usec != 0 && !debug) {
2039 if (adjtime(&adjtv, &oadjtv) < 0) {
2040 msyslog(LOG_ERR, "Can't adjust the time of day: %m");
2046 #endif /* SYS_WINNT */
2050 * This fuction is not the same as lib/systime step_systime!!!
2065 if (debug) return 1;
2067 * Take the absolute value of the offset
2070 if (L_ISNEG(&ftmp)) {
2076 if (ftmp.l_ui >= 3) { /* Step it and slew - we might win */
2078 n = step_systime(dtemp);
2087 * Just add adjustment into the current offset. The update
2088 * routine will take care of bringing the system clock into
2094 #ifdef FORCE_NTPDATE_STEP
2096 return step_systime(dtemp);
2101 #else /* SLEWALWAYS */
2105 return step_systime(dtemp);
2106 #endif /* SLEWALWAYS */
2110 /* XXX ELIMINATE printserver similar in ntptrace.c, ntpdate.c */
2112 * printserver - print detail information for a server
2116 register struct server *pp,
2125 (void) fprintf(fp, "server %s, stratum %d, offset %s, delay %s\n",
2126 stoa(&pp->srcadr), pp->stratum,
2127 lfptoa(&pp->offset, 6), fptoa((s_fp)pp->delay, 5));
2131 (void) fprintf(fp, "server %s, port %d\n",
2132 stoa(&pp->srcadr), ntohs(((struct sockaddr_in*)&(pp->srcadr))->sin_port));
2134 (void) fprintf(fp, "stratum %d, precision %d, leap %c%c, trust %03o\n",
2135 pp->stratum, pp->precision,
2136 pp->leap & 0x2 ? '1' : '0',
2137 pp->leap & 0x1 ? '1' : '0',
2140 if (pp->stratum == 1) {
2142 memmove(junk, (char *)&pp->refid, 4);
2145 str = stoa(&pp->srcadr);
2148 "refid [%s], delay %s, dispersion %s\n",
2149 str, fptoa((s_fp)pp->delay, 5),
2150 ufptoa(pp->dispersion, 5));
2152 (void) fprintf(fp, "transmitted %d, in filter %d\n",
2153 pp->xmtcnt, pp->filter_nextpt);
2155 (void) fprintf(fp, "reference time: %s\n",
2156 prettydate(&pp->reftime));
2157 (void) fprintf(fp, "originate timestamp: %s\n",
2158 prettydate(&pp->org));
2159 (void) fprintf(fp, "transmit timestamp: %s\n",
2160 prettydate(&pp->xmt));
2162 (void) fprintf(fp, "filter delay: ");
2163 for (i = 0; i < NTP_SHIFT; i++) {
2164 (void) fprintf(fp, " %-8.8s", fptoa(pp->filter_delay[i], 5));
2165 if (i == (NTP_SHIFT>>1)-1)
2166 (void) fprintf(fp, "\n ");
2168 (void) fprintf(fp, "\n");
2170 (void) fprintf(fp, "filter offset:");
2171 for (i = 0; i < PEER_SHIFT; i++) {
2172 (void) fprintf(fp, " %-8.8s", lfptoa(&pp->filter_offset[i], 6));
2173 if (i == (PEER_SHIFT>>1)-1)
2174 (void) fprintf(fp, "\n ");
2176 (void) fprintf(fp, "\n");
2178 (void) fprintf(fp, "delay %s, dispersion %s\n",
2179 fptoa((s_fp)pp->delay, 5), ufptoa(pp->dispersion, 5));
2181 (void) fprintf(fp, "offset %s\n\n",
2182 lfptoa(&pp->offset, 6));
2187 static ni_namelist *
2188 getnetinfoservers(void)
2193 ni_namelist *namelist = emalloc(sizeof(ni_namelist));
2195 /* Find a time server in NetInfo */
2196 if ((status = ni_open(NULL, ".", &domain)) != NI_OK) return NULL;
2198 while (status = ni_pathsearch(domain, &confdir, NETINFO_CONFIG_DIR) == NI_NODIR) {
2200 if (ni_open(domain, "..", &next_domain) != NI_OK) break;
2202 domain = next_domain;
2204 if (status != NI_OK) return NULL;
2207 if (ni_lookupprop(domain, &confdir, "server", namelist) != NI_OK) {
2208 ni_namelist_free(namelist);
2218 isc_boolean_t ntp_port_inuse(int af, u_short port)
2221 * Check if NTP socket is already in use on this system
2222 * This is only for Windows Systems, as they tend not to fail on the real bind() below
2226 struct sockaddr_in checkservice;
2227 checksocket = socket(af, SOCK_DGRAM, 0);
2228 if (checksocket == INVALID_SOCKET) {
2232 checkservice.sin_family = (short) AF_INET;
2233 checkservice.sin_addr.s_addr = INADDR_LOOPBACK;
2234 checkservice.sin_port = htons(port);
2236 if (bind(checksocket, (struct sockaddr *)&checkservice,
2237 sizeof(checkservice)) == SOCKET_ERROR) {
2238 if ( WSAGetLastError() == WSAEADDRINUSE ){
2239 closesocket(checksocket);
2243 closesocket(checksocket);