Expand PMF_FN_* macros.
[netbsd-mini2440.git] / dist / ntp / ntpdc / ntpdc.c
blob6dcaa66f1047a0ce455c2511426d68009902607c
1 /* $NetBSD: ntpdc.c,v 1.9 2006/06/11 19:34:21 kardel Exp $ */
3 /*
4 * ntpdc - control and monitor your ntpd daemon
5 */
7 #include <stdio.h>
9 #include <ctype.h>
10 #include <signal.h>
11 #include <setjmp.h>
13 #include "ntpdc.h"
14 #include "ntp_select.h"
15 #include "ntp_io.h"
16 #include "ntp_stdlib.h"
17 /* Don't include ISC's version of IPv6 variables and structures */
18 #define ISC_IPV6_H 1
19 #include "isc/net.h"
20 #include "isc/result.h"
22 #include "ntpdc-opts.h"
24 #ifdef SYS_WINNT
25 # include <Mswsock.h>
26 # include <io.h>
27 #else
28 # define closesocket close
29 #endif /* SYS_WINNT */
31 #if defined(HAVE_LIBREADLINE) || defined (HAVE_LIBEDIT)
32 # include <readline/readline.h>
33 # include <readline/history.h>
34 #endif /* HAVE_LIBREADLINE || HAVE_LIBEDIT */
36 #ifdef SYS_VXWORKS
37 /* vxWorks needs mode flag -casey*/
38 # define open(name, flags) open(name, flags, 0777)
39 # define SERVER_PORT_NUM 123
40 #endif
42 /* We use COMMAND as an autogen keyword */
43 #ifdef COMMAND
44 # undef COMMAND
45 #endif
48 * Because we now potentially understand a lot of commands (and
49 * it requires a lot of commands to talk to ntpd) we will run
50 * interactive if connected to a terminal.
52 static int interactive = 0; /* set to 1 when we should prompt */
53 static const char * prompt = "ntpdc> "; /* prompt to ask him about */
56 * Keyid used for authenticated requests. Obtained on the fly.
58 static u_long info_auth_keyid;
59 static int keyid_entered = 0;
62 * Type of key md5
64 #define KEY_TYPE_MD5 4
66 static int info_auth_keytype = KEY_TYPE_MD5; /* MD5 */
67 u_long current_time; /* needed by authkeys; not used */
70 * for get_systime()
72 s_char sys_precision; /* local clock precision (log2 s) */
74 int ntpdcmain P((int, char **));
76 * Built in command handler declarations
78 static int openhost P((const char *));
79 static int sendpkt P((char *, int));
80 static void growpktdata P((void));
81 static int getresponse P((int, int, int *, int *, char **, int));
82 static int sendrequest P((int, int, int, int, int, char *));
83 static void getcmds P((void));
84 static RETSIGTYPE abortcmd P((int));
85 static void docmd P((const char *));
86 static void tokenize P((const char *, char **, int *));
87 static int findcmd P((char *, struct xcmd *, struct xcmd *, struct xcmd **));
88 static int getarg P((char *, int, arg_v *));
89 static int getnetnum P((const char *, struct sockaddr_storage *, char *, int));
90 static void help P((struct parse *, FILE *));
91 #ifdef QSORT_USES_VOID_P
92 static int helpsort P((const void *, const void *));
93 #else
94 static int helpsort P((char **, char **));
95 #endif
96 static void printusage P((struct xcmd *, FILE *));
97 static void timeout P((struct parse *, FILE *));
98 static void my_delay P((struct parse *, FILE *));
99 static void host P((struct parse *, FILE *));
100 static void keyid P((struct parse *, FILE *));
101 static void keytype P((struct parse *, FILE *));
102 static void passwd P((struct parse *, FILE *));
103 static void hostnames P((struct parse *, FILE *));
104 static void setdebug P((struct parse *, FILE *));
105 static void quit P((struct parse *, FILE *));
106 static void version P((struct parse *, FILE *));
107 static void warning P((const char *, const char *, const char *));
108 static void error P((const char *, const char *, const char *));
109 static u_long getkeyid P((const char *));
114 * Built-in commands we understand
116 static struct xcmd builtins[] = {
117 { "?", help, { OPT|NTP_STR, NO, NO, NO },
118 { "command", "", "", "" },
119 "tell the use and syntax of commands" },
120 { "help", help, { OPT|NTP_STR, NO, NO, NO },
121 { "command", "", "", "" },
122 "tell the use and syntax of commands" },
123 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
124 { "msec", "", "", "" },
125 "set the primary receive time out" },
126 { "delay", my_delay, { OPT|NTP_INT, NO, NO, NO },
127 { "msec", "", "", "" },
128 "set the delay added to encryption time stamps" },
129 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
130 { "-4|-6", "hostname", "", "" },
131 "specify the host whose NTP server we talk to" },
132 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
133 { "", "", "", "" },
134 "specify a password to use for authenticated requests"},
135 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
136 { "yes|no", "", "", "" },
137 "specify whether hostnames or net numbers are printed"},
138 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
139 { "no|more|less", "", "", "" },
140 "set/change debugging level" },
141 { "quit", quit, { NO, NO, NO, NO },
142 { "", "", "", "" },
143 "exit ntpdc" },
144 { "exit", quit, { NO, NO, NO, NO },
145 { "", "", "", "" },
146 "exit ntpdc" },
147 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
148 { "key#", "", "", "" },
149 "set/show keyid to use for authenticated requests" },
150 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
151 { "(md5|des)", "", "", "" },
152 "set/show key authentication type for authenticated requests (des|md5)" },
153 { "version", version, { NO, NO, NO, NO },
154 { "", "", "", "" },
155 "print version number" },
156 { 0, 0, { NO, NO, NO, NO },
157 { "", "", "", "" }, "" }
162 * Default values we use.
164 #define DEFTIMEOUT (5) /* 5 second time out */
165 #define DEFSTIMEOUT (2) /* 2 second time out after first */
166 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
167 #define DEFHOST "localhost" /* default host name */
168 #define LENHOSTNAME 256 /* host name is 256 characters long */
169 #define MAXCMDS 100 /* maximum commands on cmd line */
170 #define MAXHOSTS 200 /* maximum hosts on cmd line */
171 #define MAXLINE 512 /* maximum line length */
172 #define MAXTOKENS (1+1+MAXARGS+MOREARGS+2) /* maximum number of usable tokens */
173 #define SCREENWIDTH 78 /* nominal screen width in columns */
176 * Some variables used and manipulated locally
178 static struct timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
179 static struct timeval tvsout = { DEFSTIMEOUT, 0 }; /* secondary time out */
180 static l_fp delay_time; /* delay time */
181 static char currenthost[LENHOSTNAME]; /* current host name */
182 int showhostnames = 1; /* show host names by default */
184 static int ai_fam_templ; /* address family */
185 static int ai_fam_default; /* default address family */
186 static SOCKET sockfd; /* fd socket is opened on */
187 static int havehost = 0; /* set to 1 when host open */
188 int s_port = 0;
190 #if defined (SYS_WINNT) || defined (SYS_VXWORKS)
191 char password[9];
192 #endif /* SYS_WINNT || SYS_VXWORKS */
194 #ifdef SYS_WINNT
195 DWORD NumberOfBytesWritten;
197 HANDLE TimerThreadHandle = NULL; /* 1998/06/03 - Used in ntplib/machines.c */
198 void timer(void) { ; }; /* 1998/06/03 - Used in ntplib/machines.c */
200 #endif /* SYS_WINNT */
203 * Holds data returned from queries. We allocate INITDATASIZE
204 * octets to begin with, increasing this as we need to.
206 #define INITDATASIZE (sizeof(struct resp_pkt) * 16)
207 #define INCDATASIZE (sizeof(struct resp_pkt) * 8)
209 static char *pktdata;
210 static int pktdatasize;
213 * These are used to help the magic with old and new versions of ntpd.
215 int impl_ver = IMPL_XNTPD;
216 static int req_pkt_size = REQ_LEN_NOMAC;
219 * For commands typed on the command line (with the -c option)
221 static int numcmds = 0;
222 static const char *ccmds[MAXCMDS];
223 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
226 * When multiple hosts are specified.
228 static int numhosts = 0;
229 static const char *chosts[MAXHOSTS];
230 #define ADDHOST(cp) if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp)
233 * Error codes for internal use
235 #define ERR_INCOMPLETE 16
236 #define ERR_TIMEOUT 17
239 * Macro definitions we use
241 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
242 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
243 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
246 * For converting time stamps to dates
248 #define JAN_1970 2208988800 /* 1970 - 1900 in seconds */
251 * Jump buffer for longjumping back to the command level
253 static jmp_buf interrupt_buf;
254 static volatile int jump = 0;
257 * Pointer to current output unit
259 static FILE *current_output;
262 * Command table imported from ntpdc_ops.c
264 extern struct xcmd opcmds[];
266 char *progname;
267 volatile int debug;
269 #ifdef NO_MAIN_ALLOWED
270 CALL(ntpdc,"ntpdc",ntpdcmain);
271 #else
273 main(
274 int argc,
275 char *argv[]
278 return ntpdcmain(argc, argv);
280 #endif
282 #ifdef SYS_VXWORKS
283 void clear_globals(void)
285 showhostnames = 0; /* show host names by default */
286 havehost = 0; /* set to 1 when host open */
287 numcmds = 0;
288 numhosts = 0;
290 #endif
293 * main - parse arguments and handle options
296 ntpdcmain(
297 int argc,
298 char *argv[]
301 extern int ntp_optind;
303 delay_time.l_ui = 0;
304 delay_time.l_uf = DEFDELAY;
306 #ifdef SYS_VXWORKS
307 clear_globals();
308 taskPrioritySet(taskIdSelf(), 100 );
309 #endif
311 #ifdef SYS_WINNT
312 if (!Win32InitSockets())
314 fprintf(stderr, "No useable winsock.dll:");
315 exit(1);
317 #endif /* SYS_WINNT */
319 /* Check to see if we have IPv6. Otherwise force the -4 flag */
320 if (isc_net_probeipv6() != ISC_R_SUCCESS) {
321 ai_fam_default = AF_INET;
324 progname = argv[0];
327 int optct = optionProcess(&ntpdcOptions, argc, argv);
328 argc -= optct;
329 argv += optct;
332 switch (WHICH_IDX_IPV4) {
333 case INDEX_OPT_IPV4:
334 ai_fam_templ = AF_INET;
335 break;
336 case INDEX_OPT_IPV6:
337 ai_fam_templ = AF_INET6;
338 break;
339 default:
340 ai_fam_templ = ai_fam_default;
341 break;
344 if (HAVE_OPT(COMMAND)) {
345 int cmdct = STACKCT_OPT( COMMAND );
346 const char** cmds = STACKLST_OPT( COMMAND );
348 while (cmdct-- > 0) {
349 ADDCMD(*cmds++);
353 debug = DESC(DEBUG_LEVEL).optOccCt;
355 if (HAVE_OPT(INTERACTIVE)) {
356 interactive = 1;
359 if (HAVE_OPT(NUMERIC)) {
360 showhostnames = 0;
363 if (HAVE_OPT(LISTPEERS)) {
364 ADDCMD("listpeers");
367 if (HAVE_OPT(PEERS)) {
368 ADDCMD("peers");
371 if (HAVE_OPT(SHOWPEERS)) {
372 ADDCMD("dmpeers");
375 if (ntp_optind == argc) {
376 ADDHOST(DEFHOST);
377 } else {
378 for (; ntp_optind < argc; ntp_optind++)
379 ADDHOST(argv[ntp_optind]);
382 if (numcmds == 0 && interactive == 0
383 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
384 interactive = 1;
387 #if 0
388 ai_fam_templ = ai_fam_default;
389 while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF)
390 switch (c) {
391 case '4':
392 ai_fam_templ = AF_INET;
393 break;
394 case '6':
395 ai_fam_templ = AF_INET6;
396 break;
397 case 'c':
398 ADDCMD(ntp_optarg);
399 break;
400 case 'd':
401 ++debug;
402 break;
403 case 'i':
404 interactive = 1;
405 break;
406 case 'l':
407 ADDCMD("listpeers");
408 break;
409 case 'n':
410 showhostnames = 0;
411 break;
412 case 'p':
413 ADDCMD("peers");
414 break;
415 case 's':
416 ADDCMD("dmpeers");
417 break;
418 default:
419 errflg++;
420 break;
423 if (errflg) {
424 (void) fprintf(stderr,
425 "usage: %s [-46dilnps] [-c cmd] host ...\n",
426 progname);
427 exit(2);
430 if (ntp_optind == argc) {
431 ADDHOST(DEFHOST);
432 } else {
433 for (; ntp_optind < argc; ntp_optind++)
434 ADDHOST(argv[ntp_optind]);
437 if (numcmds == 0 && interactive == 0
438 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
439 interactive = 1;
441 #endif
443 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
444 if (interactive)
445 (void) signal_no_reset(SIGINT, abortcmd);
446 #endif /* SYS_WINNT */
449 * Initialize the packet data buffer
451 pktdata = (char *)malloc(INITDATASIZE);
452 if (pktdata == NULL) {
453 (void) fprintf(stderr, "%s: malloc() failed!\n", progname);
454 exit(1);
456 pktdatasize = INITDATASIZE;
458 if (numcmds == 0) {
459 (void) openhost(chosts[0]);
460 getcmds();
461 } else {
462 int ihost;
463 int icmd;
465 for (ihost = 0; ihost < numhosts; ihost++) {
466 if (openhost(chosts[ihost]))
467 for (icmd = 0; icmd < numcmds; icmd++) {
468 if (numhosts > 1)
469 printf ("--- %s ---\n",chosts[ihost]);
470 docmd(ccmds[icmd]);
474 #ifdef SYS_WINNT
475 WSACleanup();
476 #endif
477 return(0);
478 } /* main end */
482 * openhost - open a socket to a host
484 static int
485 openhost(
486 const char *hname
489 char temphost[LENHOSTNAME];
490 int a_info, i;
491 struct addrinfo hints, *ai = NULL;
492 register const char *cp;
493 char name[LENHOSTNAME];
494 char service[5];
497 * We need to get by the [] if they were entered
500 cp = hname;
502 if (*cp == '[') {
503 cp++;
504 for(i = 0; *cp != ']'; cp++, i++)
505 name[i] = *cp;
506 name[i] = '\0';
507 hname = name;
511 * First try to resolve it as an ip address and if that fails,
512 * do a fullblown (dns) lookup. That way we only use the dns
513 * when it is needed and work around some implementations that
514 * will return an "IPv4-mapped IPv6 address" address if you
515 * give it an IPv4 address to lookup.
517 strcpy(service, "ntp");
518 memset((char *)&hints, 0, sizeof(struct addrinfo));
519 hints.ai_family = ai_fam_templ;
520 hints.ai_protocol = IPPROTO_UDP;
521 hints.ai_socktype = SOCK_DGRAM;
522 hints.ai_flags = AI_NUMERICHOST;
524 a_info = getaddrinfo(hname, service, &hints, &ai);
525 if (a_info == EAI_NONAME
526 #ifdef EAI_NODATA
527 || a_info == EAI_NODATA
528 #endif
530 hints.ai_flags = AI_CANONNAME;
531 #ifdef AI_ADDRCONFIG
532 hints.ai_flags |= AI_ADDRCONFIG;
533 #endif
534 a_info = getaddrinfo(hname, service, &hints, &ai);
536 /* Some older implementations don't like AI_ADDRCONFIG. */
537 if (a_info == EAI_BADFLAGS) {
538 hints.ai_flags = AI_CANONNAME;
539 a_info = getaddrinfo(hname, service, &hints, &ai);
541 if (a_info != 0) {
542 (void) fprintf(stderr, "%s\n", gai_strerror(a_info));
543 if (ai != NULL)
544 freeaddrinfo(ai);
545 return 0;
548 if (ai->ai_canonname == NULL) {
549 strncpy(temphost, stoa((struct sockaddr_storage *)ai->ai_addr),
550 LENHOSTNAME);
551 temphost[LENHOSTNAME-1] = '\0';
552 } else {
553 strncpy(temphost, ai->ai_canonname, LENHOSTNAME);
554 temphost[LENHOSTNAME-1] = '\0';
557 if (debug > 2)
558 printf("Opening host %s\n", temphost);
560 if (havehost == 1) {
561 if (debug > 2)
562 printf("Closing old host %s\n", currenthost);
563 (void) closesocket(sockfd);
564 havehost = 0;
566 (void) strcpy(currenthost, temphost);
568 /* port maps to the same in both families */
569 s_port = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port;
570 #ifdef SYS_VXWORKS
571 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
572 if (ai->ai_family == AF_INET)
573 *(struct sockaddr_in *)&hostaddr=
574 *((struct sockaddr_in *)ai->ai_addr);
575 else
576 *(struct sockaddr_in6 *)&hostaddr=
577 *((struct sockaddr_in6 *)ai->ai_addr);
578 #endif /* SYS_VXWORKS */
580 #ifdef SYS_WINNT
582 int optionValue = SO_SYNCHRONOUS_NONALERT;
583 int err;
585 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue));
586 if (err != NO_ERROR) {
587 (void) fprintf(stderr, "cannot open nonoverlapped sockets\n");
588 exit(1);
592 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
593 if (sockfd == INVALID_SOCKET) {
594 error("socket", "", "");
595 exit(-1);
597 #else
598 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
599 if (sockfd == -1)
600 error("socket", "", "");
601 #endif /* SYS_WINNT */
604 #ifdef NEED_RCVBUF_SLOP
605 # ifdef SO_RCVBUF
607 int rbufsize = INITDATASIZE + 2048; /* 2K for slop */
609 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
610 &rbufsize, sizeof(int)) == -1)
611 error("setsockopt", "", "");
613 # endif
614 #endif
616 #ifdef SYS_VXWORKS
617 if (connect(sockfd, (struct sockaddr *)&hostaddr,
618 sizeof(hostaddr)) == -1)
619 #else
620 if (connect(sockfd, (struct sockaddr *)ai->ai_addr,
621 ai->ai_addrlen) == -1)
622 #endif /* SYS_VXWORKS */
623 error("connect", "", "");
624 if (ai != NULL)
625 freeaddrinfo(ai);
626 havehost = 1;
627 req_pkt_size = REQ_LEN_NOMAC;
628 impl_ver = IMPL_XNTPD;
629 return 1;
633 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
635 * sendpkt - send a packet to the remote host
637 static int
638 sendpkt(
639 char *xdata,
640 int xdatalen
643 if (send(sockfd, xdata, (size_t)xdatalen, 0) == -1) {
644 warning("write to %s failed", currenthost, "");
645 return -1;
648 return 0;
653 * growpktdata - grow the packet data area
655 static void
656 growpktdata(void)
658 pktdatasize += INCDATASIZE;
659 pktdata = (char *)realloc(pktdata, (unsigned)pktdatasize);
660 if (pktdata == 0) {
661 (void) fprintf(stderr, "%s: realloc() failed!\n", progname);
662 exit(1);
668 * getresponse - get a (series of) response packet(s) and return the data
670 static int
671 getresponse(
672 int implcode,
673 int reqcode,
674 int *ritems,
675 int *rsize,
676 char **rdata,
677 int esize
680 struct resp_pkt rpkt;
681 struct timeval tvo;
682 int items;
683 int i;
684 int size;
685 int datasize;
686 char *datap;
687 char *tmp_data;
688 char haveseq[MAXSEQ+1];
689 int firstpkt;
690 int lastseq;
691 int numrecv;
692 int seq;
693 fd_set fds;
694 int n;
695 int pad;
698 * This is pretty tricky. We may get between 1 and many packets
699 * back in response to the request. We peel the data out of
700 * each packet and collect it in one long block. When the last
701 * packet in the sequence is received we'll know how many we
702 * should have had. Note we use one long time out, should reconsider.
704 *ritems = 0;
705 *rsize = 0;
706 firstpkt = 1;
707 numrecv = 0;
708 *rdata = datap = pktdata;
709 lastseq = 999; /* too big to be a sequence number */
710 memset(haveseq, 0, sizeof(haveseq));
711 FD_ZERO(&fds);
713 again:
714 if (firstpkt)
715 tvo = tvout;
716 else
717 tvo = tvsout;
719 FD_SET(sockfd, &fds);
720 n = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvo);
722 if (n == -1) {
723 warning("select fails", "", "");
724 return -1;
726 if (n == 0) {
728 * Timed out. Return what we have
730 if (firstpkt) {
731 (void) fprintf(stderr,
732 "%s: timed out, nothing received\n", currenthost);
733 return ERR_TIMEOUT;
734 } else {
735 (void) fprintf(stderr,
736 "%s: timed out with incomplete data\n",
737 currenthost);
738 if (debug) {
739 printf("Received sequence numbers");
740 for (n = 0; n <= MAXSEQ; n++)
741 if (haveseq[n])
742 printf(" %d,", n);
743 if (lastseq != 999)
744 printf(" last frame received\n");
745 else
746 printf(" last frame not received\n");
748 return ERR_INCOMPLETE;
752 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
753 if (n == -1) {
754 warning("read", "", "");
755 return -1;
760 * Check for format errors. Bug proofing.
762 if (n < RESP_HEADER_SIZE) {
763 if (debug)
764 printf("Short (%d byte) packet received\n", n);
765 goto again;
767 if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION ||
768 INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) {
769 if (debug)
770 printf("Packet received with version %d\n",
771 INFO_VERSION(rpkt.rm_vn_mode));
772 goto again;
774 if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) {
775 if (debug)
776 printf("Packet received with mode %d\n",
777 INFO_MODE(rpkt.rm_vn_mode));
778 goto again;
780 if (INFO_IS_AUTH(rpkt.auth_seq)) {
781 if (debug)
782 printf("Encrypted packet received\n");
783 goto again;
785 if (!ISRESPONSE(rpkt.rm_vn_mode)) {
786 if (debug)
787 printf("Received request packet, wanted response\n");
788 goto again;
790 if (INFO_MBZ(rpkt.mbz_itemsize) != 0) {
791 if (debug)
792 printf("Received packet with nonzero MBZ field!\n");
793 goto again;
797 * Check implementation/request. Could be old data getting to us.
799 if (rpkt.implementation != implcode || rpkt.request != reqcode) {
800 if (debug)
801 printf(
802 "Received implementation/request of %d/%d, wanted %d/%d",
803 rpkt.implementation, rpkt.request,
804 implcode, reqcode);
805 goto again;
809 * Check the error code. If non-zero, return it.
811 if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) {
812 if (debug && ISMORE(rpkt.rm_vn_mode)) {
813 printf("Error code %d received on not-final packet\n",
814 INFO_ERR(rpkt.err_nitems));
816 return (int)INFO_ERR(rpkt.err_nitems);
820 * Collect items and size. Make sure they make sense.
822 items = INFO_NITEMS(rpkt.err_nitems);
823 size = INFO_ITEMSIZE(rpkt.mbz_itemsize);
824 if (esize > size)
825 pad = esize - size;
826 else
827 pad = 0;
828 if ((datasize = items*size) > (n-RESP_HEADER_SIZE)) {
829 if (debug)
830 printf(
831 "Received items %d, size %d (total %d), data in packet is %d\n",
832 items, size, datasize, n-RESP_HEADER_SIZE);
833 goto again;
837 * If this isn't our first packet, make sure the size matches
838 * the other ones.
840 if (!firstpkt && esize != *rsize) {
841 if (debug)
842 printf("Received itemsize %d, previous %d\n",
843 size, *rsize);
844 goto again;
847 * If we've received this before, +toss it
849 seq = INFO_SEQ(rpkt.auth_seq);
850 if (haveseq[seq]) {
851 if (debug)
852 printf("Received duplicate sequence number %d\n", seq);
853 goto again;
855 haveseq[seq] = 1;
858 * If this is the last in the sequence, record that.
860 if (!ISMORE(rpkt.rm_vn_mode)) {
861 if (lastseq != 999) {
862 printf("Received second end sequence packet\n");
863 goto again;
865 lastseq = seq;
869 * So far, so good. Copy this data into the output array.
871 if ((datap + datasize + (pad * items)) > (pktdata + pktdatasize)) {
872 int offset = datap - pktdata;
873 growpktdata();
874 *rdata = pktdata; /* might have been realloced ! */
875 datap = pktdata + offset;
878 * We now move the pointer along according to size and number of
879 * items. This is so we can play nice with older implementations
882 tmp_data = (char *)rpkt.data;
883 for(i = 0; i <items; i++){
884 memmove(datap, tmp_data, (unsigned)size);
885 tmp_data += size;
886 memset(datap + size, 0, pad);
887 datap += size + pad;
890 if (firstpkt) {
891 firstpkt = 0;
892 *rsize = size + pad;
894 *ritems += items;
897 * Finally, check the count of received packets. If we've got them
898 * all, return
900 ++numrecv;
901 if (numrecv <= lastseq)
902 goto again;
903 return INFO_OKAY;
908 * sendrequest - format and send a request packet
910 static int
911 sendrequest(
912 int implcode,
913 int reqcode,
914 int auth,
915 int qitems,
916 int qsize,
917 char *qdata
920 struct req_pkt qpkt;
921 int datasize;
923 memset((char *)&qpkt, 0, sizeof qpkt);
925 qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
926 qpkt.implementation = (u_char)implcode;
927 qpkt.request = (u_char)reqcode;
929 datasize = qitems * qsize;
930 if (datasize != 0 && qdata != NULL) {
931 memmove((char *)qpkt.data, qdata, (unsigned)datasize);
932 qpkt.err_nitems = ERR_NITEMS(0, qitems);
933 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);
934 } else {
935 qpkt.err_nitems = ERR_NITEMS(0, 0);
936 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize); /* allow for optional first item */
939 if (!auth || (keyid_entered && info_auth_keyid == 0)) {
940 qpkt.auth_seq = AUTH_SEQ(0, 0);
941 return sendpkt((char *)&qpkt, req_pkt_size);
942 } else {
943 l_fp ts;
944 int maclen = 0;
945 const char *pass = "\0";
946 struct req_pkt_tail *qpktail;
948 qpktail = (struct req_pkt_tail *)((char *)&qpkt + req_pkt_size
949 + MAX_MAC_LEN - sizeof(struct req_pkt_tail));
951 if (info_auth_keyid == 0) {
952 if (((struct conf_peer *)qpkt.data)->keyid > 0)
953 info_auth_keyid = ((struct conf_peer *)qpkt.data)->keyid;
954 else {
955 maclen = getkeyid("Keyid: ");
956 if (maclen == 0) {
957 (void) fprintf(stderr,
958 "Invalid key identifier\n");
959 return 1;
961 info_auth_keyid = maclen;
964 if (!authistrusted(info_auth_keyid)) {
965 pass = getpass("MD5 Password: ");
966 if (*pass == '\0') {
967 (void) fprintf(stderr,
968 "Invalid password\n");
969 return (1);
972 authusekey(info_auth_keyid, info_auth_keytype, (const u_char *)pass);
973 authtrust(info_auth_keyid, 1);
974 qpkt.auth_seq = AUTH_SEQ(1, 0);
975 qpktail->keyid = htonl(info_auth_keyid);
976 get_systime(&ts);
977 L_ADD(&ts, &delay_time);
978 HTONL_FP(&ts, &qpktail->tstamp);
979 maclen = authencrypt(info_auth_keyid, (u_int32 *)&qpkt,
980 req_pkt_size);
981 if (maclen == 0) {
982 (void) fprintf(stderr, "Key not found\n");
983 return (1);
985 return sendpkt((char *)&qpkt, (int)(req_pkt_size + maclen));
987 /*NOTREACHED*/
992 * doquery - send a request and process the response
995 doquery(
996 int implcode,
997 int reqcode,
998 int auth,
999 int qitems,
1000 int qsize,
1001 char *qdata,
1002 int *ritems,
1003 int *rsize,
1004 char **rdata,
1005 int quiet_mask,
1006 int esize
1009 int res;
1010 char junk[512];
1011 fd_set fds;
1012 struct timeval tvzero;
1015 * Check to make sure host is open
1017 if (!havehost) {
1018 (void) fprintf(stderr, "***No host open, use `host' command\n");
1019 return -1;
1023 * Poll the socket and clear out any pending data
1025 again:
1026 do {
1027 tvzero.tv_sec = tvzero.tv_usec = 0;
1028 FD_ZERO(&fds);
1029 FD_SET(sockfd, &fds);
1030 res = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
1032 if (res == -1) {
1033 warning("polling select", "", "");
1034 return -1;
1035 } else if (res > 0)
1037 (void) recv(sockfd, junk, sizeof junk, 0);
1038 } while (res > 0);
1042 * send a request
1044 res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata);
1045 if (res != 0)
1046 return res;
1049 * Get the response. If we got a standard error, print a message
1051 res = getresponse(implcode, reqcode, ritems, rsize, rdata, esize);
1054 * Try to be compatible with older implementations of ntpd.
1056 if (res == INFO_ERR_FMT && req_pkt_size != 48) {
1057 int oldsize;
1059 oldsize = req_pkt_size;
1061 switch(req_pkt_size) {
1062 case REQ_LEN_NOMAC:
1063 req_pkt_size = 160;
1064 break;
1065 case 160:
1066 req_pkt_size = 48;
1067 break;
1069 if (impl_ver == IMPL_XNTPD) {
1070 fprintf(stderr,
1071 "***Warning changing to older implementation\n");
1072 return INFO_ERR_IMPL;
1075 fprintf(stderr,
1076 "***Warning changing the request packet size from %d to %d\n",
1077 oldsize, req_pkt_size);
1078 goto again;
1081 /* log error message if not told to be quiet */
1082 if ((res > 0) && (((1 << res) & quiet_mask) == 0)) {
1083 switch(res) {
1084 case INFO_ERR_IMPL:
1085 /* Give us a chance to try the older implementation. */
1086 if (implcode == IMPL_XNTPD)
1087 break;
1088 (void) fprintf(stderr,
1089 "***Server implementation incompatable with our own\n");
1090 break;
1091 case INFO_ERR_REQ:
1092 (void) fprintf(stderr,
1093 "***Server doesn't implement this request\n");
1094 break;
1095 case INFO_ERR_FMT:
1096 (void) fprintf(stderr,
1097 "***Server reports a format error in the received packet (shouldn't happen)\n");
1098 break;
1099 case INFO_ERR_NODATA:
1100 (void) fprintf(stderr,
1101 "***Server reports data not found\n");
1102 break;
1103 case INFO_ERR_AUTH:
1104 (void) fprintf(stderr, "***Permission denied\n");
1105 break;
1106 case ERR_TIMEOUT:
1107 (void) fprintf(stderr, "***Request timed out\n");
1108 break;
1109 case ERR_INCOMPLETE:
1110 (void) fprintf(stderr,
1111 "***Response from server was incomplete\n");
1112 break;
1113 default:
1114 (void) fprintf(stderr,
1115 "***Server returns unknown error code %d\n", res);
1116 break;
1119 return res;
1124 * getcmds - read commands from the standard input and execute them
1126 static void
1127 getcmds(void)
1129 #if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDIT)
1130 char *line;
1132 for (;;) {
1133 if ((line = readline(interactive?prompt:"")) == NULL) return;
1134 if (*line) add_history(line);
1135 docmd(line);
1136 free(line);
1138 #else /* not (HAVE_LIBREADLINE || HAVE_LIBEDIT) */
1139 char line[MAXLINE];
1141 for (;;) {
1142 if (interactive) {
1143 #ifdef VMS /* work around a problem with mixing stdout & stderr */
1144 fputs("",stdout);
1145 #endif
1146 (void) fputs(prompt, stderr);
1147 (void) fflush(stderr);
1150 if (fgets(line, sizeof line, stdin) == NULL)
1151 return;
1153 docmd(line);
1155 #endif /* not HAVE_LIBREADLINE || HAVE_LIBEDIT */
1159 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
1161 * abortcmd - catch interrupts and abort the current command
1163 static RETSIGTYPE
1164 abortcmd(
1165 int sig
1169 if (current_output == stdout)
1170 (void) fflush(stdout);
1171 putc('\n', stderr);
1172 (void) fflush(stderr);
1173 if (jump) longjmp(interrupt_buf, 1);
1175 #endif /* SYS_WINNT */
1178 * docmd - decode the command line and execute a command
1180 static void
1181 docmd(
1182 const char *cmdline
1185 char *tokens[1+MAXARGS+MOREARGS+2];
1186 struct parse pcmd;
1187 int ntok;
1188 int i, ti;
1189 int rval;
1190 struct xcmd *xcmd = NULL; /* XXX: GCC */
1192 ai_fam_templ = ai_fam_default;
1194 * Tokenize the command line. If nothing on it, return.
1196 tokenize(cmdline, tokens, &ntok);
1197 if (ntok == 0)
1198 return;
1201 * Find the appropriate command description.
1203 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1204 if (i == 0) {
1205 (void) fprintf(stderr, "***Command `%s' unknown\n",
1206 tokens[0]);
1207 return;
1208 } else if (i >= 2) {
1209 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1210 tokens[0]);
1211 return;
1215 * Save the keyword, then walk through the arguments, interpreting
1216 * as we go.
1218 pcmd.keyword = tokens[0];
1219 pcmd.nargs = 0;
1220 ti = 1;
1221 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) {
1222 if ((i+ti) >= ntok) {
1223 if (!(xcmd->arg[i] & OPT)) {
1224 printusage(xcmd, stderr);
1225 return;
1227 break;
1229 if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>'))
1230 break;
1231 rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]);
1232 if (rval == -1) {
1233 ti++;
1234 continue;
1236 if (rval == 0)
1237 return;
1238 pcmd.nargs++;
1239 i++;
1242 /* Any extra args are assumed to be "OPT|NTP_STR". */
1243 for ( ; i < MAXARGS + MOREARGS;) {
1244 if ((i+ti) >= ntok)
1245 break;
1246 rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]);
1247 if (rval == -1) {
1248 ti++;
1249 continue;
1251 if (rval == 0)
1252 return;
1253 pcmd.nargs++;
1254 i++;
1257 i += ti;
1258 if (i < ntok && *tokens[i] == '>') {
1259 char *fname;
1261 if (*(tokens[i]+1) != '\0')
1262 fname = tokens[i]+1;
1263 else if ((i+1) < ntok)
1264 fname = tokens[i+1];
1265 else {
1266 (void) fprintf(stderr, "***No file for redirect\n");
1267 return;
1270 current_output = fopen(fname, "w");
1271 if (current_output == NULL) {
1272 (void) fprintf(stderr, "***Error opening %s: ", fname);
1273 perror("");
1274 return;
1276 } else {
1277 current_output = stdout;
1280 if (interactive && setjmp(interrupt_buf)) {
1281 return;
1282 } else {
1283 jump = 1;
1284 (xcmd->handler)(&pcmd, current_output);
1285 jump = 0;
1286 if (current_output != stdout)
1287 (void) fclose(current_output);
1288 current_output = NULL;
1294 * tokenize - turn a command line into tokens
1296 static void
1297 tokenize(
1298 const char *line,
1299 char **tokens,
1300 int *ntok
1303 register const char *cp;
1304 register char *sp;
1305 static char tspace[MAXLINE];
1307 sp = tspace;
1308 cp = line;
1309 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1310 tokens[*ntok] = sp;
1311 while (ISSPACE(*cp))
1312 cp++;
1313 if (ISEOL(*cp))
1314 break;
1315 do {
1316 *sp++ = *cp++;
1317 } while (!ISSPACE(*cp) && !ISEOL(*cp));
1319 *sp++ = '\0';
1326 * findcmd - find a command in a command description table
1328 static int
1329 findcmd(
1330 register char *str,
1331 struct xcmd *clist1,
1332 struct xcmd *clist2,
1333 struct xcmd **cmd
1336 register struct xcmd *cl;
1337 register int clen;
1338 int nmatch;
1339 struct xcmd *nearmatch = NULL;
1340 struct xcmd *clist;
1342 clen = strlen(str);
1343 nmatch = 0;
1344 if (clist1 != 0)
1345 clist = clist1;
1346 else if (clist2 != 0)
1347 clist = clist2;
1348 else
1349 return 0;
1351 again:
1352 for (cl = clist; cl->keyword != 0; cl++) {
1353 /* do a first character check, for efficiency */
1354 if (*str != *(cl->keyword))
1355 continue;
1356 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1358 * Could be extact match, could be approximate.
1359 * Is exact if the length of the keyword is the
1360 * same as the str.
1362 if (*((cl->keyword) + clen) == '\0') {
1363 *cmd = cl;
1364 return 1;
1366 nmatch++;
1367 nearmatch = cl;
1372 * See if there is more to do. If so, go again. Sorry about the
1373 * goto, too much looking at BSD sources...
1375 if (clist == clist1 && clist2 != 0) {
1376 clist = clist2;
1377 goto again;
1381 * If we got extactly 1 near match, use it, else return number
1382 * of matches.
1384 if (nmatch == 1) {
1385 *cmd = nearmatch;
1386 return 1;
1388 return nmatch;
1393 * getarg - interpret an argument token
1395 * string is always set.
1396 * type is set to the decoded type.
1398 * return: 0 - failure
1399 * 1 - success
1400 * -1 - skip to next token
1402 static int
1403 getarg(
1404 char *str,
1405 int code,
1406 arg_v *argp
1409 int isneg;
1410 char *cp, *np;
1411 static const char *digits = "0123456789";
1413 memset(argp, 0, sizeof(*argp));
1415 argp->string = str;
1416 argp->type = code & ~OPT;
1418 switch (argp->type) {
1419 case NTP_STR:
1420 break;
1421 case NTP_ADD:
1422 if (!strcmp("-6", str)) {
1423 ai_fam_templ = AF_INET6;
1424 return -1;
1425 } else if (!strcmp("-4", str)) {
1426 ai_fam_templ = AF_INET;
1427 return -1;
1429 if (!getnetnum(str, &(argp->netnum), (char *)0, 0)) {
1430 return 0;
1432 break;
1433 case NTP_INT:
1434 case NTP_UINT:
1435 isneg = 0;
1436 np = str;
1437 if (*np == '-') {
1438 np++;
1439 isneg = 1;
1442 argp->uval = 0;
1443 do {
1444 cp = strchr(digits, *np);
1445 if (cp == NULL) {
1446 (void) fprintf(stderr,
1447 "***Illegal integer value %s\n", str);
1448 return 0;
1450 argp->uval *= 10;
1451 argp->uval += (cp - digits);
1452 } while (*(++np) != '\0');
1454 if (isneg) {
1455 if ((code & ~OPT) == NTP_UINT) {
1456 (void) fprintf(stderr,
1457 "***Value %s should be unsigned\n", str);
1458 return 0;
1460 argp->ival = -argp->ival;
1462 break;
1463 case IP_VERSION:
1464 if (!strcmp("-6", str))
1465 argp->ival = 6 ;
1466 else if (!strcmp("-4", str))
1467 argp->ival = 4 ;
1468 else {
1469 (void) fprintf(stderr,
1470 "***Version must be either 4 or 6\n");
1471 return 0;
1473 break;
1476 return 1;
1481 * getnetnum - given a host name, return its net number
1482 * and (optional) full name
1484 static int
1485 getnetnum(
1486 const char *hname,
1487 struct sockaddr_storage *num,
1488 char *fullhost,
1489 int af
1492 int sockaddr_len;
1493 struct addrinfo hints, *ai = NULL;
1495 sockaddr_len = (af == AF_INET)
1496 ? sizeof(struct sockaddr_in)
1497 : sizeof(struct sockaddr_in6);
1498 memset((char *)&hints, 0, sizeof(struct addrinfo));
1499 hints.ai_flags = AI_CANONNAME;
1500 #ifdef AI_ADDRCONFIG
1501 hints.ai_flags |= AI_ADDRCONFIG;
1502 #endif
1504 /* decodenetnum only works with addresses */
1505 if (decodenetnum(hname, num)) {
1506 if (fullhost != 0) {
1507 getnameinfo((struct sockaddr *)num, sockaddr_len,
1508 fullhost, sizeof(fullhost), NULL, 0,
1509 NI_NUMERICHOST);
1511 return 1;
1512 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1513 memmove((char *)num, ai->ai_addr, ai->ai_addrlen);
1514 if (fullhost != 0)
1515 (void) strcpy(fullhost, ai->ai_canonname);
1516 return 1;
1517 } else {
1518 (void) fprintf(stderr, "***Can't find host %s\n", hname);
1519 return 0;
1521 /*NOTREACHED*/
1525 * nntohost - convert network number to host name. This routine enforces
1526 * the showhostnames setting.
1528 char *
1529 nntohost(
1530 struct sockaddr_storage *netnum
1533 if (!showhostnames)
1534 return stoa(netnum);
1536 if ((netnum->ss_family == AF_INET) && ISREFCLOCKADR(netnum))
1537 return refnumtoa(netnum);
1538 return socktohost(netnum);
1543 * Finally, the built in command handlers
1547 * help - tell about commands, or details of a particular command
1549 static void
1550 help(
1551 struct parse *pcmd,
1552 FILE *fp
1555 struct xcmd *xcp;
1556 char *cmd;
1557 const char *list[100];
1558 int word, words;
1559 int row, rows;
1560 int col, cols;
1562 if (pcmd->nargs == 0) {
1563 words = 0;
1564 for (xcp = builtins; xcp->keyword != 0; xcp++) {
1565 if (*(xcp->keyword) != '?')
1566 list[words++] = xcp->keyword;
1568 for (xcp = opcmds; xcp->keyword != 0; xcp++)
1569 list[words++] = xcp->keyword;
1571 qsort(
1572 #ifdef QSORT_USES_VOID_P
1573 (void *)
1574 #else
1575 (char *)
1576 #endif
1577 (list), (size_t)(words), sizeof(char *), helpsort);
1578 col = 0;
1579 for (word = 0; word < words; word++) {
1580 int length = strlen(list[word]);
1581 if (col < length) {
1582 col = length;
1586 cols = SCREENWIDTH / ++col;
1587 rows = (words + cols - 1) / cols;
1589 (void) fprintf(fp, "ntpdc commands:\n");
1591 for (row = 0; row < rows; row++) {
1592 for (word = row; word < words; word += rows) {
1593 (void) fprintf(fp, "%-*.*s", col, col-1, list[word]);
1595 (void) fprintf(fp, "\n");
1597 } else {
1598 cmd = pcmd->argval[0].string;
1599 words = findcmd(cmd, builtins, opcmds, &xcp);
1600 if (words == 0) {
1601 (void) fprintf(stderr,
1602 "Command `%s' is unknown\n", cmd);
1603 return;
1604 } else if (words >= 2) {
1605 (void) fprintf(stderr,
1606 "Command `%s' is ambiguous\n", cmd);
1607 return;
1609 (void) fprintf(fp, "function: %s\n", xcp->comment);
1610 printusage(xcp, fp);
1616 * helpsort - do hostname qsort comparisons
1618 #ifdef QSORT_USES_VOID_P
1619 static int
1620 helpsort(
1621 const void *t1,
1622 const void *t2
1625 char const * const * name1 = (char const * const *)t1;
1626 char const * const * name2 = (char const * const *)t2;
1628 return strcmp(*name1, *name2);
1630 #else
1631 static int
1632 helpsort(
1633 char **name1,
1634 char **name2
1637 return strcmp(*name1, *name2);
1639 #endif
1643 * printusage - print usage information for a command
1645 static void
1646 printusage(
1647 struct xcmd *xcp,
1648 FILE *fp
1651 int i, opt46;
1653 opt46 = 0;
1654 (void) fprintf(fp, "usage: %s", xcp->keyword);
1655 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
1656 if (opt46 == 0 && (xcp->arg[i] & ~OPT) == NTP_ADD) {
1657 (void) fprintf(fp, " [ -4|-6 ]");
1658 opt46 = 1;
1660 if (xcp->arg[i] & OPT)
1661 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
1662 else
1663 (void) fprintf(fp, " %s", xcp->desc[i]);
1665 (void) fprintf(fp, "\n");
1670 * timeout - set time out time
1672 static void
1673 timeout(
1674 struct parse *pcmd,
1675 FILE *fp
1678 int val;
1680 if (pcmd->nargs == 0) {
1681 val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
1682 (void) fprintf(fp, "primary timeout %d ms\n", val);
1683 } else {
1684 tvout.tv_sec = pcmd->argval[0].uval / 1000;
1685 tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000))
1686 * 1000;
1692 * my_delay - set delay for auth requests
1694 static void
1695 my_delay(
1696 struct parse *pcmd,
1697 FILE *fp
1700 int isneg;
1701 u_long val;
1703 if (pcmd->nargs == 0) {
1704 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
1705 (void) fprintf(fp, "delay %lu ms\n", val);
1706 } else {
1707 if (pcmd->argval[0].ival < 0) {
1708 isneg = 1;
1709 val = (u_long)(-pcmd->argval[0].ival);
1710 } else {
1711 isneg = 0;
1712 val = (u_long)pcmd->argval[0].ival;
1715 delay_time.l_ui = val / 1000;
1716 val %= 1000;
1717 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
1719 if (isneg)
1720 L_NEG(&delay_time);
1726 * host - set the host we are dealing with.
1728 static void
1729 host(
1730 struct parse *pcmd,
1731 FILE *fp
1734 int i;
1736 if (pcmd->nargs == 0) {
1737 if (havehost)
1738 (void) fprintf(fp, "current host is %s\n", currenthost);
1739 else
1740 (void) fprintf(fp, "no current host\n");
1741 return;
1744 i = 0;
1745 if (pcmd->nargs == 2) {
1746 if (!strcmp("-4", pcmd->argval[i].string))
1747 ai_fam_templ = AF_INET;
1748 else if (!strcmp("-6", pcmd->argval[i].string))
1749 ai_fam_templ = AF_INET6;
1750 else {
1751 if (havehost)
1752 (void) fprintf(fp,
1753 "current host remains %s\n", currenthost);
1754 else
1755 (void) fprintf(fp, "still no current host\n");
1756 return;
1758 i = 1;
1760 if (openhost(pcmd->argval[i].string)) {
1761 (void) fprintf(fp, "current host set to %s\n", currenthost);
1762 } else {
1763 if (havehost)
1764 (void) fprintf(fp,
1765 "current host remains %s\n", currenthost);
1766 else
1767 (void) fprintf(fp, "still no current host\n");
1773 * keyid - get a keyid to use for authenticating requests
1775 static void
1776 keyid(
1777 struct parse *pcmd,
1778 FILE *fp
1781 if (pcmd->nargs == 0) {
1782 if (info_auth_keyid == 0 && !keyid_entered)
1783 (void) fprintf(fp, "no keyid defined\n");
1784 else if (info_auth_keyid == 0 && keyid_entered)
1785 (void) fprintf(fp, "no keyid will be sent\n");
1786 else
1787 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
1788 } else {
1789 info_auth_keyid = pcmd->argval[0].uval;
1790 keyid_entered = 1;
1796 * keytype - get type of key to use for authenticating requests
1798 static void
1799 keytype(
1800 struct parse *pcmd,
1801 FILE *fp
1804 if (pcmd->nargs == 0)
1805 fprintf(fp, "keytype is %s\n",
1806 (info_auth_keytype == KEY_TYPE_MD5) ? "MD5" : "???");
1807 else
1808 switch (*(pcmd->argval[0].string)) {
1809 case 'm':
1810 case 'M':
1811 info_auth_keytype = KEY_TYPE_MD5;
1812 break;
1814 default:
1815 fprintf(fp, "keytype must be 'md5'\n");
1822 * passwd - get an authentication key
1824 /*ARGSUSED*/
1825 static void
1826 passwd(
1827 struct parse *pcmd,
1828 FILE *fp
1831 char *pass;
1833 if (info_auth_keyid == 0) {
1834 info_auth_keyid = getkeyid("Keyid: ");
1835 if (info_auth_keyid == 0) {
1836 (void)fprintf(fp, "Keyid must be defined\n");
1837 return;
1840 if (!interactive) {
1841 authusekey(info_auth_keyid, info_auth_keytype,
1842 (u_char *)pcmd->argval[0].string);
1843 authtrust(info_auth_keyid, 1);
1844 } else {
1845 pass = getpass("MD5 Password: ");
1846 if (*pass == '\0')
1847 (void) fprintf(fp, "Password unchanged\n");
1848 else {
1849 authusekey(info_auth_keyid, info_auth_keytype,
1850 (u_char *)pass);
1851 authtrust(info_auth_keyid, 1);
1858 * hostnames - set the showhostnames flag
1860 static void
1861 hostnames(
1862 struct parse *pcmd,
1863 FILE *fp
1866 if (pcmd->nargs == 0) {
1867 if (showhostnames)
1868 (void) fprintf(fp, "hostnames being shown\n");
1869 else
1870 (void) fprintf(fp, "hostnames not being shown\n");
1871 } else {
1872 if (STREQ(pcmd->argval[0].string, "yes"))
1873 showhostnames = 1;
1874 else if (STREQ(pcmd->argval[0].string, "no"))
1875 showhostnames = 0;
1876 else
1877 (void)fprintf(stderr, "What?\n");
1883 * setdebug - set/change debugging level
1885 static void
1886 setdebug(
1887 struct parse *pcmd,
1888 FILE *fp
1891 if (pcmd->nargs == 0) {
1892 (void) fprintf(fp, "debug level is %d\n", debug);
1893 return;
1894 } else if (STREQ(pcmd->argval[0].string, "no")) {
1895 debug = 0;
1896 } else if (STREQ(pcmd->argval[0].string, "more")) {
1897 debug++;
1898 } else if (STREQ(pcmd->argval[0].string, "less")) {
1899 debug--;
1900 } else {
1901 (void) fprintf(fp, "What?\n");
1902 return;
1904 (void) fprintf(fp, "debug level set to %d\n", debug);
1909 * quit - stop this nonsense
1911 /*ARGSUSED*/
1912 static void
1913 quit(
1914 struct parse *pcmd,
1915 FILE *fp
1918 if (havehost)
1919 closesocket(sockfd);
1920 exit(0);
1925 * version - print the current version number
1927 /*ARGSUSED*/
1928 static void
1929 version(
1930 struct parse *pcmd,
1931 FILE *fp
1935 (void) fprintf(fp, "%s\n", Version);
1936 return;
1941 * warning - print a warning message
1943 static void
1944 warning(
1945 const char *fmt,
1946 const char *st1,
1947 const char *st2
1950 (void) fprintf(stderr, "%s: ", progname);
1951 (void) fprintf(stderr, fmt, st1, st2);
1952 (void) fprintf(stderr, ": ");
1953 perror("");
1958 * error - print a message and exit
1960 static void
1961 error(
1962 const char *fmt,
1963 const char *st1,
1964 const char *st2
1967 warning(fmt, st1, st2);
1968 exit(1);
1972 * getkeyid - prompt the user for a keyid to use
1974 static u_long
1975 getkeyid(
1976 const char *keyprompt
1979 register char *p;
1980 register int c;
1981 FILE *fi;
1982 char pbuf[20];
1984 #ifndef SYS_WINNT
1985 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
1986 #else
1987 if ((fi = _fdopen((int)GetStdHandle(STD_INPUT_HANDLE), "r")) == NULL)
1988 #endif /* SYS_WINNT */
1989 fi = stdin;
1990 else
1991 setbuf(fi, (char *)NULL);
1992 fprintf(stderr, "%s", keyprompt); fflush(stderr);
1993 for (p=pbuf; (c = getc(fi))!='\n' && c!=EOF;) {
1994 if (p < &pbuf[18])
1995 *p++ = (char) c;
1997 *p = '\0';
1998 if (fi != stdin)
1999 fclose(fi);
2000 return (u_int32)atoi(pbuf);