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