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