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