xref: /netbsd-src/external/bsd/ntp/dist/ntpdc/ntpdc.c (revision b1c86f5f087524e68db12794ee9c3e3da1ab17a0)
1 /*	$NetBSD: ntpdc.c,v 1.1.1.1 2009/12/13 16:56:24 kardel Exp $	*/
2 
3 /*
4  * ntpdc - control and monitor your ntpd daemon
5  */
6 
7 #include <stdio.h>
8 #include <stddef.h>
9 #include <ctype.h>
10 #include <signal.h>
11 #include <setjmp.h>
12 
13 #include "ntpdc.h"
14 #include "ntp_select.h"
15 #include "ntp_io.h"
16 #include "ntp_stdlib.h"
17 #include "ntp_assert.h"
18 #include "ntp_lineedit.h"
19 #include "isc/net.h"
20 #include "isc/result.h"
21 #include <ssl_applink.c>
22 
23 #include "ntpdc-opts.h"
24 
25 #ifdef SYS_WINNT
26 # include <Mswsock.h>
27 # include <io.h>
28 #endif /* SYS_WINNT */
29 
30 #ifdef SYS_VXWORKS
31 				/* vxWorks needs mode flag -casey*/
32 # define open(name, flags)   open(name, flags, 0777)
33 # define SERVER_PORT_NUM     123
34 #endif
35 
36 /* We use COMMAND as an autogen keyword */
37 #ifdef COMMAND
38 # undef COMMAND
39 #endif
40 
41 /*
42  * Because we now potentially understand a lot of commands (and
43  * it requires a lot of commands to talk to ntpd) we will run
44  * interactive if connected to a terminal.
45  */
46 static	int	interactive = 0;	/* set to 1 when we should prompt */
47 static	const char *	prompt = "ntpdc> ";	/* prompt to ask him about */
48 
49 /*
50  * Keyid used for authenticated requests.  Obtained on the fly.
51  */
52 static	u_long	info_auth_keyid;
53 static int keyid_entered = 0;
54 
55 static	int	info_auth_keytype = NID_md5;	/* MD5 */
56 static	size_t	info_auth_hashlen = 16;		/* MD5 */
57 u_long	current_time;		/* needed by authkeys; not used */
58 
59 /*
60  * for get_systime()
61  */
62 s_char	sys_precision;		/* local clock precision (log2 s) */
63 
64 /*
65  * Use getpassphrase() if configure.ac detected it, as Suns that
66  * have it truncate the password in getpass() to 8 characters.
67  */
68 #ifdef HAVE_GETPASSPHRASE
69 # define	getpass(str)	getpassphrase(str)
70 #endif
71 
72 int		ntpdcmain	(int,	char **);
73 /*
74  * Built in command handler declarations
75  */
76 static	int	openhost	(const char *);
77 static	int	sendpkt		(void *, size_t);
78 static	void	growpktdata	(void);
79 static	int	getresponse	(int, int, int *, int *, char **, int);
80 static	int	sendrequest	(int, int, int, u_int, size_t, char *);
81 static	void	getcmds		(void);
82 static	RETSIGTYPE abortcmd	(int);
83 static	void	docmd		(const char *);
84 static	void	tokenize	(const char *, char **, int *);
85 static	int	findcmd		(char *, struct xcmd *, struct xcmd *, struct xcmd **);
86 static	int	getarg		(char *, int, arg_v *);
87 static	int	getnetnum	(const char *, sockaddr_u *, char *, int);
88 static	void	help		(struct parse *, FILE *);
89 #ifdef QSORT_USES_VOID_P
90 static	int	helpsort	(const void *, const void *);
91 #else
92 static	int	helpsort	(char **, char **);
93 #endif
94 static	void	printusage	(struct xcmd *, FILE *);
95 static	void	timeout		(struct parse *, FILE *);
96 static	void	my_delay	(struct parse *, FILE *);
97 static	void	host		(struct parse *, FILE *);
98 static	void	keyid		(struct parse *, FILE *);
99 static	void	keytype		(struct parse *, FILE *);
100 static	void	passwd		(struct parse *, FILE *);
101 static	void	hostnames	(struct parse *, FILE *);
102 static	void	setdebug	(struct parse *, FILE *);
103 static	void	quit		(struct parse *, FILE *);
104 static	void	version		(struct parse *, FILE *);
105 static	void	warning		(const char *, const char *, const char *);
106 static	void	error		(const char *, const char *, const char *);
107 static	u_long	getkeyid	(const char *);
108 
109 
110 
111 /*
112  * Built-in commands we understand
113  */
114 static	struct xcmd builtins[] = {
115 	{ "?",		help,		{  OPT|NTP_STR, NO, NO, NO },
116 	  { "command", "", "", "" },
117 	  "tell the use and syntax of commands" },
118 	{ "help",	help,		{  OPT|NTP_STR, NO, NO, NO },
119 	  { "command", "", "", "" },
120 	  "tell the use and syntax of commands" },
121 	{ "timeout",	timeout,	{ OPT|NTP_UINT, NO, NO, NO },
122 	  { "msec", "", "", "" },
123 	  "set the primary receive time out" },
124 	{ "delay",	my_delay,	{ OPT|NTP_INT, NO, NO, NO },
125 	  { "msec", "", "", "" },
126 	  "set the delay added to encryption time stamps" },
127 	{ "host",	host,		{ OPT|NTP_STR, OPT|NTP_STR, NO, NO },
128 	  { "-4|-6", "hostname", "", "" },
129 	  "specify the host whose NTP server we talk to" },
130 	{ "passwd",	passwd,		{ OPT|NTP_STR, NO, NO, NO },
131 	  { "", "", "", "" },
132 	  "specify a password to use for authenticated requests"},
133 	{ "hostnames",	hostnames,	{ OPT|NTP_STR, NO, NO, NO },
134 	  { "yes|no", "", "", "" },
135 	  "specify whether hostnames or net numbers are printed"},
136 	{ "debug",	setdebug,	{ OPT|NTP_STR, NO, NO, NO },
137 	  { "no|more|less", "", "", "" },
138 	  "set/change debugging level" },
139 	{ "quit",	quit,		{ NO, NO, NO, NO },
140 	  { "", "", "", "" },
141 	  "exit ntpdc" },
142 	{ "exit",	quit,		{ NO, NO, NO, NO },
143 	  { "", "", "", "" },
144 	  "exit ntpdc" },
145 	{ "keyid",	keyid,		{ OPT|NTP_UINT, NO, NO, NO },
146 	  { "key#", "", "", "" },
147 	  "set/show keyid to use for authenticated requests" },
148 	{ "keytype",	keytype,	{ OPT|NTP_STR, NO, NO, NO },
149 	  { "(md5|des)", "", "", "" },
150 	  "set/show key authentication type for authenticated requests (des|md5)" },
151 	{ "version",	version,	{ NO, NO, NO, NO },
152 	  { "", "", "", "" },
153 	  "print version number" },
154 	{ 0,		0,		{ NO, NO, NO, NO },
155 	  { "", "", "", "" }, "" }
156 };
157 
158 
159 /*
160  * Default values we use.
161  */
162 #define	DEFHOST		"localhost"	/* default host name */
163 #define	DEFTIMEOUT	(5)		/* 5 second time out */
164 #define	DEFSTIMEOUT	(2)		/* 2 second time out after first */
165 #define	DEFDELAY	0x51EB852	/* 20 milliseconds, l_fp fraction */
166 #define	LENHOSTNAME	256		/* host name is 256 characters long */
167 #define	MAXCMDS		100		/* maximum commands on cmd line */
168 #define	MAXHOSTS	200		/* maximum hosts on cmd line */
169 #define	MAXLINE		512		/* maximum line length */
170 #define	MAXTOKENS	(1+1+MAXARGS+MOREARGS+2)	/* maximum number of usable tokens */
171 #define	SCREENWIDTH  	78		/* nominal screen width in columns */
172 
173 /*
174  * Some variables used and manipulated locally
175  */
176 static	struct sock_timeval tvout = { DEFTIMEOUT, 0 };	/* time out for reads */
177 static	struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
178 static	l_fp delay_time;				/* delay time */
179 static	char currenthost[LENHOSTNAME];			/* current host name */
180 int showhostnames = 1;					/* show host names by default */
181 
182 static	int ai_fam_templ;				/* address family */
183 static	int ai_fam_default;				/* default address family */
184 static	SOCKET sockfd;					/* fd socket is opened on */
185 static	int havehost = 0;				/* set to 1 when host open */
186 int s_port = 0;
187 
188 /*
189  * Holds data returned from queries.  We allocate INITDATASIZE
190  * octets to begin with, increasing this as we need to.
191  */
192 #define	INITDATASIZE	(sizeof(struct resp_pkt) * 16)
193 #define	INCDATASIZE	(sizeof(struct resp_pkt) * 8)
194 
195 static	char *pktdata;
196 static	int pktdatasize;
197 
198 /*
199  * These are used to help the magic with old and new versions of ntpd.
200  */
201 int impl_ver = IMPL_XNTPD;
202 static int req_pkt_size = REQ_LEN_NOMAC;
203 
204 /*
205  * For commands typed on the command line (with the -c option)
206  */
207 static	int numcmds = 0;
208 static	const char *ccmds[MAXCMDS];
209 #define	ADDCMD(cp)	if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
210 
211 /*
212  * When multiple hosts are specified.
213  */
214 static	int numhosts = 0;
215 static	const char *chosts[MAXHOSTS];
216 #define	ADDHOST(cp)	if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp)
217 
218 /*
219  * Error codes for internal use
220  */
221 #define	ERR_INCOMPLETE		16
222 #define	ERR_TIMEOUT		17
223 
224 /*
225  * Macro definitions we use
226  */
227 #define	ISSPACE(c)	((c) == ' ' || (c) == '\t')
228 #define	ISEOL(c)	((c) == '\n' || (c) == '\r' || (c) == '\0')
229 #define	STREQ(a, b)	(*(a) == *(b) && strcmp((a), (b)) == 0)
230 
231 /*
232  * For converting time stamps to dates
233  */
234 #define	JAN_1970	2208988800	/* 1970 - 1900 in seconds */
235 
236 /*
237  * Jump buffer for longjumping back to the command level
238  */
239 static	jmp_buf interrupt_buf;
240 static  volatile int jump = 0;
241 
242 /*
243  * Pointer to current output unit
244  */
245 static	FILE *current_output;
246 
247 /*
248  * Command table imported from ntpdc_ops.c
249  */
250 extern struct xcmd opcmds[];
251 
252 char *progname;
253 volatile int debug;
254 
255 #ifdef NO_MAIN_ALLOWED
256 CALL(ntpdc,"ntpdc",ntpdcmain);
257 #else
258 int
259 main(
260 	int argc,
261 	char *argv[]
262 	)
263 {
264 	return ntpdcmain(argc, argv);
265 }
266 #endif
267 
268 #ifdef SYS_VXWORKS
269 void clear_globals(void)
270 {
271     showhostnames = 0;              /* show host names by default */
272     havehost = 0;                   /* set to 1 when host open */
273     numcmds = 0;
274     numhosts = 0;
275 }
276 #endif
277 
278 /*
279  * main - parse arguments and handle options
280  */
281 int
282 ntpdcmain(
283 	int argc,
284 	char *argv[]
285 	)
286 {
287 	extern int ntp_optind;
288 
289 	delay_time.l_ui = 0;
290 	delay_time.l_uf = DEFDELAY;
291 
292 #ifdef SYS_VXWORKS
293 	clear_globals();
294 	taskPrioritySet(taskIdSelf(), 100 );
295 #endif
296 
297 	init_lib();	/* sets up ipv4_works, ipv6_works */
298 	ssl_applink();
299 
300 	/* Check to see if we have IPv6. Otherwise default to IPv4 */
301 	if (!ipv6_works)
302 		ai_fam_default = AF_INET;
303 
304 	progname = argv[0];
305 
306 	{
307 		int optct = optionProcess(&ntpdcOptions, argc, argv);
308 		argc -= optct;
309 		argv += optct;
310 	}
311 
312 	if (HAVE_OPT(IPV4))
313 		ai_fam_templ = AF_INET;
314 	else if (HAVE_OPT(IPV6))
315 		ai_fam_templ = AF_INET6;
316 	else
317 		ai_fam_templ = ai_fam_default;
318 
319 	if (HAVE_OPT(COMMAND)) {
320 		int		cmdct = STACKCT_OPT( COMMAND );
321 		const char**	cmds  = STACKLST_OPT( COMMAND );
322 
323 		while (cmdct-- > 0) {
324 			ADDCMD(*cmds++);
325 		}
326 	}
327 
328 	debug = DESC(DEBUG_LEVEL).optOccCt;
329 
330 	if (HAVE_OPT(INTERACTIVE)) {
331 		interactive = 1;
332 	}
333 
334 	if (HAVE_OPT(NUMERIC)) {
335 		showhostnames = 0;
336 	}
337 
338 	if (HAVE_OPT(LISTPEERS)) {
339 		ADDCMD("listpeers");
340 	}
341 
342 	if (HAVE_OPT(PEERS)) {
343 		ADDCMD("peers");
344 	}
345 
346 	if (HAVE_OPT(SHOWPEERS)) {
347 		ADDCMD("dmpeers");
348 	}
349 
350 	if (ntp_optind == argc) {
351 		ADDHOST(DEFHOST);
352 	} else {
353 		for (; ntp_optind < argc; ntp_optind++)
354 		    ADDHOST(argv[ntp_optind]);
355 	}
356 
357 	if (numcmds == 0 && interactive == 0
358 	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
359 		interactive = 1;
360 	}
361 
362 #if 0
363 	ai_fam_templ = ai_fam_default;
364 	while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF)
365 	    switch (c) {
366 		case '4':
367 		    ai_fam_templ = AF_INET;
368 		    break;
369 		case '6':
370 		    ai_fam_templ = AF_INET6;
371 		    break;
372 		case 'c':
373 		    ADDCMD(ntp_optarg);
374 		    break;
375 		case 'd':
376 		    ++debug;
377 		    break;
378 		case 'i':
379 		    interactive = 1;
380 		    break;
381 		case 'l':
382 		    ADDCMD("listpeers");
383 		    break;
384 		case 'n':
385 		    showhostnames = 0;
386 		    break;
387 		case 'p':
388 		    ADDCMD("peers");
389 		    break;
390 		case 's':
391 		    ADDCMD("dmpeers");
392 		    break;
393 		default:
394 		    errflg++;
395 		    break;
396 	    }
397 
398 	if (errflg) {
399 		(void) fprintf(stderr,
400 			       "usage: %s [-46dilnps] [-c cmd] host ...\n",
401 			       progname);
402 		exit(2);
403 	}
404 
405 	if (ntp_optind == argc) {
406 		ADDHOST(DEFHOST);
407 	} else {
408 		for (; ntp_optind < argc; ntp_optind++)
409 		    ADDHOST(argv[ntp_optind]);
410 	}
411 
412 	if (numcmds == 0 && interactive == 0
413 	    && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
414 		interactive = 1;
415 	}
416 #endif
417 
418 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
419 	if (interactive)
420 	    (void) signal_no_reset(SIGINT, abortcmd);
421 #endif /* SYS_WINNT */
422 
423 	/*
424 	 * Initialize the packet data buffer
425 	 */
426 	pktdatasize = INITDATASIZE;
427 	pktdata = emalloc(INITDATASIZE);
428 
429 	if (numcmds == 0) {
430 		(void) openhost(chosts[0]);
431 		getcmds();
432 	} else {
433 		int ihost;
434 		int icmd;
435 
436 		for (ihost = 0; ihost < numhosts; ihost++) {
437 			if (openhost(chosts[ihost]))
438 			    for (icmd = 0; icmd < numcmds; icmd++) {
439 				    if (numhosts > 1)
440 					printf ("--- %s ---\n",chosts[ihost]);
441 				    docmd(ccmds[icmd]);
442 			    }
443 		}
444 	}
445 #ifdef SYS_WINNT
446 	WSACleanup();
447 #endif
448 	return(0);
449 } /* main end */
450 
451 
452 /*
453  * openhost - open a socket to a host
454  */
455 static int
456 openhost(
457 	const char *hname
458 	)
459 {
460 	char temphost[LENHOSTNAME];
461 	int a_info, i;
462 	struct addrinfo hints, *ai = NULL;
463 	register const char *cp;
464 	char name[LENHOSTNAME];
465 	char service[5];
466 
467 	/*
468 	 * We need to get by the [] if they were entered
469 	 */
470 
471 	cp = hname;
472 
473 	if (*cp == '[') {
474 		cp++;
475 		for (i = 0; *cp && *cp != ']'; cp++, i++)
476 			name[i] = *cp;
477 		if (*cp == ']') {
478 			name[i] = '\0';
479 			hname = name;
480 		} else {
481 			return 0;
482 		}
483 	}
484 
485 	/*
486 	 * First try to resolve it as an ip address and if that fails,
487 	 * do a fullblown (dns) lookup. That way we only use the dns
488 	 * when it is needed and work around some implementations that
489 	 * will return an "IPv4-mapped IPv6 address" address if you
490 	 * give it an IPv4 address to lookup.
491 	 */
492 	strcpy(service, "ntp");
493 	memset((char *)&hints, 0, sizeof(struct addrinfo));
494 	hints.ai_family = ai_fam_templ;
495 	hints.ai_protocol = IPPROTO_UDP;
496 	hints.ai_socktype = SOCK_DGRAM;
497 	hints.ai_flags = AI_NUMERICHOST;
498 
499 	a_info = getaddrinfo(hname, service, &hints, &ai);
500 	if (a_info == EAI_NONAME
501 #ifdef EAI_NODATA
502 	    || a_info == EAI_NODATA
503 #endif
504 	   ) {
505 		hints.ai_flags = AI_CANONNAME;
506 #ifdef AI_ADDRCONFIG
507 		hints.ai_flags |= AI_ADDRCONFIG;
508 #endif
509 		a_info = getaddrinfo(hname, service, &hints, &ai);
510 	}
511 	/* Some older implementations don't like AI_ADDRCONFIG. */
512 	if (a_info == EAI_BADFLAGS) {
513 		hints.ai_flags = AI_CANONNAME;
514 		a_info = getaddrinfo(hname, service, &hints, &ai);
515 	}
516 	if (a_info != 0) {
517 		(void) fprintf(stderr, "%s\n", gai_strerror(a_info));
518 		if (ai != NULL)
519 			freeaddrinfo(ai);
520 		return 0;
521 	}
522 
523 	/*
524 	 * getaddrinfo() has returned without error so ai should not
525 	 * be NULL.
526 	 */
527 	NTP_INSIST(ai != NULL);
528 
529 	if (ai->ai_canonname == NULL) {
530 		strncpy(temphost, stoa((sockaddr_u *)ai->ai_addr),
531 		    LENHOSTNAME);
532 		temphost[LENHOSTNAME-1] = '\0';
533 	} else {
534 		strncpy(temphost, ai->ai_canonname, LENHOSTNAME);
535 		temphost[LENHOSTNAME-1] = '\0';
536 	}
537 
538 	if (debug > 2)
539 	    printf("Opening host %s\n", temphost);
540 
541 	if (havehost == 1) {
542 		if (debug > 2)
543 		    printf("Closing old host %s\n", currenthost);
544 		(void) closesocket(sockfd);
545 		havehost = 0;
546 	}
547 	(void) strcpy(currenthost, temphost);
548 
549 	/* port maps to the same in both families */
550 	s_port = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port;
551 #ifdef SYS_VXWORKS
552 	((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
553 	if (ai->ai_family == AF_INET)
554 		*(struct sockaddr_in *)&hostaddr=
555 			*((struct sockaddr_in *)ai->ai_addr);
556 	else
557 		*(struct sockaddr_in6 *)&hostaddr=
558 			*((struct sockaddr_in6 *)ai->ai_addr);
559 #endif /* SYS_VXWORKS */
560 
561 #ifdef SYS_WINNT
562 	{
563 		int optionValue = SO_SYNCHRONOUS_NONALERT;
564 		int err;
565 
566 		err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue));
567 		if (err != NO_ERROR) {
568 			(void) fprintf(stderr, "cannot open nonoverlapped sockets\n");
569 			exit(1);
570 		}
571 	}
572 
573 	sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
574 	if (sockfd == INVALID_SOCKET) {
575 		error("socket", "", "");
576 		exit(-1);
577 	}
578 #else
579 	sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
580 	if (sockfd == -1)
581 	    error("socket", "", "");
582 #endif /* SYS_WINNT */
583 
584 
585 #ifdef NEED_RCVBUF_SLOP
586 # ifdef SO_RCVBUF
587 	{
588 		int rbufsize = INITDATASIZE + 2048; /* 2K for slop */
589 
590 		if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
591 			       &rbufsize, sizeof(int)) == -1)
592 		    error("setsockopt", "", "");
593 	}
594 # endif
595 #endif
596 
597 #ifdef SYS_VXWORKS
598 	if (connect(sockfd, (struct sockaddr *)&hostaddr,
599 		    sizeof(hostaddr)) == -1)
600 #else
601 	if (connect(sockfd, (struct sockaddr *)ai->ai_addr,
602 		    ai->ai_addrlen) == -1)
603 #endif /* SYS_VXWORKS */
604 	    error("connect", "", "");
605 
606 	freeaddrinfo(ai);
607 	havehost = 1;
608 	req_pkt_size = REQ_LEN_NOMAC;
609 	impl_ver = IMPL_XNTPD;
610 	return 1;
611 }
612 
613 
614 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
615 /*
616  * sendpkt - send a packet to the remote host
617  */
618 static int
619 sendpkt(
620 	void *	xdata,
621 	size_t	xdatalen
622 	)
623 {
624 	if (send(sockfd, xdata, xdatalen, 0) == -1) {
625 		warning("write to %s failed", currenthost, "");
626 		return -1;
627 	}
628 
629 	return 0;
630 }
631 
632 
633 /*
634  * growpktdata - grow the packet data area
635  */
636 static void
637 growpktdata(void)
638 {
639 	pktdatasize += INCDATASIZE;
640 	pktdata = erealloc(pktdata, (size_t)pktdatasize);
641 }
642 
643 
644 /*
645  * getresponse - get a (series of) response packet(s) and return the data
646  */
647 static int
648 getresponse(
649 	int implcode,
650 	int reqcode,
651 	int *ritems,
652 	int *rsize,
653 	char **rdata,
654 	int esize
655 	)
656 {
657 	struct resp_pkt rpkt;
658 	struct sock_timeval tvo;
659 	int items;
660 	int i;
661 	int size;
662 	int datasize;
663 	char *datap;
664 	char *tmp_data;
665 	char haveseq[MAXSEQ+1];
666 	int firstpkt;
667 	int lastseq;
668 	int numrecv;
669 	int seq;
670 	fd_set fds;
671 	int n;
672 	int pad;
673 
674 	/*
675 	 * This is pretty tricky.  We may get between 1 and many packets
676 	 * back in response to the request.  We peel the data out of
677 	 * each packet and collect it in one long block.  When the last
678 	 * packet in the sequence is received we'll know how many we
679 	 * should have had.  Note we use one long time out, should reconsider.
680 	 */
681 	*ritems = 0;
682 	*rsize = 0;
683 	firstpkt = 1;
684 	numrecv = 0;
685 	*rdata = datap = pktdata;
686 	lastseq = 999;	/* too big to be a sequence number */
687 	memset(haveseq, 0, sizeof(haveseq));
688 	FD_ZERO(&fds);
689 
690     again:
691 	if (firstpkt)
692 		tvo = tvout;
693 	else
694 		tvo = tvsout;
695 
696 	FD_SET(sockfd, &fds);
697 	n = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvo);
698 
699 	if (n == -1) {
700 		warning("select fails", "", "");
701 		return -1;
702 	}
703 	if (n == 0) {
704 		/*
705 		 * Timed out.  Return what we have
706 		 */
707 		if (firstpkt) {
708 			(void) fprintf(stderr,
709 				       "%s: timed out, nothing received\n", currenthost);
710 			return ERR_TIMEOUT;
711 		} else {
712 			(void) fprintf(stderr,
713 				       "%s: timed out with incomplete data\n",
714 				       currenthost);
715 			if (debug) {
716 				printf("Received sequence numbers");
717 				for (n = 0; n <= MAXSEQ; n++)
718 				    if (haveseq[n])
719 					printf(" %d,", n);
720 				if (lastseq != 999)
721 				    printf(" last frame received\n");
722 				else
723 				    printf(" last frame not received\n");
724 			}
725 			return ERR_INCOMPLETE;
726 		}
727 	}
728 
729 	n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
730 	if (n == -1) {
731 		warning("read", "", "");
732 		return -1;
733 	}
734 
735 
736 	/*
737 	 * Check for format errors.  Bug proofing.
738 	 */
739 	if (n < RESP_HEADER_SIZE) {
740 		if (debug)
741 		    printf("Short (%d byte) packet received\n", n);
742 		goto again;
743 	}
744 	if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION ||
745 	    INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) {
746 		if (debug)
747 		    printf("Packet received with version %d\n",
748 			   INFO_VERSION(rpkt.rm_vn_mode));
749 		goto again;
750 	}
751 	if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) {
752 		if (debug)
753 		    printf("Packet received with mode %d\n",
754 			   INFO_MODE(rpkt.rm_vn_mode));
755 		goto again;
756 	}
757 	if (INFO_IS_AUTH(rpkt.auth_seq)) {
758 		if (debug)
759 		    printf("Encrypted packet received\n");
760 		goto again;
761 	}
762 	if (!ISRESPONSE(rpkt.rm_vn_mode)) {
763 		if (debug)
764 		    printf("Received request packet, wanted response\n");
765 		goto again;
766 	}
767 	if (INFO_MBZ(rpkt.mbz_itemsize) != 0) {
768 		if (debug)
769 		    printf("Received packet with nonzero MBZ field!\n");
770 		goto again;
771 	}
772 
773 	/*
774 	 * Check implementation/request.  Could be old data getting to us.
775 	 */
776 	if (rpkt.implementation != implcode || rpkt.request != reqcode) {
777 		if (debug)
778 		    printf(
779 			    "Received implementation/request of %d/%d, wanted %d/%d",
780 			    rpkt.implementation, rpkt.request,
781 			    implcode, reqcode);
782 		goto again;
783 	}
784 
785 	/*
786 	 * Check the error code.  If non-zero, return it.
787 	 */
788 	if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) {
789 		if (debug && ISMORE(rpkt.rm_vn_mode)) {
790 			printf("Error code %d received on not-final packet\n",
791 			       INFO_ERR(rpkt.err_nitems));
792 		}
793 		return (int)INFO_ERR(rpkt.err_nitems);
794 	}
795 
796 	/*
797 	 * Collect items and size.  Make sure they make sense.
798 	 */
799 	items = INFO_NITEMS(rpkt.err_nitems);
800 	size = INFO_ITEMSIZE(rpkt.mbz_itemsize);
801 	if (esize > size)
802 		pad = esize - size;
803 	else
804 		pad = 0;
805 	datasize = items * size;
806 	if ((size_t)datasize > (n-RESP_HEADER_SIZE)) {
807 		if (debug)
808 		    printf(
809 			    "Received items %d, size %d (total %d), data in packet is %d\n",
810 			    items, size, datasize, n-RESP_HEADER_SIZE);
811 		goto again;
812 	}
813 
814 	/*
815 	 * If this isn't our first packet, make sure the size matches
816 	 * the other ones.
817 	 */
818 	if (!firstpkt && esize != *rsize) {
819 		if (debug)
820 		    printf("Received itemsize %d, previous %d\n",
821 			   size, *rsize);
822 		goto again;
823 	}
824 	/*
825 	 * If we've received this before, +toss it
826 	 */
827 	seq = INFO_SEQ(rpkt.auth_seq);
828 	if (haveseq[seq]) {
829 		if (debug)
830 		    printf("Received duplicate sequence number %d\n", seq);
831 		goto again;
832 	}
833 	haveseq[seq] = 1;
834 
835 	/*
836 	 * If this is the last in the sequence, record that.
837 	 */
838 	if (!ISMORE(rpkt.rm_vn_mode)) {
839 		if (lastseq != 999) {
840 			printf("Received second end sequence packet\n");
841 			goto again;
842 		}
843 		lastseq = seq;
844 	}
845 
846 	/*
847 	 * So far, so good.  Copy this data into the output array.
848 	 */
849 	if ((datap + datasize + (pad * items)) > (pktdata + pktdatasize)) {
850 		int offset = datap - pktdata;
851 		growpktdata();
852 		*rdata = pktdata; /* might have been realloced ! */
853 		datap = pktdata + offset;
854 	}
855 	/*
856 	 * We now move the pointer along according to size and number of
857 	 * items.  This is so we can play nice with older implementations
858 	 */
859 
860 	tmp_data = rpkt.data;
861 	for (i = 0; i < items; i++) {
862 		memcpy(datap, tmp_data, (unsigned)size);
863 		tmp_data += size;
864 		memset(datap + size, 0, pad);
865 		datap += size + pad;
866 	}
867 
868 	if (firstpkt) {
869 		firstpkt = 0;
870 		*rsize = size + pad;
871 	}
872 	*ritems += items;
873 
874 	/*
875 	 * Finally, check the count of received packets.  If we've got them
876 	 * all, return
877 	 */
878 	++numrecv;
879 	if (numrecv <= lastseq)
880 		goto again;
881 	return INFO_OKAY;
882 }
883 
884 
885 /*
886  * sendrequest - format and send a request packet
887  *
888  * Historically, ntpdc has used a fixed-size request packet regardless
889  * of the actual payload size.  When authenticating, the timestamp, key
890  * ID, and digest have been placed just before the end of the packet.
891  * With the introduction in late 2009 of support for authenticated
892  * ntpdc requests using larger 20-octet digests (vs. 16 for MD5), we
893  * come up four bytes short.
894  *
895  * To maintain interop while allowing for larger digests, the behavior
896  * is unchanged when using 16-octet digests.  For larger digests, the
897  * timestamp, key ID, and digest are placed immediately following the
898  * request payload, with the overall packet size variable.  ntpd can
899  * distinguish 16-octet digests by the overall request size being
900  * REQ_LEN_NOMAC + 4 + 16 with the auth bit enabled.  When using a
901  * longer digest, that request size should be avoided.
902  *
903  * With the form used with 20-octet and larger digests, the timestamp,
904  * key ID, and digest are located by ntpd relative to the start of the
905  * packet, and the size of the digest is then implied by the packet
906  * size.
907  */
908 static int
909 sendrequest(
910 	int implcode,
911 	int reqcode,
912 	int auth,
913 	u_int qitems,
914 	size_t qsize,
915 	char *qdata
916 	)
917 {
918 	struct req_pkt qpkt;
919 	size_t	datasize;
920 	size_t	reqsize;
921 	u_long	key_id;
922 	l_fp	ts;
923 	l_fp *	ptstamp;
924 	int	maclen;
925 	char	pass_prompt[32];
926 	char *	pass;
927 
928 	memset(&qpkt, 0, sizeof(qpkt));
929 
930 	qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
931 	qpkt.implementation = (u_char)implcode;
932 	qpkt.request = (u_char)reqcode;
933 
934 	datasize = qitems * qsize;
935 	if (datasize && qdata != NULL) {
936 		memcpy(qpkt.data, qdata, datasize);
937 		qpkt.err_nitems = ERR_NITEMS(0, qitems);
938 		qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);
939 	} else {
940 		qpkt.err_nitems = ERR_NITEMS(0, 0);
941 		qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);  /* allow for optional first item */
942 	}
943 
944 	if (!auth || (keyid_entered && info_auth_keyid == 0)) {
945 		qpkt.auth_seq = AUTH_SEQ(0, 0);
946 		return sendpkt(&qpkt, req_pkt_size);
947 	}
948 
949 	if (info_auth_keyid == 0) {
950 		key_id = getkeyid("Keyid: ");
951 		if (!key_id) {
952 			fprintf(stderr, "Invalid key identifier\n");
953 			return 1;
954 		}
955 		info_auth_keyid = key_id;
956 	}
957 	if (!authistrusted(info_auth_keyid)) {
958 		snprintf(pass_prompt, sizeof(pass_prompt),
959 			 "%s Password: ",
960 			 keytype_name(info_auth_keytype));
961 		pass = getpass(pass_prompt);
962 		if ('\0' == pass[0]) {
963 			fprintf(stderr, "Invalid password\n");
964 			return 1;
965 		}
966 		authusekey(info_auth_keyid, info_auth_keytype,
967 			   (u_char *)pass);
968 		authtrust(info_auth_keyid, 1);
969 	}
970 	qpkt.auth_seq = AUTH_SEQ(1, 0);
971 	if (info_auth_hashlen > 16) {
972 		/*
973 		 * Only ntpd which expects REQ_LEN_NOMAC plus maclen
974 		 * octets in an authenticated request using a 16 octet
975 		 * digest (that is, a newer ntpd) will handle digests
976 		 * larger than 16 octets, so for longer digests, do
977 		 * not attempt to shorten the requests for downlevel
978 		 * ntpd compatibility.
979 		 */
980 		if (REQ_LEN_NOMAC != req_pkt_size)
981 			return 1;
982 		reqsize = REQ_LEN_HDR + datasize + sizeof(*ptstamp);
983 		/* align to 32 bits */
984 		reqsize = (reqsize + 3) & ~3;
985 	} else
986 		reqsize = req_pkt_size;
987 	ptstamp = (void *)((char *)&qpkt + reqsize);
988 	ptstamp--;
989 	get_systime(&ts);
990 	L_ADD(&ts, &delay_time);
991 	HTONL_FP(&ts, ptstamp);
992 	maclen = authencrypt(info_auth_keyid, (void *)&qpkt, reqsize);
993 	if (!maclen) {
994 		fprintf(stderr, "Key not found\n");
995 		return 1;
996 	} else if (maclen != (info_auth_hashlen + sizeof(keyid_t))) {
997 		fprintf(stderr,
998 			"%d octet MAC, %u expected with %u octet digest\n",
999 			maclen, (info_auth_hashlen + sizeof(keyid_t)),
1000 			info_auth_hashlen);
1001 		return 1;
1002 	}
1003 	return sendpkt(&qpkt, reqsize + maclen);
1004 }
1005 
1006 
1007 /*
1008  * doquery - send a request and process the response
1009  */
1010 int
1011 doquery(
1012 	int implcode,
1013 	int reqcode,
1014 	int auth,
1015 	int qitems,
1016 	int qsize,
1017 	char *qdata,
1018 	int *ritems,
1019 	int *rsize,
1020 	char **rdata,
1021  	int quiet_mask,
1022 	int esize
1023 	)
1024 {
1025 	int res;
1026 	char junk[512];
1027 	fd_set fds;
1028 	struct sock_timeval tvzero;
1029 
1030 	/*
1031 	 * Check to make sure host is open
1032 	 */
1033 	if (!havehost) {
1034 		(void) fprintf(stderr, "***No host open, use `host' command\n");
1035 		return -1;
1036 	}
1037 
1038 	/*
1039 	 * Poll the socket and clear out any pending data
1040 	 */
1041 again:
1042 	do {
1043 		tvzero.tv_sec = tvzero.tv_usec = 0;
1044 		FD_ZERO(&fds);
1045 		FD_SET(sockfd, &fds);
1046 		res = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
1047 
1048 		if (res == -1) {
1049 			warning("polling select", "", "");
1050 			return -1;
1051 		} else if (res > 0)
1052 
1053 		    (void) recv(sockfd, junk, sizeof junk, 0);
1054 	} while (res > 0);
1055 
1056 
1057 	/*
1058 	 * send a request
1059 	 */
1060 	res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata);
1061 	if (res != 0)
1062 		return res;
1063 
1064 	/*
1065 	 * Get the response.  If we got a standard error, print a message
1066 	 */
1067 	res = getresponse(implcode, reqcode, ritems, rsize, rdata, esize);
1068 
1069 	/*
1070 	 * Try to be compatible with older implementations of ntpd.
1071 	 */
1072 	if (res == INFO_ERR_FMT && req_pkt_size != 48) {
1073 		int oldsize;
1074 
1075 		oldsize = req_pkt_size;
1076 
1077 		switch(req_pkt_size) {
1078 		case REQ_LEN_NOMAC:
1079 			req_pkt_size = 160;
1080 			break;
1081 		case 160:
1082 			req_pkt_size = 48;
1083 			break;
1084 		}
1085 		if (impl_ver == IMPL_XNTPD) {
1086 			fprintf(stderr,
1087 			    "***Warning changing to older implementation\n");
1088 			return INFO_ERR_IMPL;
1089 		}
1090 
1091 		fprintf(stderr,
1092 		    "***Warning changing the request packet size from %d to %d\n",
1093 		    oldsize, req_pkt_size);
1094 		goto again;
1095 	}
1096 
1097  	/* log error message if not told to be quiet */
1098  	if ((res > 0) && (((1 << res) & quiet_mask) == 0)) {
1099 		switch(res) {
1100 		case INFO_ERR_IMPL:
1101 			/* Give us a chance to try the older implementation. */
1102 			if (implcode == IMPL_XNTPD)
1103 				break;
1104 			(void) fprintf(stderr,
1105 				       "***Server implementation incompatable with our own\n");
1106 			break;
1107 		case INFO_ERR_REQ:
1108 			(void) fprintf(stderr,
1109 				       "***Server doesn't implement this request\n");
1110 			break;
1111 		case INFO_ERR_FMT:
1112 			(void) fprintf(stderr,
1113 				       "***Server reports a format error in the received packet (shouldn't happen)\n");
1114 			break;
1115 		case INFO_ERR_NODATA:
1116 			(void) fprintf(stderr,
1117 				       "***Server reports data not found\n");
1118 			break;
1119 		case INFO_ERR_AUTH:
1120 			(void) fprintf(stderr, "***Permission denied\n");
1121 			break;
1122 		case ERR_TIMEOUT:
1123 			(void) fprintf(stderr, "***Request timed out\n");
1124 			break;
1125 		case ERR_INCOMPLETE:
1126 			(void) fprintf(stderr,
1127 				       "***Response from server was incomplete\n");
1128 			break;
1129 		default:
1130 			(void) fprintf(stderr,
1131 				       "***Server returns unknown error code %d\n", res);
1132 			break;
1133 		}
1134 	}
1135 	return res;
1136 }
1137 
1138 
1139 /*
1140  * getcmds - read commands from the standard input and execute them
1141  */
1142 static void
1143 getcmds(void)
1144 {
1145 	char *	line;
1146 	int	count;
1147 
1148 	ntp_readline_init(interactive ? prompt : NULL);
1149 
1150 	for (;;) {
1151 		line = ntp_readline(&count);
1152 		if (NULL == line)
1153 			break;
1154 		docmd(line);
1155 		free(line);
1156 	}
1157 
1158 	ntp_readline_uninit();
1159 }
1160 
1161 
1162 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
1163 /*
1164  * abortcmd - catch interrupts and abort the current command
1165  */
1166 static RETSIGTYPE
1167 abortcmd(
1168 	int sig
1169 	)
1170 {
1171 
1172 	if (current_output == stdout)
1173 	    (void) fflush(stdout);
1174 	putc('\n', stderr);
1175 	(void) fflush(stderr);
1176 	if (jump) longjmp(interrupt_buf, 1);
1177 }
1178 #endif /* SYS_WINNT */
1179 
1180 /*
1181  * docmd - decode the command line and execute a command
1182  */
1183 static void
1184 docmd(
1185 	const char *cmdline
1186 	)
1187 {
1188 	char *tokens[1+MAXARGS+MOREARGS+2];
1189 	struct parse pcmd;
1190 	int ntok;
1191 	int i, ti;
1192 	int rval;
1193 	struct xcmd *xcmd;
1194 
1195 	ai_fam_templ = ai_fam_default;
1196 	/*
1197 	 * Tokenize the command line.  If nothing on it, return.
1198 	 */
1199 	tokenize(cmdline, tokens, &ntok);
1200 	if (ntok == 0)
1201 	    return;
1202 
1203 	/*
1204 	 * Find the appropriate command description.
1205 	 */
1206 	i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1207 	if (i == 0) {
1208 		(void) fprintf(stderr, "***Command `%s' unknown\n",
1209 			       tokens[0]);
1210 		return;
1211 	} else if (i >= 2) {
1212 		(void) fprintf(stderr, "***Command `%s' ambiguous\n",
1213 			       tokens[0]);
1214 		return;
1215 	}
1216 
1217 	/*
1218 	 * Save the keyword, then walk through the arguments, interpreting
1219 	 * as we go.
1220 	 */
1221 	pcmd.keyword = tokens[0];
1222 	pcmd.nargs = 0;
1223 	ti = 1;
1224 	for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) {
1225 		if ((i+ti) >= ntok) {
1226 			if (!(xcmd->arg[i] & OPT)) {
1227 				printusage(xcmd, stderr);
1228 				return;
1229 			}
1230 			break;
1231 		}
1232 		if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>'))
1233 			break;
1234 		rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]);
1235 		if (rval == -1) {
1236 			ti++;
1237 			continue;
1238 		}
1239 		if (rval == 0)
1240 			return;
1241 		pcmd.nargs++;
1242 		i++;
1243 	}
1244 
1245 	/* Any extra args are assumed to be "OPT|NTP_STR". */
1246 	for ( ; i < MAXARGS + MOREARGS;) {
1247 	     if ((i+ti) >= ntok)
1248 		  break;
1249 		rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]);
1250 		if (rval == -1) {
1251 			ti++;
1252 			continue;
1253 		}
1254 		if (rval == 0)
1255 			return;
1256 		pcmd.nargs++;
1257 		i++;
1258 	}
1259 
1260 	i += ti;
1261 	if (i < ntok && *tokens[i] == '>') {
1262 		char *fname;
1263 
1264 		if (*(tokens[i]+1) != '\0')
1265 		    fname = tokens[i]+1;
1266 		else if ((i+1) < ntok)
1267 		    fname = tokens[i+1];
1268 		else {
1269 			(void) fprintf(stderr, "***No file for redirect\n");
1270 			return;
1271 		}
1272 
1273 		current_output = fopen(fname, "w");
1274 		if (current_output == NULL) {
1275 			(void) fprintf(stderr, "***Error opening %s: ", fname);
1276 			perror("");
1277 			return;
1278 		}
1279 	} else {
1280 		current_output = stdout;
1281 	}
1282 
1283 	if (interactive && setjmp(interrupt_buf)) {
1284 		return;
1285 	} else {
1286 		jump = 1;
1287 		(xcmd->handler)(&pcmd, current_output);
1288 		jump = 0;
1289 		if (current_output != stdout)
1290 			(void) fclose(current_output);
1291 		current_output = NULL;
1292 	}
1293 }
1294 
1295 
1296 /*
1297  * tokenize - turn a command line into tokens
1298  */
1299 static void
1300 tokenize(
1301 	const char *line,
1302 	char **tokens,
1303 	int *ntok
1304 	)
1305 {
1306 	register const char *cp;
1307 	register char *sp;
1308 	static char tspace[MAXLINE];
1309 
1310 	sp = tspace;
1311 	cp = line;
1312 	for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1313 		tokens[*ntok] = sp;
1314 		while (ISSPACE(*cp))
1315 		    cp++;
1316 		if (ISEOL(*cp))
1317 		    break;
1318 		do {
1319 			*sp++ = *cp++;
1320 		} while (!ISSPACE(*cp) && !ISEOL(*cp));
1321 
1322 		*sp++ = '\0';
1323 	}
1324 }
1325 
1326 
1327 
1328 /*
1329  * findcmd - find a command in a command description table
1330  */
1331 static int
1332 findcmd(
1333 	register char *str,
1334 	struct xcmd *clist1,
1335 	struct xcmd *clist2,
1336 	struct xcmd **cmd
1337 	)
1338 {
1339 	register struct xcmd *cl;
1340 	register int clen;
1341 	int nmatch;
1342 	struct xcmd *nearmatch = NULL;
1343 	struct xcmd *clist;
1344 
1345 	clen = strlen(str);
1346 	nmatch = 0;
1347 	if (clist1 != 0)
1348 	    clist = clist1;
1349 	else if (clist2 != 0)
1350 	    clist = clist2;
1351 	else
1352 	    return 0;
1353 
1354     again:
1355 	for (cl = clist; cl->keyword != 0; cl++) {
1356 		/* do a first character check, for efficiency */
1357 		if (*str != *(cl->keyword))
1358 		    continue;
1359 		if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1360 			/*
1361 			 * Could be extact match, could be approximate.
1362 			 * Is exact if the length of the keyword is the
1363 			 * same as the str.
1364 			 */
1365 			if (*((cl->keyword) + clen) == '\0') {
1366 				*cmd = cl;
1367 				return 1;
1368 			}
1369 			nmatch++;
1370 			nearmatch = cl;
1371 		}
1372 	}
1373 
1374 				/*
1375 				 * See if there is more to do.  If so, go again.  Sorry about the
1376 				 * goto, too much looking at BSD sources...
1377 				 */
1378 	if (clist == clist1 && clist2 != 0) {
1379 		clist = clist2;
1380 		goto again;
1381 	}
1382 
1383 				/*
1384 				 * If we got extactly 1 near match, use it, else return number
1385 				 * of matches.
1386 				 */
1387 	if (nmatch == 1) {
1388 		*cmd = nearmatch;
1389 		return 1;
1390 	}
1391 	return nmatch;
1392 }
1393 
1394 
1395 /*
1396  * getarg - interpret an argument token
1397  *
1398  * string is always set.
1399  * type is set to the decoded type.
1400  *
1401  * return:	 0 - failure
1402  *		 1 - success
1403  *		-1 - skip to next token
1404  */
1405 static int
1406 getarg(
1407 	char *str,
1408 	int code,
1409 	arg_v *argp
1410 	)
1411 {
1412 	int isneg;
1413 	char *cp, *np;
1414 	static const char *digits = "0123456789";
1415 
1416 	memset(argp, 0, sizeof(*argp));
1417 
1418 	argp->string = str;
1419 	argp->type   = code & ~OPT;
1420 
1421 	switch (argp->type) {
1422 	    case NTP_STR:
1423 		break;
1424 	    case NTP_ADD:
1425 		if (!strcmp("-6", str)) {
1426 			ai_fam_templ = AF_INET6;
1427 			return -1;
1428 		} else if (!strcmp("-4", str)) {
1429 			ai_fam_templ = AF_INET;
1430 			return -1;
1431 		}
1432 		if (!getnetnum(str, &(argp->netnum), (char *)0, 0)) {
1433 			return 0;
1434 		}
1435 		break;
1436 	    case NTP_INT:
1437 	    case NTP_UINT:
1438 		isneg = 0;
1439 		np = str;
1440 		if (*np == '-') {
1441 			np++;
1442 			isneg = 1;
1443 		}
1444 
1445 		argp->uval = 0;
1446 		do {
1447 			cp = strchr(digits, *np);
1448 			if (cp == NULL) {
1449 				(void) fprintf(stderr,
1450 					       "***Illegal integer value %s\n", str);
1451 				return 0;
1452 			}
1453 			argp->uval *= 10;
1454 			argp->uval += (cp - digits);
1455 		} while (*(++np) != '\0');
1456 
1457 		if (isneg) {
1458 			if ((code & ~OPT) == NTP_UINT) {
1459 				(void) fprintf(stderr,
1460 					       "***Value %s should be unsigned\n", str);
1461 				return 0;
1462 			}
1463 			argp->ival = -argp->ival;
1464 		}
1465 		break;
1466 	    case IP_VERSION:
1467 		if (!strcmp("-6", str))
1468 			argp->ival = 6 ;
1469 		else if (!strcmp("-4", str))
1470 			argp->ival = 4 ;
1471 		else {
1472 			(void) fprintf(stderr,
1473 			    "***Version must be either 4 or 6\n");
1474 			return 0;
1475 		}
1476 		break;
1477 	}
1478 
1479 	return 1;
1480 }
1481 
1482 
1483 /*
1484  * getnetnum - given a host name, return its net number
1485  *	       and (optional) full name
1486  */
1487 static int
1488 getnetnum(
1489 	const char *hname,
1490 	sockaddr_u *num,
1491 	char *fullhost,
1492 	int af
1493 	)
1494 {
1495 	int sockaddr_len;
1496 	struct addrinfo hints, *ai = NULL;
1497 
1498 	sockaddr_len = SIZEOF_SOCKADDR(af);
1499 	memset((char *)&hints, 0, sizeof(struct addrinfo));
1500 	hints.ai_flags = AI_CANONNAME;
1501 #ifdef AI_ADDRCONFIG
1502 	hints.ai_flags |= AI_ADDRCONFIG;
1503 #endif
1504 
1505 	/* decodenetnum only works with addresses */
1506 	if (decodenetnum(hname, num)) {
1507 		if (fullhost != 0) {
1508 			getnameinfo(&num->sa, sockaddr_len,
1509 				    fullhost, sizeof(fullhost), NULL, 0,
1510 				    NI_NUMERICHOST);
1511 		}
1512 		return 1;
1513 	} else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1514 		memmove((char *)num, ai->ai_addr, ai->ai_addrlen);
1515 		if (fullhost != 0)
1516 			(void) strcpy(fullhost, ai->ai_canonname);
1517 		return 1;
1518 	} else {
1519 		(void) fprintf(stderr, "***Can't find host %s\n", hname);
1520 		return 0;
1521 	}
1522 	/*NOTREACHED*/
1523 }
1524 
1525 /*
1526  * nntohost - convert network number to host name.  This routine enforces
1527  *	       the showhostnames setting.
1528  */
1529 char *
1530 nntohost(
1531 	sockaddr_u *netnum
1532 	)
1533 {
1534 	if (!showhostnames)
1535 		return stoa(netnum);
1536 
1537 	if (ISREFCLOCKADR(netnum))
1538 		return refnumtoa(netnum);
1539 	return socktohost(netnum);
1540 }
1541 
1542 
1543 /*
1544  * Finally, the built in command handlers
1545  */
1546 
1547 /*
1548  * help - tell about commands, or details of a particular command
1549  */
1550 static void
1551 help(
1552 	struct parse *pcmd,
1553 	FILE *fp
1554 	)
1555 {
1556 	struct xcmd *xcp;
1557 	char *cmd;
1558 	const char *list[100];
1559 	int word, words;
1560         int row, rows;
1561 	int col, cols;
1562 
1563 	if (pcmd->nargs == 0) {
1564 		words = 0;
1565 		for (xcp = builtins; xcp->keyword != 0; xcp++) {
1566 			if (*(xcp->keyword) != '?')
1567 			    list[words++] = xcp->keyword;
1568 		}
1569                 for (xcp = opcmds; xcp->keyword != 0; xcp++)
1570 		    list[words++] = xcp->keyword;
1571 
1572 		qsort(
1573 #ifdef QSORT_USES_VOID_P
1574 		    (void *)
1575 #else
1576 		    (char *)
1577 #endif
1578 			(list), (size_t)(words), sizeof(char *), helpsort);
1579 		col = 0;
1580 		for (word = 0; word < words; word++) {
1581 			int length = strlen(list[word]);
1582 			if (col < length) {
1583 			    col = length;
1584                         }
1585 		}
1586 
1587 		cols = SCREENWIDTH / ++col;
1588                 rows = (words + cols - 1) / cols;
1589 
1590 		(void) fprintf(fp, "ntpdc commands:\n");
1591 
1592 		for (row = 0; row < rows; row++) {
1593                         for (word = row; word < words; word += rows) {
1594 				(void) fprintf(fp, "%-*.*s", col, col-1, list[word]);
1595                         }
1596 			(void) fprintf(fp, "\n");
1597 		}
1598 	} else {
1599 		cmd = pcmd->argval[0].string;
1600 		words = findcmd(cmd, builtins, opcmds, &xcp);
1601 		if (words == 0) {
1602 			(void) fprintf(stderr,
1603 				       "Command `%s' is unknown\n", cmd);
1604 			return;
1605 		} else if (words >= 2) {
1606 			(void) fprintf(stderr,
1607 				       "Command `%s' is ambiguous\n", cmd);
1608 			return;
1609 		}
1610 		(void) fprintf(fp, "function: %s\n", xcp->comment);
1611 		printusage(xcp, fp);
1612 	}
1613 }
1614 
1615 
1616 /*
1617  * helpsort - do hostname qsort comparisons
1618  */
1619 #ifdef QSORT_USES_VOID_P
1620 static int
1621 helpsort(
1622 	const void *t1,
1623 	const void *t2
1624 	)
1625 {
1626 	char const * const * name1 = (char const * const *)t1;
1627 	char const * const * name2 = (char const * const *)t2;
1628 
1629 	return strcmp(*name1, *name2);
1630 }
1631 #else
1632 static int
1633 helpsort(
1634 	char **name1,
1635 	char **name2
1636 	)
1637 {
1638 	return strcmp(*name1, *name2);
1639 }
1640 #endif
1641 
1642 
1643 /*
1644  * printusage - print usage information for a command
1645  */
1646 static void
1647 printusage(
1648 	struct xcmd *xcp,
1649 	FILE *fp
1650 	)
1651 {
1652 	int i, opt46;
1653 
1654 	opt46 = 0;
1655 	(void) fprintf(fp, "usage: %s", xcp->keyword);
1656 	for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
1657 		if (opt46 == 0 && (xcp->arg[i] & ~OPT) == NTP_ADD) {
1658 			(void) fprintf(fp, " [ -4|-6 ]");
1659 			opt46 = 1;
1660 		}
1661 		if (xcp->arg[i] & OPT)
1662 		    (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
1663 		else
1664 		    (void) fprintf(fp, " %s", xcp->desc[i]);
1665 	}
1666 	(void) fprintf(fp, "\n");
1667 }
1668 
1669 
1670 /*
1671  * timeout - set time out time
1672  */
1673 static void
1674 timeout(
1675 	struct parse *pcmd,
1676 	FILE *fp
1677 	)
1678 {
1679 	int val;
1680 
1681 	if (pcmd->nargs == 0) {
1682 		val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
1683 		(void) fprintf(fp, "primary timeout %d ms\n", val);
1684 	} else {
1685 		tvout.tv_sec = pcmd->argval[0].uval / 1000;
1686 		tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000))
1687 			* 1000;
1688 	}
1689 }
1690 
1691 
1692 /*
1693  * my_delay - set delay for auth requests
1694  */
1695 static void
1696 my_delay(
1697 	struct parse *pcmd,
1698 	FILE *fp
1699 	)
1700 {
1701 	int isneg;
1702 	u_long val;
1703 
1704 	if (pcmd->nargs == 0) {
1705 		val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
1706 		(void) fprintf(fp, "delay %lu ms\n", val);
1707 	} else {
1708 		if (pcmd->argval[0].ival < 0) {
1709 			isneg = 1;
1710 			val = (u_long)(-pcmd->argval[0].ival);
1711 		} else {
1712 			isneg = 0;
1713 			val = (u_long)pcmd->argval[0].ival;
1714 		}
1715 
1716 		delay_time.l_ui = val / 1000;
1717 		val %= 1000;
1718 		delay_time.l_uf = val * 4294967;	/* 2**32/1000 */
1719 
1720 		if (isneg)
1721 		    L_NEG(&delay_time);
1722 	}
1723 }
1724 
1725 
1726 /*
1727  * host - set the host we are dealing with.
1728  */
1729 static void
1730 host(
1731 	struct parse *pcmd,
1732 	FILE *fp
1733 	)
1734 {
1735 	int i;
1736 
1737 	if (pcmd->nargs == 0) {
1738 		if (havehost)
1739 		    (void) fprintf(fp, "current host is %s\n", currenthost);
1740 		else
1741 		    (void) fprintf(fp, "no current host\n");
1742 		return;
1743 	}
1744 
1745 	i = 0;
1746 	if (pcmd->nargs == 2) {
1747 		if (!strcmp("-4", pcmd->argval[i].string))
1748 			ai_fam_templ = AF_INET;
1749 		else if (!strcmp("-6", pcmd->argval[i].string))
1750 			ai_fam_templ = AF_INET6;
1751 		else {
1752 			if (havehost)
1753 				(void) fprintf(fp,
1754 				    "current host remains %s\n", currenthost);
1755 			else
1756 				(void) fprintf(fp, "still no current host\n");
1757 			return;
1758 		}
1759 		i = 1;
1760 	}
1761 	if (openhost(pcmd->argval[i].string)) {
1762 		(void) fprintf(fp, "current host set to %s\n", currenthost);
1763 	} else {
1764 		if (havehost)
1765 		    (void) fprintf(fp,
1766 				   "current host remains %s\n", currenthost);
1767 		else
1768 		    (void) fprintf(fp, "still no current host\n");
1769 	}
1770 }
1771 
1772 
1773 /*
1774  * keyid - get a keyid to use for authenticating requests
1775  */
1776 static void
1777 keyid(
1778 	struct parse *pcmd,
1779 	FILE *fp
1780 	)
1781 {
1782 	if (pcmd->nargs == 0) {
1783 		if (info_auth_keyid == 0 && !keyid_entered)
1784 		    (void) fprintf(fp, "no keyid defined\n");
1785 		else if (info_auth_keyid == 0 && keyid_entered)
1786 		    (void) fprintf(fp, "no keyid will be sent\n");
1787 		else
1788 		    (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
1789 	} else {
1790 		info_auth_keyid = pcmd->argval[0].uval;
1791 		keyid_entered = 1;
1792 	}
1793 }
1794 
1795 
1796 /*
1797  * keytype - get type of key to use for authenticating requests
1798  */
1799 static void
1800 keytype(
1801 	struct parse *pcmd,
1802 	FILE *fp
1803 	)
1804 {
1805 	const char *	digest_name;
1806 	size_t		digest_len;
1807 	int		key_type;
1808 
1809 	if (!pcmd->nargs) {
1810 		fprintf(fp, "keytype is %s with %u octet digests\n",
1811 			keytype_name(info_auth_keytype),
1812 			info_auth_hashlen);
1813 		return;
1814 	}
1815 
1816 	digest_name = pcmd->argval[0].string;
1817 	digest_len = 0;
1818 	key_type = keytype_from_text(digest_name, &digest_len);
1819 
1820 	if (!key_type) {
1821 		fprintf(fp, "keytype must be 'md5'%s\n",
1822 #ifdef OPENSSL
1823 			" or a digest type provided by OpenSSL");
1824 #else
1825 			"");
1826 #endif
1827 		return;
1828 	}
1829 
1830 	info_auth_keytype = key_type;
1831 	info_auth_hashlen = digest_len;
1832 }
1833 
1834 
1835 /*
1836  * passwd - get an authentication key
1837  */
1838 /*ARGSUSED*/
1839 static void
1840 passwd(
1841 	struct parse *pcmd,
1842 	FILE *fp
1843 	)
1844 {
1845 	char *pass;
1846 
1847 	if (info_auth_keyid == 0) {
1848 		info_auth_keyid = getkeyid("Keyid: ");
1849 		if (info_auth_keyid == 0) {
1850 			(void)fprintf(fp, "Keyid must be defined\n");
1851 			return;
1852 		}
1853 	}
1854 	if (!interactive) {
1855 		authusekey(info_auth_keyid, info_auth_keytype,
1856 			   (u_char *)pcmd->argval[0].string);
1857 		authtrust(info_auth_keyid, 1);
1858 	} else {
1859 		pass = getpass("MD5 Password: ");
1860 		if (*pass == '\0')
1861 		    (void) fprintf(fp, "Password unchanged\n");
1862 		else {
1863 		    authusekey(info_auth_keyid, info_auth_keytype,
1864 			       (u_char *)pass);
1865 		    authtrust(info_auth_keyid, 1);
1866 		}
1867 	}
1868 }
1869 
1870 
1871 /*
1872  * hostnames - set the showhostnames flag
1873  */
1874 static void
1875 hostnames(
1876 	struct parse *pcmd,
1877 	FILE *fp
1878 	)
1879 {
1880 	if (pcmd->nargs == 0) {
1881 		if (showhostnames)
1882 		    (void) fprintf(fp, "hostnames being shown\n");
1883 		else
1884 		    (void) fprintf(fp, "hostnames not being shown\n");
1885 	} else {
1886 		if (STREQ(pcmd->argval[0].string, "yes"))
1887 		    showhostnames = 1;
1888 		else if (STREQ(pcmd->argval[0].string, "no"))
1889 		    showhostnames = 0;
1890 		else
1891 		    (void)fprintf(stderr, "What?\n");
1892 	}
1893 }
1894 
1895 
1896 /*
1897  * setdebug - set/change debugging level
1898  */
1899 static void
1900 setdebug(
1901 	struct parse *pcmd,
1902 	FILE *fp
1903 	)
1904 {
1905 	if (pcmd->nargs == 0) {
1906 		(void) fprintf(fp, "debug level is %d\n", debug);
1907 		return;
1908 	} else if (STREQ(pcmd->argval[0].string, "no")) {
1909 		debug = 0;
1910 	} else if (STREQ(pcmd->argval[0].string, "more")) {
1911 		debug++;
1912 	} else if (STREQ(pcmd->argval[0].string, "less")) {
1913 		debug--;
1914 	} else {
1915 		(void) fprintf(fp, "What?\n");
1916 		return;
1917 	}
1918 	(void) fprintf(fp, "debug level set to %d\n", debug);
1919 }
1920 
1921 
1922 /*
1923  * quit - stop this nonsense
1924  */
1925 /*ARGSUSED*/
1926 static void
1927 quit(
1928 	struct parse *pcmd,
1929 	FILE *fp
1930 	)
1931 {
1932 	if (havehost)
1933 	    closesocket(sockfd);
1934 	exit(0);
1935 }
1936 
1937 
1938 /*
1939  * version - print the current version number
1940  */
1941 /*ARGSUSED*/
1942 static void
1943 version(
1944 	struct parse *pcmd,
1945 	FILE *fp
1946 	)
1947 {
1948 
1949 	(void) fprintf(fp, "%s\n", Version);
1950 	return;
1951 }
1952 
1953 
1954 /*
1955  * warning - print a warning message
1956  */
1957 static void
1958 warning(
1959 	const char *fmt,
1960 	const char *st1,
1961 	const char *st2
1962 	)
1963 {
1964 	(void) fprintf(stderr, "%s: ", progname);
1965 	(void) fprintf(stderr, fmt, st1, st2);
1966 	(void) fprintf(stderr, ": ");
1967 	perror("");
1968 }
1969 
1970 
1971 /*
1972  * error - print a message and exit
1973  */
1974 static void
1975 error(
1976 	const char *fmt,
1977 	const char *st1,
1978 	const char *st2
1979 	)
1980 {
1981 	warning(fmt, st1, st2);
1982 	exit(1);
1983 }
1984 
1985 /*
1986  * getkeyid - prompt the user for a keyid to use
1987  */
1988 static u_long
1989 getkeyid(
1990 	const char *keyprompt
1991 	)
1992 {
1993 	register char *p;
1994 	register int c;
1995 	FILE *fi;
1996 	char pbuf[20];
1997 
1998 #ifndef SYS_WINNT
1999 	if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2000 #else
2001 	if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2002 #endif /* SYS_WINNT */
2003 		fi = stdin;
2004 	    else
2005 		setbuf(fi, (char *)NULL);
2006 	fprintf(stderr, "%s", keyprompt); fflush(stderr);
2007 	for (p=pbuf; (c = getc(fi))!='\n' && c!=EOF;) {
2008 		if (p < &pbuf[18])
2009 		    *p++ = (char) c;
2010 	}
2011 	*p = '\0';
2012 	if (fi != stdin)
2013 	    fclose(fi);
2014 	return (u_int32)atoi(pbuf);
2015 }
2016