2 * ntpdc - control and monitor your ntpd daemon
8 #include "ntp_select.h"
10 #include "ntp_stdlib.h"
20 # define closesocket close
21 #endif /* SYS_WINNT */
23 #ifdef HAVE_LIBREADLINE
24 # include <readline/readline.h>
25 # include <readline/history.h>
26 #endif /* HAVE_LIBREADLINE */
29 /* vxWorks needs mode flag -casey*/
30 #define open(name, flags) open(name, flags, 0777)
31 #define SERVER_PORT_NUM 123
35 * Because we now potentially understand a lot of commands (and
36 * it requires a lot of commands to talk to ntpd) we will run
37 * interactive if connected to a terminal.
39 static int interactive = 0; /* set to 1 when we should prompt */
40 static const char * prompt = "ntpdc> "; /* prompt to ask him about */
43 * Keyid used for authenticated requests. Obtained on the fly.
45 static u_long info_auth_keyid;
48 * Type of key md5 or des
50 #define KEY_TYPE_DES 3
51 #define KEY_TYPE_MD5 4
53 static int info_auth_keytype = KEY_TYPE_MD5; /* MD5*/
54 u_long current_time; /* needed by authkeys; not used */
56 int ntpdcmain P((int, char **));
58 * Built in command handler declarations
60 static int openhost P((const char *));
61 static int sendpkt P((char *, int));
62 static void growpktdata P((void));
63 static int getresponse P((int, int, int *, int *, char **));
64 static int sendrequest P((int, int, int, int, int, char *));
65 static void getcmds P((void));
66 static RETSIGTYPE abortcmd P((int));
67 static void docmd P((const char *));
68 static void tokenize P((const char *, char **, int *));
69 static int findcmd P((char *, struct xcmd *, struct xcmd *, struct xcmd **));
70 static int getarg P((char *, int, arg_v *));
71 static int getnetnum P((const char *, u_int32 *, char *));
72 static void help P((struct parse *, FILE *));
73 #ifdef QSORT_USES_VOID_P
74 static int helpsort P((const void *, const void *));
76 static int helpsort P((char **, char **));
78 static void printusage P((struct xcmd *, FILE *));
79 static void timeout P((struct parse *, FILE *));
80 static void my_delay P((struct parse *, FILE *));
81 static void host P((struct parse *, FILE *));
82 static void keyid P((struct parse *, FILE *));
83 static void keytype P((struct parse *, FILE *));
84 static void passwd P((struct parse *, FILE *));
85 static void hostnames P((struct parse *, FILE *));
86 static void setdebug P((struct parse *, FILE *));
87 static void quit P((struct parse *, FILE *));
88 static void version P((struct parse *, FILE *));
89 static void warning P((const char *, const char *, const char *));
90 static void error P((const char *, const char *, const char *));
91 static u_long getkeyid P((const char *));
96 * Built-in commands we understand
98 static struct xcmd builtins[] = {
99 { "?", help, { OPT|NTP_STR, NO, NO, NO },
100 { "command", "", "", "" },
101 "tell the use and syntax of commands" },
102 { "help", help, { OPT|NTP_STR, NO, NO, NO },
103 { "command", "", "", "" },
104 "tell the use and syntax of commands" },
105 { "timeout", timeout, { OPT|UINT, NO, NO, NO },
106 { "msec", "", "", "" },
107 "set the primary receive time out" },
108 { "delay", my_delay, { OPT|INT, NO, NO, NO },
109 { "msec", "", "", "" },
110 "set the delay added to encryption time stamps" },
111 { "host", host, { OPT|NTP_STR, NO, NO, NO },
112 { "hostname", "", "", "" },
113 "specify the host whose NTP server we talk to" },
114 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
116 "specify a password to use for authenticated requests"},
117 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
118 { "yes|no", "", "", "" },
119 "specify whether hostnames or net numbers are printed"},
120 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
121 { "no|more|less", "", "", "" },
122 "set/change debugging level" },
123 { "quit", quit, { NO, NO, NO, NO },
126 { "exit", quit, { NO, NO, NO, NO },
129 { "keyid", keyid, { OPT|UINT, NO, NO, NO },
130 { "key#", "", "", "" },
131 "set/show keyid to use for authenticated requests" },
132 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
133 { "(md5|des)", "", "", "" },
134 "set/show key authentication type for authenticated requests (des|md5)" },
135 { "version", version, { NO, NO, NO, NO },
137 "print version number" },
138 { 0, 0, { NO, NO, NO, NO },
139 { "", "", "", "" }, "" }
144 * Default values we use.
146 #define DEFTIMEOUT (5) /* 5 second time out */
147 #define DEFSTIMEOUT (2) /* 2 second time out after first */
148 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
149 #define DEFHOST "localhost" /* default host name */
150 #define LENHOSTNAME 256 /* host name is 256 characters long */
151 #define MAXCMDS 100 /* maximum commands on cmd line */
152 #define MAXHOSTS 200 /* maximum hosts on cmd line */
153 #define MAXLINE 512 /* maximum line length */
154 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
157 * Some variables used and manipulated locally
159 static struct timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
160 static struct timeval tvsout = { DEFSTIMEOUT, 0 }; /* secondary time out */
161 static l_fp delay_time; /* delay time */
162 static char currenthost[LENHOSTNAME]; /* current host name */
163 static struct sockaddr_in hostaddr = { 0 }; /* host address */
164 static int showhostnames = 1; /* show host names by default */
166 static int sockfd; /* fd socket is openned on */
167 static int havehost = 0; /* set to 1 when host open */
168 struct servent *server_entry = NULL; /* server entry for ntp */
170 #if defined (SYS_WINNT) || defined (SYS_VXWORKS)
172 #endif /* SYS_WINNT || SYS_VXWORKS */
175 WORD wVersionRequested;
177 DWORD NumberOfBytesWritten;
179 HANDLE TimerThreadHandle = NULL; /* 1998/06/03 - Used in ntplib/machines.c */
180 void timer(void) { ; }; /* 1998/06/03 - Used in ntplib/machines.c */
182 #endif /* SYS_WINNT */
185 * Holds data returned from queries. We allocate INITDATASIZE
186 * octets to begin with, increasing this as we need to.
188 #define INITDATASIZE (sizeof(struct resp_pkt) * 16)
189 #define INCDATASIZE (sizeof(struct resp_pkt) * 8)
191 static char *pktdata;
192 static int pktdatasize;
195 * For commands typed on the command line (with the -c option)
197 static int numcmds = 0;
198 static const char *ccmds[MAXCMDS];
199 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
202 * When multiple hosts are specified.
204 static int numhosts = 0;
205 static const char *chosts[MAXHOSTS];
206 #define ADDHOST(cp) if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp)
209 * Error codes for internal use
211 #define ERR_INCOMPLETE 16
212 #define ERR_TIMEOUT 17
215 * Macro definitions we use
217 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
218 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
219 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
222 * For converting time stamps to dates
224 #define JAN_1970 2208988800 /* 1970 - 1900 in seconds */
227 * Jump buffer for longjumping back to the command level
229 static jmp_buf interrupt_buf;
230 static volatile int jump = 0;
233 * Pointer to current output unit
235 static FILE *current_output;
238 * Command table imported from ntpdc_ops.c
240 extern struct xcmd opcmds[];
245 #ifdef NO_MAIN_ALLOWED
246 CALL(ntpdc,"ntpdc",ntpdcmain);
254 return ntpdcmain(argc, argv);
259 void clear_globals(void)
261 extern int ntp_optind;
262 extern char *ntp_optarg;
263 showhostnames = 0; /* show host names by default */
266 server_entry = NULL; /* server entry for ntp */
267 havehost = 0; /* set to 1 when host open */
274 * main - parse arguments and handle options
284 extern int ntp_optind;
285 extern char *ntp_optarg;
288 delay_time.l_uf = DEFDELAY;
292 taskPrioritySet(taskIdSelf(), 100 );
296 while ((c = ntp_getopt(argc, argv, "c:dilnps")) != EOF)
324 (void) fprintf(stderr,
325 "usage: %s [-dilnps] [-c cmd] host ...\n",
329 if (ntp_optind == argc) {
332 for (; ntp_optind < argc; ntp_optind++)
333 ADDHOST(argv[ntp_optind]);
336 if (numcmds == 0 && interactive == 0
337 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
341 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
343 (void) signal_no_reset(SIGINT, abortcmd);
344 #endif /* SYS_WINNT */
347 * Initialize the packet data buffer
349 pktdata = (char *)malloc(INITDATASIZE);
350 if (pktdata == NULL) {
351 (void) fprintf(stderr, "%s: malloc() failed!\n", progname);
354 pktdatasize = INITDATASIZE;
357 wVersionRequested = MAKEWORD(1,1);
358 if (WSAStartup(wVersionRequested, &wsaData)) {
359 fprintf(stderr, "No useable winsock.dll");
362 #endif /* SYS_WINNT */
365 (void) openhost(chosts[0]);
371 for (ihost = 0; ihost < numhosts; ihost++) {
372 if (openhost(chosts[ihost]))
373 for (icmd = 0; icmd < numcmds; icmd++) {
375 printf ("--- %s ---\n",chosts[ihost]);
388 * openhost - open a socket to a host
396 char temphost[LENHOSTNAME];
398 if (server_entry == NULL) {
399 server_entry = getservbyname("ntp", "udp");
400 if (server_entry == NULL) {
401 #ifdef VMS /* UCX getservbyname() doesn't work [yet], but we do know better */
402 server_entry = (struct servent *)
403 malloc(sizeof(struct servent));
404 server_entry->s_port = htons(NTP_PORT);
406 (void) fprintf(stderr, "%s: ntp/udp: unknown service\n",
409 #endif /* VMS & UCX */
412 printf("Got ntp/udp service entry\n");
415 if (!getnetnum(hname, &netnum, temphost))
419 printf("Opening host %s\n", temphost);
423 printf("Closing old host %s\n", currenthost);
424 (void) closesocket(sockfd);
427 (void) strcpy(currenthost, temphost);
429 hostaddr.sin_family = AF_INET;
431 hostaddr.sin_port = server_entry->s_port;
433 hostaddr.sin_port = htons(SERVER_PORT_NUM);
435 hostaddr.sin_addr.s_addr = netnum;
439 int optionValue = SO_SYNCHRONOUS_NONALERT;
441 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue));
442 if (err != NO_ERROR) {
443 (void) fprintf(stderr, "cannot open nonoverlapped sockets\n");
448 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
449 if (sockfd == INVALID_SOCKET) {
450 error("socket", "", "");
454 sockfd = socket(AF_INET, SOCK_DGRAM, 0);
456 error("socket", "", "");
457 #endif /* SYS_WINNT */
460 #ifdef NEED_RCVBUF_SLOP
463 int rbufsize = INITDATASIZE + 2048; /* 2K for slop */
465 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
466 &rbufsize, sizeof(int)) == -1)
467 error("setsockopt", "", "");
472 if (connect(sockfd, (struct sockaddr *)&hostaddr,
473 sizeof(hostaddr)) == -1)
474 error("connect", "", "");
481 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
483 * sendpkt - send a packet to the remote host
491 if (send(sockfd, xdata, (size_t)xdatalen, 0) == -1) {
492 warning("write to %s failed", currenthost, "");
501 * growpktdata - grow the packet data area
506 pktdatasize += INCDATASIZE;
507 pktdata = (char *)realloc(pktdata, (unsigned)pktdatasize);
509 (void) fprintf(stderr, "%s: realloc() failed!\n", progname);
516 * getresponse - get a (series of) response packet(s) and return the data
527 struct resp_pkt rpkt;
533 char haveseq[MAXSEQ+1];
542 * This is pretty tricky. We may get between 1 and many packets
543 * back in response to the request. We peel the data out of
544 * each packet and collect it in one long block. When the last
545 * packet in the sequence is received we'll know how many we
546 * should have had. Note we use one long time out, should reconsider.
552 *rdata = datap = pktdata;
553 lastseq = 999; /* too big to be a sequence number */
554 memset(haveseq, 0, sizeof(haveseq));
563 FD_SET(sockfd, &fds);
564 n = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvo);
567 warning("select fails", "", "");
572 * Timed out. Return what we have
575 (void) fprintf(stderr,
576 "%s: timed out, nothing received\n", currenthost);
579 (void) fprintf(stderr,
580 "%s: timed out with incomplete data\n",
583 printf("Received sequence numbers");
584 for (n = 0; n <= MAXSEQ; n++)
588 printf(" last frame received\n");
590 printf(" last frame not received\n");
592 return ERR_INCOMPLETE;
596 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
598 warning("read", "", "");
604 * Check for format errors. Bug proofing.
606 if (n < RESP_HEADER_SIZE) {
608 printf("Short (%d byte) packet received\n", n);
611 if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION ||
612 INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) {
614 printf("Packet received with version %d\n",
615 INFO_VERSION(rpkt.rm_vn_mode));
618 if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) {
620 printf("Packet received with mode %d\n",
621 INFO_MODE(rpkt.rm_vn_mode));
624 if (INFO_IS_AUTH(rpkt.auth_seq)) {
626 printf("Encrypted packet received\n");
629 if (!ISRESPONSE(rpkt.rm_vn_mode)) {
631 printf("Received request packet, wanted response\n");
634 if (INFO_MBZ(rpkt.mbz_itemsize) != 0) {
636 printf("Received packet with nonzero MBZ field!\n");
641 * Check implementation/request. Could be old data getting to us.
643 if (rpkt.implementation != implcode || rpkt.request != reqcode) {
646 "Received implementation/request of %d/%d, wanted %d/%d",
647 rpkt.implementation, rpkt.request,
653 * Check the error code. If non-zero, return it.
655 if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) {
656 if (debug && ISMORE(rpkt.rm_vn_mode)) {
657 printf("Error code %d received on not-final packet\n",
658 INFO_ERR(rpkt.err_nitems));
660 return (int)INFO_ERR(rpkt.err_nitems);
665 * Collect items and size. Make sure they make sense.
667 items = INFO_NITEMS(rpkt.err_nitems);
668 size = INFO_ITEMSIZE(rpkt.mbz_itemsize);
670 if ((datasize = items*size) > (n-RESP_HEADER_SIZE)) {
673 "Received items %d, size %d (total %d), data in packet is %d\n",
674 items, size, datasize, n-RESP_HEADER_SIZE);
679 * If this isn't our first packet, make sure the size matches
682 if (!firstpkt && size != *rsize) {
684 printf("Received itemsize %d, previous %d\n",
690 * If we've received this before, toss it
692 seq = INFO_SEQ(rpkt.auth_seq);
695 printf("Received duplicate sequence number %d\n", seq);
701 * If this is the last in the sequence, record that.
703 if (!ISMORE(rpkt.rm_vn_mode)) {
704 if (lastseq != 999) {
705 printf("Received second end sequence packet\n");
712 * So far, so good. Copy this data into the output array.
714 if ((datap + datasize) > (pktdata + pktdatasize)) {
715 int offset = datap - pktdata;
717 *rdata = pktdata; /* might have been realloced ! */
718 datap = pktdata + offset;
720 memmove(datap, (char *)rpkt.data, (unsigned)datasize);
729 * Finally, check the count of received packets. If we've got them
733 if (numrecv <= lastseq)
740 * sendrequest - format and send a request packet
755 memset((char *)&qpkt, 0, sizeof qpkt);
757 qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
758 qpkt.implementation = (u_char)implcode;
759 qpkt.request = (u_char)reqcode;
761 datasize = qitems * qsize;
762 if (datasize != 0 && qdata != NULL) {
763 memmove((char *)qpkt.data, qdata, (unsigned)datasize);
764 qpkt.err_nitems = ERR_NITEMS(0, qitems);
765 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);
767 qpkt.err_nitems = ERR_NITEMS(0, 0);
768 qpkt.mbz_itemsize = MBZ_ITEMSIZE(0);
772 qpkt.auth_seq = AUTH_SEQ(0, 0);
773 return sendpkt((char *)&qpkt, REQ_LEN_NOMAC);
777 const char *pass = "\0";
779 if (info_auth_keyid == 0) {
780 maclen = getkeyid("Keyid: ");
782 (void) fprintf(stderr,
783 "Invalid key identifier\n");
786 info_auth_keyid = maclen;
788 if (!authistrusted(info_auth_keyid)) {
789 pass = getpass((info_auth_keytype == KEY_TYPE_DES)
790 ? "DES Password: " : "MD5 Password: ");
792 (void) fprintf(stderr,
793 "Invalid password\n");
797 authusekey(info_auth_keyid, info_auth_keytype, (const u_char *)pass);
798 authtrust(info_auth_keyid, 1);
799 qpkt.auth_seq = AUTH_SEQ(1, 0);
800 qpkt.keyid = htonl(info_auth_keyid);
802 L_ADD(&ts, &delay_time);
803 HTONL_FP(&ts, &qpkt.tstamp);
804 maclen = authencrypt(info_auth_keyid, (u_int32 *)&qpkt,
807 (void) fprintf(stderr, "Key not found\n");
810 return sendpkt((char *)&qpkt, (int)(REQ_LEN_NOMAC + maclen));
817 * doquery - send a request and process the response
836 struct timeval tvzero;
839 * Check to make sure host is open
842 (void) fprintf(stderr, "***No host open, use `host' command\n");
847 * Poll the socket and clear out any pending data
850 tvzero.tv_sec = tvzero.tv_usec = 0;
852 FD_SET(sockfd, &fds);
853 res = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
856 warning("polling select", "", "");
860 (void) recv(sockfd, junk, sizeof junk, 0);
867 res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata);
872 * Get the response. If we got a standard error, print a message
874 res = getresponse(implcode, reqcode, ritems, rsize, rdata);
876 /* log error message if not told to be quiet */
877 if ((res > 0) && (((1 << res) & quiet_mask) == 0)) {
880 (void) fprintf(stderr,
881 "***Server implementation incompatable with our own\n");
884 (void) fprintf(stderr,
885 "***Server doesn't implement this request\n");
888 (void) fprintf(stderr,
889 "***Server reports a format error in the received packet (shouldn't happen)\n");
891 case INFO_ERR_NODATA:
892 (void) fprintf(stderr,
893 "***Server reports data not found\n");
896 (void) fprintf(stderr, "***Permission denied\n");
899 (void) fprintf(stderr, "***Request timed out\n");
902 (void) fprintf(stderr,
903 "***Response from server was incomplete\n");
906 (void) fprintf(stderr,
907 "***Server returns unknown error code %d\n", res);
916 * getcmds - read commands from the standard input and execute them
921 #ifdef HAVE_LIBREADLINE
925 if ((line = readline(interactive?prompt:"")) == NULL) return;
926 if (*line) add_history(line);
930 #else /* not HAVE_LIBREADLINE */
935 #ifdef VMS /* work around a problem with mixing stdout & stderr */
938 (void) fputs(prompt, stderr);
939 (void) fflush(stderr);
942 if (fgets(line, sizeof line, stdin) == NULL)
947 #endif /* not HAVE_LIBREADLINE */
952 * abortcmd - catch interrupts and abort the current command
960 if (current_output == stdout)
961 (void) fflush(stdout);
963 (void) fflush(stderr);
964 if (jump) longjmp(interrupt_buf, 1);
969 * docmd - decode the command line and execute a command
976 char *tokens[1+MAXARGS+2];
983 * Tokenize the command line. If nothing on it, return.
985 tokenize(cmdline, tokens, &ntok);
990 * Find the appropriate command description.
992 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
994 (void) fprintf(stderr, "***Command `%s' unknown\n",
998 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1004 * Save the keyword, then walk through the arguments, interpreting
1007 pcmd.keyword = tokens[0];
1009 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1010 if ((i+1) >= ntok) {
1011 if (!(xcmd->arg[i] & OPT)) {
1012 printusage(xcmd, stderr);
1017 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1019 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1025 if (i < ntok && *tokens[i] == '>') {
1028 if (*(tokens[i]+1) != '\0')
1029 fname = tokens[i]+1;
1030 else if ((i+1) < ntok)
1031 fname = tokens[i+1];
1033 (void) fprintf(stderr, "***No file for redirect\n");
1037 current_output = fopen(fname, "w");
1038 if (current_output == NULL) {
1039 (void) fprintf(stderr, "***Error opening %s: ", fname);
1043 i = 1; /* flag we need a close */
1045 current_output = stdout;
1046 i = 0; /* flag no close */
1049 if (interactive && setjmp(interrupt_buf)) {
1053 (xcmd->handler)(&pcmd, current_output);
1055 if (i) (void) fclose(current_output);
1061 * tokenize - turn a command line into tokens
1070 register const char *cp;
1072 static char tspace[MAXLINE];
1076 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1078 while (ISSPACE(*cp))
1084 } while (!ISSPACE(*cp) && !ISEOL(*cp));
1093 * findcmd - find a command in a command description table
1098 struct xcmd *clist1,
1099 struct xcmd *clist2,
1103 register struct xcmd *cl;
1106 struct xcmd *nearmatch = NULL;
1113 else if (clist2 != 0)
1119 for (cl = clist; cl->keyword != 0; cl++) {
1120 /* do a first character check, for efficiency */
1121 if (*str != *(cl->keyword))
1123 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1125 * Could be extact match, could be approximate.
1126 * Is exact if the length of the keyword is the
1129 if (*((cl->keyword) + clen) == '\0') {
1139 * See if there is more to do. If so, go again. Sorry about the
1140 * goto, too much looking at BSD sources...
1142 if (clist == clist1 && clist2 != 0) {
1148 * If we got extactly 1 near match, use it, else return number
1160 * getarg - interpret an argument token
1171 static const char *digits = "0123456789";
1173 switch (code & ~OPT) {
1178 if (!getnetnum(str, &(argp->netnum), (char *)0)) {
1193 cp = strchr(digits, *np);
1195 (void) fprintf(stderr,
1196 "***Illegal integer value %s\n", str);
1200 argp->uval += (cp - digits);
1201 } while (*(++np) != '\0');
1204 if ((code & ~OPT) == UINT) {
1205 (void) fprintf(stderr,
1206 "***Value %s should be unsigned\n", str);
1209 argp->ival = -argp->ival;
1219 * getnetnum - given a host name, return its net number
1220 * and (optional) full name
1231 if (decodenetnum(hname, num)) {
1232 if (fullhost != 0) {
1233 (void) sprintf(fullhost,
1234 "%u.%u.%u.%u", (u_int)((htonl(*num)>>24)&0xff),
1235 (u_int)((htonl(*num)>>16)&0xff), (u_int)((htonl(*num)>>8)&0xff),
1236 (u_int)(htonl(*num)&0xff));
1239 } else if ((hp = gethostbyname(hname)) != 0) {
1240 memmove((char *)num, hp->h_addr, sizeof(u_int32));
1242 (void) strcpy(fullhost, hp->h_name);
1245 (void) fprintf(stderr, "***Can't find host %s\n", hname);
1252 * nntohost - convert network number to host name. This routine enforces
1253 * the showhostnames setting.
1261 return numtoa(netnum);
1262 if ((ntohl(netnum) & REFCLOCK_MASK) == REFCLOCK_ADDR)
1263 return refnumtoa(netnum);
1264 return numtohost(netnum);
1269 * Finally, the built in command handlers
1273 * help - tell about commands, or details of a particular command
1285 const char *cmdsort[100];
1289 static const char *spaces = " "; /* 20 spaces */
1291 if (pcmd->nargs == 0) {
1293 for (xcp = builtins; xcp->keyword != 0; xcp++) {
1294 if (*(xcp->keyword) != '?')
1295 cmdsort[n++] = xcp->keyword;
1297 for (xcp = opcmds; xcp->keyword != 0; xcp++)
1298 cmdsort[n++] = xcp->keyword;
1300 #ifdef QSORT_USES_VOID_P
1301 qsort(cmdsort, (size_t)n, sizeof(char *), helpsort);
1303 qsort((char *)cmdsort, (size_t)n, sizeof(char *), helpsort);
1307 for (i = 0; i < n; i++) {
1308 length[i] = strlen(cmdsort[i]);
1309 if (length[i] > maxlength)
1310 maxlength = length[i];
1313 numperline = 76 / maxlength;
1315 (void) fprintf(fp, "Commands available:\n");
1316 for (i = 0; i < n; i++) {
1317 if ((i % numperline) == (numperline-1)
1319 (void) fprintf(fp, "%s\n", cmdsort[i]);
1321 (void) fprintf(fp, "%s%s", cmdsort[i],
1322 spaces+20-maxlength+length[i]);
1325 cmd = pcmd->argval[0].string;
1326 n = findcmd(cmd, builtins, opcmds, &xcp);
1328 (void) fprintf(stderr,
1329 "Command `%s' is unknown\n", cmd);
1331 } else if (n >= 2) {
1332 (void) fprintf(stderr,
1333 "Command `%s' is ambiguous\n", cmd);
1336 (void) fprintf(fp, "function: %s\n", xcp->comment);
1337 printusage(xcp, fp);
1343 * helpsort - do hostname qsort comparisons
1345 #ifdef QSORT_USES_VOID_P
1352 const char **name1 = (const char **)t1;
1353 const char **name2 = (const char **)t2;
1355 return strcmp(*name1, *name2);
1364 return strcmp(*name1, *name2);
1370 * printusage - print usage information for a command
1380 (void) fprintf(fp, "usage: %s", xcp->keyword);
1381 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
1382 if (xcp->arg[i] & OPT)
1383 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
1385 (void) fprintf(fp, " %s", xcp->desc[i]);
1387 (void) fprintf(fp, "\n");
1392 * timeout - set time out time
1402 if (pcmd->nargs == 0) {
1403 val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
1404 (void) fprintf(fp, "primary timeout %d ms\n", val);
1406 tvout.tv_sec = pcmd->argval[0].uval / 1000;
1407 tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000))
1414 * my_delay - set delay for auth requests
1425 if (pcmd->nargs == 0) {
1426 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
1427 (void) fprintf(fp, "delay %lu ms\n", val);
1429 if (pcmd->argval[0].ival < 0) {
1431 val = (u_long)(-pcmd->argval[0].ival);
1434 val = (u_long)pcmd->argval[0].ival;
1437 delay_time.l_ui = val / 1000;
1439 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
1448 * host - set the host we are dealing with.
1456 if (pcmd->nargs == 0) {
1458 (void) fprintf(fp, "current host is %s\n", currenthost);
1460 (void) fprintf(fp, "no current host\n");
1461 } else if (openhost(pcmd->argval[0].string)) {
1462 (void) fprintf(fp, "current host set to %s\n", currenthost);
1466 "current host remains %s\n", currenthost);
1468 (void) fprintf(fp, "still no current host\n");
1474 * keyid - get a keyid to use for authenticating requests
1482 if (pcmd->nargs == 0) {
1483 if (info_auth_keyid == 0)
1484 (void) fprintf(fp, "no keyid defined\n");
1486 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
1488 info_auth_keyid = pcmd->argval[0].uval;
1494 * keytype - get type of key to use for authenticating requests
1502 if (pcmd->nargs == 0)
1503 fprintf(fp, "keytype is %s\n",
1504 (info_auth_keytype == KEY_TYPE_MD5) ? "MD5" : "DES");
1506 switch (*(pcmd->argval[0].string)) {
1509 info_auth_keytype = KEY_TYPE_MD5;
1514 info_auth_keytype = KEY_TYPE_DES;
1518 fprintf(fp, "keytype must be 'md5' or 'des'\n");
1525 * passwd - get an authentication key
1536 if (info_auth_keyid == 0) {
1537 info_auth_keyid = getkeyid("Keyid: ");
1538 if (info_auth_keyid == 0) {
1539 (void)fprintf(fp, "Keyid must be defined\n");
1544 authusekey(info_auth_keyid, info_auth_keytype,
1545 (u_char *)pcmd->argval[0].string);
1546 authtrust(info_auth_keyid, 1);
1548 pass = getpass((info_auth_keytype == KEY_TYPE_DES)
1553 (void) fprintf(fp, "Password unchanged\n");
1555 authusekey(info_auth_keyid, info_auth_keytype,
1557 authtrust(info_auth_keyid, 1);
1564 * hostnames - set the showhostnames flag
1572 if (pcmd->nargs == 0) {
1574 (void) fprintf(fp, "hostnames being shown\n");
1576 (void) fprintf(fp, "hostnames not being shown\n");
1578 if (STREQ(pcmd->argval[0].string, "yes"))
1580 else if (STREQ(pcmd->argval[0].string, "no"))
1583 (void)fprintf(stderr, "What?\n");
1589 * setdebug - set/change debugging level
1597 if (pcmd->nargs == 0) {
1598 (void) fprintf(fp, "debug level is %d\n", debug);
1600 } else if (STREQ(pcmd->argval[0].string, "no")) {
1602 } else if (STREQ(pcmd->argval[0].string, "more")) {
1604 } else if (STREQ(pcmd->argval[0].string, "less")) {
1607 (void) fprintf(fp, "What?\n");
1610 (void) fprintf(fp, "debug level set to %d\n", debug);
1615 * quit - stop this nonsense
1625 closesocket(sockfd);
1631 * version - print the current version number
1641 (void) fprintf(fp, "%s\n", Version);
1647 * warning - print a warning message
1656 (void) fprintf(stderr, "%s: ", progname);
1657 (void) fprintf(stderr, fmt, st1, st2);
1658 (void) fprintf(stderr, ": ");
1664 * error - print a message and exit
1673 warning(fmt, st1, st2);
1678 * getkeyid - prompt the user for a keyid to use
1682 const char *keyprompt
1691 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
1693 if ((fi = _fdopen((int)GetStdHandle(STD_INPUT_HANDLE), "r")) == NULL)
1694 #endif /* SYS_WINNT */
1697 setbuf(fi, (char *)NULL);
1698 fprintf(stderr, "%s", keyprompt); fflush(stderr);
1699 for (p=pbuf; (c = getc(fi))!='\n' && c!=EOF;) {
1706 return (u_int32)atoi(pbuf);