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