2 * ntpdc - control and monitor your ntpd daemon
8 #include "ntp_select.h"
10 #include "ntp_stdlib.h"
11 /* Don't include ISC's version of IPv6 variables and structures */
14 #include "isc/result.h"
24 # define closesocket close
25 #endif /* SYS_WINNT */
27 #if defined(HAVE_LIBREADLINE) || defined (HAVE_LIBEDIT)
28 # include <readline/readline.h>
29 # include <readline/history.h>
30 #endif /* HAVE_LIBREADLINE || HAVE_LIBEDIT */
33 /* vxWorks needs mode flag -casey*/
34 #define open(name, flags) open(name, flags, 0777)
35 #define SERVER_PORT_NUM 123
39 * Because we now potentially understand a lot of commands (and
40 * it requires a lot of commands to talk to ntpd) we will run
41 * interactive if connected to a terminal.
43 static int interactive = 0; /* set to 1 when we should prompt */
44 static const char * prompt = "ntpdc> "; /* prompt to ask him about */
47 * Keyid used for authenticated requests. Obtained on the fly.
49 static u_long info_auth_keyid;
54 #define KEY_TYPE_MD5 4
56 static int info_auth_keytype = KEY_TYPE_MD5; /* MD5 */
57 u_long current_time; /* needed by authkeys; not used */
59 int ntpdcmain P((int, char **));
61 * Built in command handler declarations
63 static int openhost P((const char *));
64 static int sendpkt P((char *, int));
65 static void growpktdata P((void));
66 static int getresponse P((int, int, int *, int *, char **, int));
67 static int sendrequest P((int, int, int, int, int, char *));
68 static void getcmds P((void));
69 static RETSIGTYPE abortcmd P((int));
70 static void docmd P((const char *));
71 static void tokenize P((const char *, char **, int *));
72 static int findcmd P((char *, struct xcmd *, struct xcmd *, struct xcmd **));
73 static int getarg P((char *, int, arg_v *));
74 static int getnetnum P((const char *, struct sockaddr_storage *, char *, int));
75 static void help P((struct parse *, FILE *));
76 #ifdef QSORT_USES_VOID_P
77 static int helpsort P((const void *, const void *));
79 static int helpsort P((char **, char **));
81 static void printusage P((struct xcmd *, FILE *));
82 static void timeout P((struct parse *, FILE *));
83 static void my_delay P((struct parse *, FILE *));
84 static void host P((struct parse *, FILE *));
85 static void keyid P((struct parse *, FILE *));
86 static void keytype P((struct parse *, FILE *));
87 static void passwd P((struct parse *, FILE *));
88 static void hostnames P((struct parse *, FILE *));
89 static void setdebug P((struct parse *, FILE *));
90 static void quit P((struct parse *, FILE *));
91 static void version P((struct parse *, FILE *));
92 static void warning P((const char *, const char *, const char *));
93 static void error P((const char *, const char *, const char *));
94 static u_long getkeyid P((const char *));
99 * Built-in commands we understand
101 static struct xcmd builtins[] = {
102 { "?", help, { OPT|NTP_STR, NO, NO, NO },
103 { "command", "", "", "" },
104 "tell the use and syntax of commands" },
105 { "help", help, { OPT|NTP_STR, NO, NO, NO },
106 { "command", "", "", "" },
107 "tell the use and syntax of commands" },
108 { "timeout", timeout, { OPT|UINT, NO, NO, NO },
109 { "msec", "", "", "" },
110 "set the primary receive time out" },
111 { "delay", my_delay, { OPT|INT, NO, NO, NO },
112 { "msec", "", "", "" },
113 "set the delay added to encryption time stamps" },
114 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
115 { "-4|-6", "hostname", "", "" },
116 "specify the host whose NTP server we talk to" },
117 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
119 "specify a password to use for authenticated requests"},
120 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
121 { "yes|no", "", "", "" },
122 "specify whether hostnames or net numbers are printed"},
123 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
124 { "no|more|less", "", "", "" },
125 "set/change debugging level" },
126 { "quit", quit, { NO, NO, NO, NO },
129 { "exit", quit, { NO, NO, NO, NO },
132 { "keyid", keyid, { OPT|UINT, NO, NO, NO },
133 { "key#", "", "", "" },
134 "set/show keyid to use for authenticated requests" },
135 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
136 { "(md5|des)", "", "", "" },
137 "set/show key authentication type for authenticated requests (des|md5)" },
138 { "version", version, { NO, NO, NO, NO },
140 "print version number" },
141 { 0, 0, { NO, NO, NO, NO },
142 { "", "", "", "" }, "" }
147 * Default values we use.
149 #define DEFTIMEOUT (5) /* 5 second time out */
150 #define DEFSTIMEOUT (2) /* 2 second time out after first */
151 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
152 #define DEFHOST "localhost" /* default host name */
153 #define LENHOSTNAME 256 /* host name is 256 characters long */
154 #define MAXCMDS 100 /* maximum commands on cmd line */
155 #define MAXHOSTS 200 /* maximum hosts on cmd line */
156 #define MAXLINE 512 /* maximum line length */
157 #define MAXTOKENS (1+1+MAXARGS+2) /* maximum number of usable tokens */
158 /* command + -4|-6 + MAXARGS + */
162 * Some variables used and manipulated locally
164 static struct timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
165 static struct timeval tvsout = { DEFSTIMEOUT, 0 }; /* secondary time out */
166 static l_fp delay_time; /* delay time */
167 static char currenthost[LENHOSTNAME]; /* current host name */
168 int showhostnames = 1; /* show host names by default */
170 static int ai_fam_templ; /* address family */
171 static int ai_fam_default; /* default address family */
172 static SOCKET sockfd; /* fd socket is opened on */
173 static int havehost = 0; /* set to 1 when host open */
176 #if defined (SYS_WINNT) || defined (SYS_VXWORKS)
178 #endif /* SYS_WINNT || SYS_VXWORKS */
181 DWORD NumberOfBytesWritten;
183 HANDLE TimerThreadHandle = NULL; /* 1998/06/03 - Used in ntplib/machines.c */
184 void timer(void) { ; }; /* 1998/06/03 - Used in ntplib/machines.c */
186 #endif /* SYS_WINNT */
189 * Holds data returned from queries. We allocate INITDATASIZE
190 * octets to begin with, increasing this as we need to.
192 #define INITDATASIZE (sizeof(struct resp_pkt) * 16)
193 #define INCDATASIZE (sizeof(struct resp_pkt) * 8)
195 static char *pktdata;
196 static int pktdatasize;
199 * These are used to help the magic with old and new versions of ntpd.
201 int impl_ver = IMPL_XNTPD;
202 static int req_pkt_size = REQ_LEN_NOMAC;
205 * For commands typed on the command line (with the -c option)
207 static int numcmds = 0;
208 static const char *ccmds[MAXCMDS];
209 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
212 * When multiple hosts are specified.
214 static int numhosts = 0;
215 static const char *chosts[MAXHOSTS];
216 #define ADDHOST(cp) if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp)
219 * Error codes for internal use
221 #define ERR_INCOMPLETE 16
222 #define ERR_TIMEOUT 17
225 * Macro definitions we use
227 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
228 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
229 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
232 * For converting time stamps to dates
234 #define JAN_1970 2208988800 /* 1970 - 1900 in seconds */
237 * Jump buffer for longjumping back to the command level
239 static jmp_buf interrupt_buf;
240 static volatile int jump = 0;
243 * Pointer to current output unit
245 static FILE *current_output;
248 * Command table imported from ntpdc_ops.c
250 extern struct xcmd opcmds[];
255 #ifdef NO_MAIN_ALLOWED
256 CALL(ntpdc,"ntpdc",ntpdcmain);
264 return ntpdcmain(argc, argv);
269 void clear_globals(void)
271 extern int ntp_optind;
272 extern char *ntp_optarg;
273 showhostnames = 0; /* show host names by default */
276 havehost = 0; /* set to 1 when host open */
283 * main - parse arguments and handle options
293 extern int ntp_optind;
294 extern char *ntp_optarg;
297 delay_time.l_uf = DEFDELAY;
301 taskPrioritySet(taskIdSelf(), 100 );
305 if (!Win32InitSockets())
307 fprintf(stderr, "No useable winsock.dll:");
310 #endif /* SYS_WINNT */
312 /* Check to see if we have IPv6. Otherwise force the -4 flag */
313 if (isc_net_probeipv6() != ISC_R_SUCCESS) {
314 ai_fam_default = AF_INET;
318 ai_fam_templ = ai_fam_default;
319 while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF)
322 ai_fam_templ = AF_INET;
325 ai_fam_templ = AF_INET6;
353 (void) fprintf(stderr,
354 "usage: %s [-46dilnps] [-c cmd] host ...\n",
358 if (ntp_optind == argc) {
361 for (; ntp_optind < argc; ntp_optind++)
362 ADDHOST(argv[ntp_optind]);
365 if (numcmds == 0 && interactive == 0
366 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
370 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
372 (void) signal_no_reset(SIGINT, abortcmd);
373 #endif /* SYS_WINNT */
376 * Initialize the packet data buffer
378 pktdata = (char *)malloc(INITDATASIZE);
379 if (pktdata == NULL) {
380 (void) fprintf(stderr, "%s: malloc() failed!\n", progname);
383 pktdatasize = INITDATASIZE;
386 (void) openhost(chosts[0]);
392 for (ihost = 0; ihost < numhosts; ihost++) {
393 if (openhost(chosts[ihost]))
394 for (icmd = 0; icmd < numcmds; icmd++) {
396 printf ("--- %s ---\n",chosts[ihost]);
409 * openhost - open a socket to a host
416 char temphost[LENHOSTNAME];
418 struct addrinfo hints, *ai = NULL;
419 register const char *cp;
420 char name[LENHOSTNAME];
424 * We need to get by the [] if they were entered
431 for(i = 0; *cp != ']'; cp++, i++)
438 * First try to resolve it as an ip address and if that fails,
439 * do a fullblown (dns) lookup. That way we only use the dns
440 * when it is needed and work around some implementations that
441 * will return an "IPv4-mapped IPv6 address" address if you
442 * give it an IPv4 address to lookup.
444 strcpy(service, "ntp");
445 memset((char *)&hints, 0, sizeof(struct addrinfo));
446 hints.ai_family = ai_fam_templ;
447 hints.ai_protocol = IPPROTO_UDP;
448 hints.ai_socktype = SOCK_DGRAM;
449 hints.ai_flags = AI_NUMERICHOST;
451 a_info = getaddrinfo(hname, service, &hints, &ai);
452 if (a_info == EAI_NONAME || a_info == EAI_NODATA) {
453 hints.ai_flags = AI_CANONNAME;
455 hints.ai_flags |= AI_ADDRCONFIG;
457 a_info = getaddrinfo(hname, service, &hints, &ai);
459 /* Some older implementations don't like AI_ADDRCONFIG. */
460 if (a_info == EAI_BADFLAGS) {
461 hints.ai_flags = AI_CANONNAME;
462 a_info = getaddrinfo(hname, service, &hints, &ai);
465 (void) fprintf(stderr, "%s\n", gai_strerror(a_info));
469 if (ai->ai_canonname == NULL) {
470 strncpy(temphost, stoa((struct sockaddr_storage *)ai->ai_addr),
472 temphost[LENHOSTNAME-1] = '\0';
474 strncpy(temphost, ai->ai_canonname, LENHOSTNAME);
475 temphost[LENHOSTNAME-1] = '\0';
479 printf("Opening host %s\n", temphost);
483 printf("Closing old host %s\n", currenthost);
484 (void) closesocket(sockfd);
487 (void) strcpy(currenthost, temphost);
489 /* port maps to the same in both families */
490 s_port = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port;
492 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
493 if (ai->ai_family == AF_INET)
494 *(struct sockaddr_in *)&hostaddr=
495 *((struct sockaddr_in *)ai->ai_addr);
497 *(struct sockaddr_in6 *)&hostaddr=
498 *((struct sockaddr_in6 *)ai->ai_addr);
499 #endif /* SYS_VXWORKS */
503 int optionValue = SO_SYNCHRONOUS_NONALERT;
505 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue));
506 if (err != NO_ERROR) {
507 (void) fprintf(stderr, "cannot open nonoverlapped sockets\n");
512 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
513 if (sockfd == INVALID_SOCKET) {
514 error("socket", "", "");
518 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
520 error("socket", "", "");
521 #endif /* SYS_WINNT */
524 #ifdef NEED_RCVBUF_SLOP
527 int rbufsize = INITDATASIZE + 2048; /* 2K for slop */
529 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
530 &rbufsize, sizeof(int)) == -1)
531 error("setsockopt", "", "");
537 if (connect(sockfd, (struct sockaddr *)&hostaddr,
538 sizeof(hostaddr)) == -1)
540 if (connect(sockfd, (struct sockaddr *)ai->ai_addr,
541 ai->ai_addrlen) == -1)
542 #endif /* SYS_VXWORKS */
543 error("connect", "", "");
547 req_pkt_size = REQ_LEN_NOMAC;
548 impl_ver = IMPL_XNTPD;
553 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
555 * sendpkt - send a packet to the remote host
563 if (send(sockfd, xdata, (size_t)xdatalen, 0) == -1) {
564 warning("write to %s failed", currenthost, "");
573 * growpktdata - grow the packet data area
578 pktdatasize += INCDATASIZE;
579 pktdata = (char *)realloc(pktdata, (unsigned)pktdatasize);
581 (void) fprintf(stderr, "%s: realloc() failed!\n", progname);
588 * getresponse - get a (series of) response packet(s) and return the data
600 struct resp_pkt rpkt;
608 char haveseq[MAXSEQ+1];
618 * This is pretty tricky. We may get between 1 and many packets
619 * back in response to the request. We peel the data out of
620 * each packet and collect it in one long block. When the last
621 * packet in the sequence is received we'll know how many we
622 * should have had. Note we use one long time out, should reconsider.
628 *rdata = datap = pktdata;
629 lastseq = 999; /* too big to be a sequence number */
630 memset(haveseq, 0, sizeof(haveseq));
639 FD_SET(sockfd, &fds);
640 n = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvo);
643 warning("select fails", "", "");
648 * Timed out. Return what we have
651 (void) fprintf(stderr,
652 "%s: timed out, nothing received\n", currenthost);
655 (void) fprintf(stderr,
656 "%s: timed out with incomplete data\n",
659 printf("Received sequence numbers");
660 for (n = 0; n <= MAXSEQ; n++)
664 printf(" last frame received\n");
666 printf(" last frame not received\n");
668 return ERR_INCOMPLETE;
672 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
674 warning("read", "", "");
680 * Check for format errors. Bug proofing.
682 if (n < RESP_HEADER_SIZE) {
684 printf("Short (%d byte) packet received\n", n);
687 if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION ||
688 INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) {
690 printf("Packet received with version %d\n",
691 INFO_VERSION(rpkt.rm_vn_mode));
694 if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) {
696 printf("Packet received with mode %d\n",
697 INFO_MODE(rpkt.rm_vn_mode));
700 if (INFO_IS_AUTH(rpkt.auth_seq)) {
702 printf("Encrypted packet received\n");
705 if (!ISRESPONSE(rpkt.rm_vn_mode)) {
707 printf("Received request packet, wanted response\n");
710 if (INFO_MBZ(rpkt.mbz_itemsize) != 0) {
712 printf("Received packet with nonzero MBZ field!\n");
717 * Check implementation/request. Could be old data getting to us.
719 if (rpkt.implementation != implcode || rpkt.request != reqcode) {
722 "Received implementation/request of %d/%d, wanted %d/%d",
723 rpkt.implementation, rpkt.request,
729 * Check the error code. If non-zero, return it.
731 if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) {
732 if (debug && ISMORE(rpkt.rm_vn_mode)) {
733 printf("Error code %d received on not-final packet\n",
734 INFO_ERR(rpkt.err_nitems));
736 return (int)INFO_ERR(rpkt.err_nitems);
740 * Collect items and size. Make sure they make sense.
742 items = INFO_NITEMS(rpkt.err_nitems);
743 size = INFO_ITEMSIZE(rpkt.mbz_itemsize);
748 if ((datasize = items*size) > (n-RESP_HEADER_SIZE)) {
751 "Received items %d, size %d (total %d), data in packet is %d\n",
752 items, size, datasize, n-RESP_HEADER_SIZE);
757 * If this isn't our first packet, make sure the size matches
760 if (!firstpkt && esize != *rsize) {
762 printf("Received itemsize %d, previous %d\n",
767 * If we've received this before, +toss it
769 seq = INFO_SEQ(rpkt.auth_seq);
772 printf("Received duplicate sequence number %d\n", seq);
778 * If this is the last in the sequence, record that.
780 if (!ISMORE(rpkt.rm_vn_mode)) {
781 if (lastseq != 999) {
782 printf("Received second end sequence packet\n");
789 * So far, so good. Copy this data into the output array.
791 if ((datap + datasize + (pad * items)) > (pktdata + pktdatasize)) {
792 int offset = datap - pktdata;
794 *rdata = pktdata; /* might have been realloced ! */
795 datap = pktdata + offset;
798 * We now move the pointer along according to size and number of
799 * items. This is so we can play nice with older implementations
802 tmp_data = (char *)rpkt.data;
803 for(i = 0; i <items; i++){
804 memmove(datap, tmp_data, (unsigned)size);
806 memset(datap + size, 0, pad);
817 * Finally, check the count of received packets. If we've got them
821 if (numrecv <= lastseq)
828 * sendrequest - format and send a request packet
843 memset((char *)&qpkt, 0, sizeof qpkt);
845 qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
846 qpkt.implementation = (u_char)implcode;
847 qpkt.request = (u_char)reqcode;
849 datasize = qitems * qsize;
850 if (datasize != 0 && qdata != NULL) {
851 memmove((char *)qpkt.data, qdata, (unsigned)datasize);
852 qpkt.err_nitems = ERR_NITEMS(0, qitems);
853 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);
855 qpkt.err_nitems = ERR_NITEMS(0, 0);
856 qpkt.mbz_itemsize = MBZ_ITEMSIZE(0);
860 qpkt.auth_seq = AUTH_SEQ(0, 0);
861 return sendpkt((char *)&qpkt, req_pkt_size);
865 const char *pass = "\0";
866 struct req_pkt_tail *qpktail;
868 qpktail = (struct req_pkt_tail *)((char *)&qpkt + req_pkt_size
869 + MAX_MAC_LEN - sizeof(struct req_pkt_tail));
871 if (info_auth_keyid == 0) {
872 maclen = getkeyid("Keyid: ");
874 (void) fprintf(stderr,
875 "Invalid key identifier\n");
878 info_auth_keyid = maclen;
880 if (!authistrusted(info_auth_keyid)) {
881 pass = getpass("MD5 Password: ");
883 (void) fprintf(stderr,
884 "Invalid password\n");
888 authusekey(info_auth_keyid, info_auth_keytype, (const u_char *)pass);
889 authtrust(info_auth_keyid, 1);
890 qpkt.auth_seq = AUTH_SEQ(1, 0);
891 qpktail->keyid = htonl(info_auth_keyid);
893 L_ADD(&ts, &delay_time);
894 HTONL_FP(&ts, &qpktail->tstamp);
895 maclen = authencrypt(info_auth_keyid, (u_int32 *)&qpkt,
898 (void) fprintf(stderr, "Key not found\n");
901 return sendpkt((char *)&qpkt, (int)(req_pkt_size + maclen));
908 * doquery - send a request and process the response
928 struct timeval tvzero;
931 * Check to make sure host is open
934 (void) fprintf(stderr, "***No host open, use `host' command\n");
939 * Poll the socket and clear out any pending data
943 tvzero.tv_sec = tvzero.tv_usec = 0;
945 FD_SET(sockfd, &fds);
946 res = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero);
949 warning("polling select", "", "");
953 (void) recv(sockfd, junk, sizeof junk, 0);
960 res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata);
965 * Get the response. If we got a standard error, print a message
967 res = getresponse(implcode, reqcode, ritems, rsize, rdata, esize);
970 * Try to be compatible with older implementations of ntpd.
972 if (res == INFO_ERR_FMT && req_pkt_size != 48) {
975 oldsize = req_pkt_size;
977 switch(req_pkt_size) {
985 if (impl_ver == IMPL_XNTPD) {
987 "***Warning changing to older implementation\n");
988 return INFO_ERR_IMPL;
992 "***Warning changing the request packet size from %d to %d\n",
993 oldsize, req_pkt_size);
997 /* log error message if not told to be quiet */
998 if ((res > 0) && (((1 << res) & quiet_mask) == 0)) {
1001 /* Give us a chance to try the older implementation. */
1002 if (implcode == IMPL_XNTPD)
1004 (void) fprintf(stderr,
1005 "***Server implementation incompatable with our own\n");
1008 (void) fprintf(stderr,
1009 "***Server doesn't implement this request\n");
1012 (void) fprintf(stderr,
1013 "***Server reports a format error in the received packet (shouldn't happen)\n");
1015 case INFO_ERR_NODATA:
1016 (void) fprintf(stderr,
1017 "***Server reports data not found\n");
1020 (void) fprintf(stderr, "***Permission denied\n");
1023 (void) fprintf(stderr, "***Request timed out\n");
1025 case ERR_INCOMPLETE:
1026 (void) fprintf(stderr,
1027 "***Response from server was incomplete\n");
1030 (void) fprintf(stderr,
1031 "***Server returns unknown error code %d\n", res);
1040 * getcmds - read commands from the standard input and execute them
1045 #if defined(HAVE_LIBREADLINE) || defined(HAVE_LIBEDIT)
1049 if ((line = readline(interactive?prompt:"")) == NULL) return;
1050 if (*line) add_history(line);
1054 #else /* not (HAVE_LIBREADLINE || HAVE_LIBEDIT) */
1059 #ifdef VMS /* work around a problem with mixing stdout & stderr */
1062 (void) fputs(prompt, stderr);
1063 (void) fflush(stderr);
1066 if (fgets(line, sizeof line, stdin) == NULL)
1071 #endif /* not HAVE_LIBREADLINE || HAVE_LIBEDIT */
1075 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
1077 * abortcmd - catch interrupts and abort the current command
1085 if (current_output == stdout)
1086 (void) fflush(stdout);
1088 (void) fflush(stderr);
1089 if (jump) longjmp(interrupt_buf, 1);
1091 #endif /* SYS_WINNT */
1094 * docmd - decode the command line and execute a command
1101 char *tokens[1+MAXARGS+2];
1108 ai_fam_templ = ai_fam_default;
1110 * Tokenize the command line. If nothing on it, return.
1112 tokenize(cmdline, tokens, &ntok);
1117 * Find the appropriate command description.
1119 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1121 (void) fprintf(stderr, "***Command `%s' unknown\n",
1124 } else if (i >= 2) {
1125 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1131 * Save the keyword, then walk through the arguments, interpreting
1134 pcmd.keyword = tokens[0];
1137 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) {
1138 if ((i+ti) >= ntok) {
1139 if (!(xcmd->arg[i] & OPT)) {
1140 printusage(xcmd, stderr);
1145 if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>'))
1147 rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]);
1159 if (i < ntok && *tokens[i] == '>') {
1162 if (*(tokens[i]+1) != '\0')
1163 fname = tokens[i]+1;
1164 else if ((i+1) < ntok)
1165 fname = tokens[i+1];
1167 (void) fprintf(stderr, "***No file for redirect\n");
1171 current_output = fopen(fname, "w");
1172 if (current_output == NULL) {
1173 (void) fprintf(stderr, "***Error opening %s: ", fname);
1178 current_output = stdout;
1181 if (interactive && setjmp(interrupt_buf)) {
1185 (xcmd->handler)(&pcmd, current_output);
1187 if (current_output != stdout)
1188 (void) fclose(current_output);
1189 current_output = NULL;
1195 * tokenize - turn a command line into tokens
1204 register const char *cp;
1206 static char tspace[MAXLINE];
1210 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1212 while (ISSPACE(*cp))
1218 } while (!ISSPACE(*cp) && !ISEOL(*cp));
1227 * findcmd - find a command in a command description table
1232 struct xcmd *clist1,
1233 struct xcmd *clist2,
1237 register struct xcmd *cl;
1240 struct xcmd *nearmatch = NULL;
1247 else if (clist2 != 0)
1253 for (cl = clist; cl->keyword != 0; cl++) {
1254 /* do a first character check, for efficiency */
1255 if (*str != *(cl->keyword))
1257 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1259 * Could be extact match, could be approximate.
1260 * Is exact if the length of the keyword is the
1263 if (*((cl->keyword) + clen) == '\0') {
1273 * See if there is more to do. If so, go again. Sorry about the
1274 * goto, too much looking at BSD sources...
1276 if (clist == clist1 && clist2 != 0) {
1282 * If we got extactly 1 near match, use it, else return number
1294 * getarg - interpret an argument token
1296 * return: 0 - failure
1298 * -1 - skip to next token
1309 static const char *digits = "0123456789";
1311 switch (code & ~OPT) {
1316 if (!strcmp("-6", str)) {
1317 ai_fam_templ = AF_INET6;
1319 } else if (!strcmp("-4", str)) {
1320 ai_fam_templ = AF_INET;
1323 if (!getnetnum(str, &(argp->netnum), (char *)0, 0)) {
1338 cp = strchr(digits, *np);
1340 (void) fprintf(stderr,
1341 "***Illegal integer value %s\n", str);
1345 argp->uval += (cp - digits);
1346 } while (*(++np) != '\0');
1349 if ((code & ~OPT) == UINT) {
1350 (void) fprintf(stderr,
1351 "***Value %s should be unsigned\n", str);
1354 argp->ival = -argp->ival;
1358 if (!strcmp("-6", str))
1360 else if (!strcmp("-4", str))
1363 (void) fprintf(stderr,
1364 "***Version must be either 4 or 6\n");
1375 * getnetnum - given a host name, return its net number
1376 * and (optional) full name
1381 struct sockaddr_storage *num,
1388 struct addrinfo hints, *ai = NULL;
1390 sockaddr_len = (af == AF_INET)
1391 ? sizeof(struct sockaddr_in)
1392 : sizeof(struct sockaddr_in6);
1393 memset((char *)&hints, 0, sizeof(struct addrinfo));
1394 hints.ai_flags = AI_CANONNAME;
1395 #ifdef AI_ADDRCONFIG
1396 hints.ai_flags |= AI_ADDRCONFIG;
1399 /* decodenetnum only works with addresses */
1400 if (decodenetnum(hname, num)) {
1401 if (fullhost != 0) {
1402 getnameinfo((struct sockaddr *)num, sockaddr_len,
1403 fullhost, sizeof(fullhost), NULL, 0,
1407 } else if ((err = getaddrinfo(hname, "ntp", &hints, &ai)) == 0) {
1408 memmove((char *)num, ai->ai_addr, ai->ai_addrlen);
1410 (void) strcpy(fullhost, ai->ai_canonname);
1413 (void) fprintf(stderr, "***Can't find host %s\n", hname);
1420 * nntohost - convert network number to host name. This routine enforces
1421 * the showhostnames setting.
1425 struct sockaddr_storage *netnum
1429 return stoa(netnum);
1431 if ((netnum->ss_family == AF_INET) && ISREFCLOCKADR(netnum))
1432 return refnumtoa(netnum);
1433 return socktohost(netnum);
1438 * Finally, the built in command handlers
1442 * help - tell about commands, or details of a particular command
1454 const char *cmdsort[100];
1458 static const char *spaces = " "; /* 20 spaces */
1460 if (pcmd->nargs == 0) {
1462 for (xcp = builtins; xcp->keyword != 0; xcp++) {
1463 if (*(xcp->keyword) != '?')
1464 cmdsort[n++] = xcp->keyword;
1466 for (xcp = opcmds; xcp->keyword != 0; xcp++)
1467 cmdsort[n++] = xcp->keyword;
1469 #ifdef QSORT_USES_VOID_P
1470 qsort(cmdsort, (size_t)n, sizeof(char *), helpsort);
1472 qsort((char *)cmdsort, (size_t)n, sizeof(char *), helpsort);
1476 for (i = 0; i < n; i++) {
1477 length[i] = strlen(cmdsort[i]);
1478 if (length[i] > maxlength)
1479 maxlength = length[i];
1482 numperline = 76 / maxlength;
1484 (void) fprintf(fp, "Commands available:\n");
1485 for (i = 0; i < n; i++) {
1486 if ((i % numperline) == (numperline-1)
1488 (void) fprintf(fp, "%s\n", cmdsort[i]);
1490 (void) fprintf(fp, "%s%s", cmdsort[i],
1491 spaces+20-maxlength+length[i]);
1494 cmd = pcmd->argval[0].string;
1495 n = findcmd(cmd, builtins, opcmds, &xcp);
1497 (void) fprintf(stderr,
1498 "Command `%s' is unknown\n", cmd);
1500 } else if (n >= 2) {
1501 (void) fprintf(stderr,
1502 "Command `%s' is ambiguous\n", cmd);
1505 (void) fprintf(fp, "function: %s\n", xcp->comment);
1506 printusage(xcp, fp);
1512 * helpsort - do hostname qsort comparisons
1514 #ifdef QSORT_USES_VOID_P
1521 char const * const * name1 = (char const * const *)t1;
1522 char const * const * name2 = (char const * const *)t2;
1524 return strcmp(*name1, *name2);
1533 return strcmp(*name1, *name2);
1539 * printusage - print usage information for a command
1550 (void) fprintf(fp, "usage: %s", xcp->keyword);
1551 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
1552 if (opt46 == 0 && (xcp->arg[i] & ~OPT) == ADD) {
1553 (void) fprintf(fp, " [ -4|-6 ]");
1556 if (xcp->arg[i] & OPT)
1557 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
1559 (void) fprintf(fp, " %s", xcp->desc[i]);
1561 (void) fprintf(fp, "\n");
1566 * timeout - set time out time
1576 if (pcmd->nargs == 0) {
1577 val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
1578 (void) fprintf(fp, "primary timeout %d ms\n", val);
1580 tvout.tv_sec = pcmd->argval[0].uval / 1000;
1581 tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000))
1588 * my_delay - set delay for auth requests
1599 if (pcmd->nargs == 0) {
1600 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
1601 (void) fprintf(fp, "delay %lu ms\n", val);
1603 if (pcmd->argval[0].ival < 0) {
1605 val = (u_long)(-pcmd->argval[0].ival);
1608 val = (u_long)pcmd->argval[0].ival;
1611 delay_time.l_ui = val / 1000;
1613 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
1622 * host - set the host we are dealing with.
1632 if (pcmd->nargs == 0) {
1634 (void) fprintf(fp, "current host is %s\n", currenthost);
1636 (void) fprintf(fp, "no current host\n");
1641 if (pcmd->nargs == 2) {
1642 if (!strcmp("-4", pcmd->argval[i].string))
1643 ai_fam_templ = AF_INET;
1644 else if (!strcmp("-6", pcmd->argval[i].string))
1645 ai_fam_templ = AF_INET6;
1649 "current host remains %s\n", currenthost);
1651 (void) fprintf(fp, "still no current host\n");
1656 if (openhost(pcmd->argval[i].string)) {
1657 (void) fprintf(fp, "current host set to %s\n", currenthost);
1661 "current host remains %s\n", currenthost);
1663 (void) fprintf(fp, "still no current host\n");
1669 * keyid - get a keyid to use for authenticating requests
1677 if (pcmd->nargs == 0) {
1678 if (info_auth_keyid == 0)
1679 (void) fprintf(fp, "no keyid defined\n");
1681 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
1683 info_auth_keyid = pcmd->argval[0].uval;
1689 * keytype - get type of key to use for authenticating requests
1697 if (pcmd->nargs == 0)
1698 fprintf(fp, "keytype is %s\n",
1699 (info_auth_keytype == KEY_TYPE_MD5) ? "MD5" : "???");
1701 switch (*(pcmd->argval[0].string)) {
1704 info_auth_keytype = KEY_TYPE_MD5;
1708 fprintf(fp, "keytype must be 'md5'\n");
1715 * passwd - get an authentication key
1726 if (info_auth_keyid == 0) {
1727 info_auth_keyid = getkeyid("Keyid: ");
1728 if (info_auth_keyid == 0) {
1729 (void)fprintf(fp, "Keyid must be defined\n");
1734 authusekey(info_auth_keyid, info_auth_keytype,
1735 (u_char *)pcmd->argval[0].string);
1736 authtrust(info_auth_keyid, 1);
1738 pass = getpass("MD5 Password: ");
1740 (void) fprintf(fp, "Password unchanged\n");
1742 authusekey(info_auth_keyid, info_auth_keytype,
1744 authtrust(info_auth_keyid, 1);
1751 * hostnames - set the showhostnames flag
1759 if (pcmd->nargs == 0) {
1761 (void) fprintf(fp, "hostnames being shown\n");
1763 (void) fprintf(fp, "hostnames not being shown\n");
1765 if (STREQ(pcmd->argval[0].string, "yes"))
1767 else if (STREQ(pcmd->argval[0].string, "no"))
1770 (void)fprintf(stderr, "What?\n");
1776 * setdebug - set/change debugging level
1784 if (pcmd->nargs == 0) {
1785 (void) fprintf(fp, "debug level is %d\n", debug);
1787 } else if (STREQ(pcmd->argval[0].string, "no")) {
1789 } else if (STREQ(pcmd->argval[0].string, "more")) {
1791 } else if (STREQ(pcmd->argval[0].string, "less")) {
1794 (void) fprintf(fp, "What?\n");
1797 (void) fprintf(fp, "debug level set to %d\n", debug);
1802 * quit - stop this nonsense
1812 closesocket(sockfd);
1818 * version - print the current version number
1828 (void) fprintf(fp, "%s\n", Version);
1834 * warning - print a warning message
1843 (void) fprintf(stderr, "%s: ", progname);
1844 (void) fprintf(stderr, fmt, st1, st2);
1845 (void) fprintf(stderr, ": ");
1851 * error - print a message and exit
1860 warning(fmt, st1, st2);
1865 * getkeyid - prompt the user for a keyid to use
1869 const char *keyprompt
1878 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
1880 if ((fi = _fdopen((int)GetStdHandle(STD_INPUT_HANDLE), "r")) == NULL)
1881 #endif /* SYS_WINNT */
1884 setbuf(fi, (char *)NULL);
1885 fprintf(stderr, "%s", keyprompt); fflush(stderr);
1886 for (p=pbuf; (c = getc(fi))!='\n' && c!=EOF;) {
1893 return (u_int32)atoi(pbuf);