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