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