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