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