2 * ntpdc - control and monitor your ntpd daemon
20 #include <isc/result.h>
23 #include "ntp_select.h"
24 #include "ntp_stdlib.h"
25 #include "ntp_assert.h"
26 #include "ntp_lineedit.h"
28 #include "openssl/evp.h"
29 #include "openssl/objects.h"
31 #include <ssl_applink.c>
33 #include "ntp_libopts.h"
34 #include "ntpdc-opts.h"
38 /* vxWorks needs mode flag -casey*/
39 # define open(name, flags) open(name, flags, 0777)
40 # define SERVER_PORT_NUM 123
43 /* We use COMMAND as an autogen keyword */
49 * Because we now potentially understand a lot of commands (and
50 * it requires a lot of commands to talk to ntpd) we will run
51 * interactive if connected to a terminal.
53 static int interactive = 0; /* set to 1 when we should prompt */
54 static const char * prompt = "ntpdc> "; /* prompt to ask him about */
57 * Keyid used for authenticated requests. Obtained on the fly.
59 static u_long info_auth_keyid;
60 static int keyid_entered = 0;
62 static int info_auth_keytype = NID_md5; /* MD5 */
63 static size_t info_auth_hashlen = 16; /* MD5 */
64 u_long current_time; /* needed by authkeys; not used */
69 s_char sys_precision; /* local clock precision (log2 s) */
71 int ntpdcmain (int, char **);
73 * Built in command handler declarations
75 static int openhost (const char *);
76 static int sendpkt (void *, size_t);
77 static void growpktdata (void);
78 static int getresponse (int, int, size_t *, size_t *, const char **, size_t);
79 static int sendrequest (int, int, int, size_t, size_t, const char *);
80 static void getcmds (void);
81 static RETSIGTYPE abortcmd (int);
82 static void docmd (const char *);
83 static void tokenize (const char *, char **, int *);
84 static int findcmd (char *, struct xcmd *, struct xcmd *, struct xcmd **);
85 static int getarg (char *, int, arg_v *);
86 static int getnetnum (const char *, sockaddr_u *, char *, int);
87 static void help (struct parse *, FILE *);
88 static int helpsort (const void *, const void *);
89 static void printusage (struct xcmd *, FILE *);
90 static void timeout (struct parse *, FILE *);
91 static void my_delay (struct parse *, FILE *);
92 static void host (struct parse *, FILE *);
93 static void keyid (struct parse *, FILE *);
94 static void keytype (struct parse *, FILE *);
95 static void passwd (struct parse *, FILE *);
96 static void hostnames (struct parse *, FILE *);
97 static void setdebug (struct parse *, FILE *);
98 static void quit (struct parse *, FILE *);
99 static void version (struct parse *, FILE *);
100 static void warning (const char *, ...)
101 __attribute__((__format__(__printf__, 1, 2)));
102 static void error (const char *, ...)
103 __attribute__((__format__(__printf__, 1, 2)));
104 static u_long getkeyid (const char *);
109 * Built-in commands we understand
111 static struct xcmd builtins[] = {
112 { "?", help, { OPT|NTP_STR, NO, NO, NO },
113 { "command", "", "", "" },
114 "tell the use and syntax of commands" },
115 { "help", help, { OPT|NTP_STR, NO, NO, NO },
116 { "command", "", "", "" },
117 "tell the use and syntax of commands" },
118 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
119 { "msec", "", "", "" },
120 "set the primary receive time out" },
121 { "delay", my_delay, { OPT|NTP_INT, NO, NO, NO },
122 { "msec", "", "", "" },
123 "set the delay added to encryption time stamps" },
124 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
125 { "-4|-6", "hostname", "", "" },
126 "specify the host whose NTP server we talk to" },
127 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
129 "specify a password to use for authenticated requests"},
130 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
131 { "yes|no", "", "", "" },
132 "specify whether hostnames or net numbers are printed"},
133 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
134 { "no|more|less", "", "", "" },
135 "set/change debugging level" },
136 { "quit", quit, { NO, NO, NO, NO },
139 { "exit", quit, { NO, NO, NO, NO },
142 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
143 { "key#", "", "", "" },
144 "set/show keyid to use for authenticated requests" },
145 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
146 { "(md5|des)", "", "", "" },
147 "set/show key authentication type for authenticated requests (des|md5)" },
148 { "version", version, { NO, NO, NO, NO },
150 "print version number" },
151 { 0, 0, { NO, NO, NO, NO },
152 { "", "", "", "" }, "" }
157 * Default values we use.
159 #define DEFHOST "localhost" /* default host name */
160 #define DEFTIMEOUT (5) /* 5 second time out */
161 #define DEFSTIMEOUT (2) /* 2 second time out after first */
162 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
163 #define LENHOSTNAME 256 /* host name is 256 characters long */
164 #define MAXCMDS 100 /* maximum commands on cmd line */
165 #define MAXHOSTS 200 /* maximum hosts on cmd line */
166 #define MAXLINE 512 /* maximum line length */
167 #define MAXTOKENS (1+1+MAXARGS+MOREARGS+2) /* maximum number of usable tokens */
168 #define SCREENWIDTH 78 /* nominal screen width in columns */
171 * Some variables used and manipulated locally
173 static struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
174 static struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
175 static l_fp delay_time; /* delay time */
176 static char currenthost[LENHOSTNAME]; /* current host name */
177 int showhostnames = 1; /* show host names by default */
179 static int ai_fam_templ; /* address family */
180 static int ai_fam_default; /* default address family */
181 static SOCKET sockfd; /* fd socket is opened on */
182 static int havehost = 0; /* set to 1 when host open */
186 * Holds data returned from queries. We allocate INITDATASIZE
187 * octets to begin with, increasing this as we need to.
189 #define INITDATASIZE (sizeof(struct resp_pkt) * 16)
190 #define INCDATASIZE (sizeof(struct resp_pkt) * 8)
192 static char *pktdata;
193 static int pktdatasize;
196 * These are used to help the magic with old and new versions of ntpd.
198 int impl_ver = IMPL_XNTPD;
199 static int req_pkt_size = REQ_LEN_NOMAC;
202 * For commands typed on the command line (with the -c option)
204 static int numcmds = 0;
205 static const char *ccmds[MAXCMDS];
206 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
209 * When multiple hosts are specified.
211 static int numhosts = 0;
212 static const char *chosts[MAXHOSTS];
213 #define ADDHOST(cp) if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp)
216 * Error codes for internal use
218 #define ERR_INCOMPLETE 16
219 #define ERR_TIMEOUT 17
222 * Macro definitions we use
224 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
225 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
226 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
229 * Jump buffer for longjumping back to the command level
231 static jmp_buf interrupt_buf;
232 static volatile int jump = 0;
235 * Pointer to current output unit
237 static FILE *current_output;
240 * Command table imported from ntpdc_ops.c
242 extern struct xcmd opcmds[];
244 char const *progname;
246 #ifdef NO_MAIN_ALLOWED
247 CALL(ntpdc,"ntpdc",ntpdcmain);
255 return ntpdcmain(argc, argv);
260 void clear_globals(void)
262 showhostnames = 0; /* show host names by default */
263 havehost = 0; /* set to 1 when host open */
270 * main - parse arguments and handle options
280 delay_time.l_uf = DEFDELAY;
284 taskPrioritySet(taskIdSelf(), 100 );
287 init_lib(); /* sets up ipv4_works, ipv6_works */
291 /* Check to see if we have IPv6. Otherwise default to IPv4 */
293 ai_fam_default = AF_INET;
298 int optct = ntpOptionProcess(&ntpdcOptions, argc, argv);
304 ai_fam_templ = AF_INET;
305 else if (HAVE_OPT(IPV6))
306 ai_fam_templ = AF_INET6;
308 ai_fam_templ = ai_fam_default;
310 if (HAVE_OPT(COMMAND)) {
311 int cmdct = STACKCT_OPT( COMMAND );
312 const char** cmds = STACKLST_OPT( COMMAND );
314 while (cmdct-- > 0) {
319 debug = OPT_VALUE_SET_DEBUG_LEVEL;
321 if (HAVE_OPT(INTERACTIVE)) {
325 if (HAVE_OPT(NUMERIC)) {
329 if (HAVE_OPT(LISTPEERS)) {
333 if (HAVE_OPT(PEERS)) {
337 if (HAVE_OPT(SHOWPEERS)) {
341 if (ntp_optind == argc) {
344 for (; ntp_optind < argc; ntp_optind++)
345 ADDHOST(argv[ntp_optind]);
348 if (numcmds == 0 && interactive == 0
349 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
353 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
355 (void) signal_no_reset(SIGINT, abortcmd);
356 #endif /* SYS_WINNT */
359 * Initialize the packet data buffer
361 pktdatasize = INITDATASIZE;
362 pktdata = emalloc(INITDATASIZE);
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
395 char temphost[LENHOSTNAME];
397 struct addrinfo hints, *ai = NULL;
400 register const char *cp;
401 char name[LENHOSTNAME];
405 * We need to get by the [] if they were entered
412 for (i = 0; *cp && *cp != ']'; cp++, i++)
423 * First try to resolve it as an ip address and if that fails,
424 * do a fullblown (dns) lookup. That way we only use the dns
425 * when it is needed and work around some implementations that
426 * will return an "IPv4-mapped IPv6 address" address if you
427 * give it an IPv4 address to lookup.
429 strlcpy(service, "ntp", sizeof(service));
431 hints.ai_family = ai_fam_templ;
432 hints.ai_protocol = IPPROTO_UDP;
433 hints.ai_socktype = SOCK_DGRAM;
434 hints.ai_flags = Z_AI_NUMERICHOST;
436 a_info = getaddrinfo(hname, service, &hints, &ai);
437 if (a_info == EAI_NONAME
439 || a_info == EAI_NODATA
442 hints.ai_flags = AI_CANONNAME;
444 hints.ai_flags |= AI_ADDRCONFIG;
446 a_info = getaddrinfo(hname, service, &hints, &ai);
448 /* Some older implementations don't like AI_ADDRCONFIG. */
449 if (a_info == EAI_BADFLAGS) {
450 hints.ai_flags = AI_CANONNAME;
451 a_info = getaddrinfo(hname, service, &hints, &ai);
454 fprintf(stderr, "%s\n", gai_strerror(a_info));
461 * getaddrinfo() has returned without error so ai should not
466 octets = min(sizeof(addr), ai->ai_addrlen);
467 memcpy(&addr, ai->ai_addr, octets);
469 if (ai->ai_canonname == NULL)
470 strlcpy(temphost, stoa(&addr), sizeof(temphost));
472 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
475 printf("Opening host %s\n", temphost);
479 printf("Closing old host %s\n", currenthost);
483 strlcpy(currenthost, temphost, sizeof(currenthost));
485 /* port maps to the same in both families */
486 s_port = NSRCPORT(&addr);;
488 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
489 if (ai->ai_family == AF_INET)
490 *(struct sockaddr_in *)&hostaddr=
491 *((struct sockaddr_in *)ai->ai_addr);
493 *(struct sockaddr_in6 *)&hostaddr=
494 *((struct sockaddr_in6 *)ai->ai_addr);
495 #endif /* SYS_VXWORKS */
499 int optionValue = SO_SYNCHRONOUS_NONALERT;
502 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue));
503 if (err != NO_ERROR) {
504 (void) fprintf(stderr, "cannot open nonoverlapped sockets\n");
508 #endif /* SYS_WINNT */
510 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0);
511 if (sockfd == INVALID_SOCKET) {
516 #ifdef NEED_RCVBUF_SLOP
519 int rbufsize = INITDATASIZE + 2048; /* 2K for slop */
521 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
522 &rbufsize, sizeof(int)) == -1)
529 if (connect(sockfd, (struct sockaddr *)&hostaddr,
530 sizeof(hostaddr)) == -1)
532 if (connect(sockfd, ai->ai_addr, ai->ai_addrlen) == -1)
533 #endif /* SYS_VXWORKS */
541 req_pkt_size = REQ_LEN_NOMAC;
542 impl_ver = IMPL_XNTPD;
547 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
549 * sendpkt - send a packet to the remote host
557 if (send(sockfd, xdata, xdatalen, 0) == -1) {
558 warning("write to %s failed", currenthost);
567 * growpktdata - grow the packet data area
574 priorsz = (size_t)pktdatasize;
575 pktdatasize += INCDATASIZE;
576 pktdata = erealloc_zero(pktdata, (size_t)pktdatasize, priorsz);
581 * getresponse - get a (series of) response packet(s) and return the data
593 struct resp_pkt rpkt;
594 struct sock_timeval tvo;
601 char haveseq[MAXSEQ+1];
611 * This is pretty tricky. We may get between 1 and many packets
612 * back in response to the request. We peel the data out of
613 * each packet and collect it in one long block. When the last
614 * packet in the sequence is received we'll know how many we
615 * should have had. Note we use one long time out, should reconsider.
621 *rdata = datap = pktdata;
622 lastseq = 999; /* too big to be a sequence number */
632 FD_SET(sockfd, &fds);
633 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
635 warning("select fails");
640 * Timed out. Return what we have
643 (void) fprintf(stderr,
644 "%s: timed out, nothing received\n",
648 (void) fprintf(stderr,
649 "%s: timed out with incomplete data\n",
652 printf("Received sequence numbers");
653 for (n = 0; n <= MAXSEQ; n++)
657 printf(" last frame received\n");
659 printf(" last frame not received\n");
661 return ERR_INCOMPLETE;
665 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
673 * Check for format errors. Bug proofing.
675 if (n < (ssize_t)RESP_HEADER_SIZE) {
677 printf("Short (%zd byte) packet received\n", n);
680 if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION ||
681 INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) {
683 printf("Packet received with version %d\n",
684 INFO_VERSION(rpkt.rm_vn_mode));
687 if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) {
689 printf("Packet received with mode %d\n",
690 INFO_MODE(rpkt.rm_vn_mode));
693 if (INFO_IS_AUTH(rpkt.auth_seq)) {
695 printf("Encrypted packet received\n");
698 if (!ISRESPONSE(rpkt.rm_vn_mode)) {
700 printf("Received request packet, wanted response\n");
703 if (INFO_MBZ(rpkt.mbz_itemsize) != 0) {
705 printf("Received packet with nonzero MBZ field!\n");
710 * Check implementation/request. Could be old data getting to us.
712 if (rpkt.implementation != implcode || rpkt.request != reqcode) {
715 "Received implementation/request of %d/%d, wanted %d/%d",
716 rpkt.implementation, rpkt.request,
722 * Check the error code. If non-zero, return it.
724 if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) {
725 if (debug && ISMORE(rpkt.rm_vn_mode)) {
726 printf("Error code %d received on not-final packet\n",
727 INFO_ERR(rpkt.err_nitems));
729 return (int)INFO_ERR(rpkt.err_nitems);
733 * Collect items and size. Make sure they make sense.
735 items = INFO_NITEMS(rpkt.err_nitems);
736 size = INFO_ITEMSIZE(rpkt.mbz_itemsize);
741 datasize = items * size;
742 if ((size_t)datasize > (n-RESP_HEADER_SIZE)) {
745 "Received items %zu, size %zu (total %zu), data in packet is %zu\n",
746 items, size, datasize, n-RESP_HEADER_SIZE);
751 * If this isn't our first packet, make sure the size matches
754 if (!firstpkt && size != *rsize) {
756 printf("Received itemsize %zu, previous %zu\n",
761 * If we've received this before, +toss it
763 seq = INFO_SEQ(rpkt.auth_seq);
766 printf("Received duplicate sequence number %d\n", seq);
772 * If this is the last in the sequence, record that.
774 if (!ISMORE(rpkt.rm_vn_mode)) {
775 if (lastseq != 999) {
776 printf("Received second end sequence packet\n");
783 * So far, so good. Copy this data into the output array.
785 if ((datap + datasize + (pad * items)) > (pktdata + pktdatasize)) {
786 size_t offset = datap - pktdata;
788 *rdata = pktdata; /* might have been realloced ! */
789 datap = pktdata + offset;
792 * We now move the pointer along according to size and number of
793 * items. This is so we can play nice with older implementations
796 tmp_data = rpkt.u.data;
797 for (i = 0; i < items; i++) {
798 memcpy(datap, tmp_data, (unsigned)size);
800 zero_mem(datap + size, pad);
811 * Finally, check the count of received packets. If we've got them
815 if (numrecv <= lastseq)
822 * sendrequest - format and send a request packet
824 * Historically, ntpdc has used a fixed-size request packet regardless
825 * of the actual payload size. When authenticating, the timestamp, key
826 * ID, and digest have been placed just before the end of the packet.
827 * With the introduction in late 2009 of support for authenticated
828 * ntpdc requests using larger 20-octet digests (vs. 16 for MD5), we
829 * come up four bytes short.
831 * To maintain interop while allowing for larger digests, the behavior
832 * is unchanged when using 16-octet digests. For larger digests, the
833 * timestamp, key ID, and digest are placed immediately following the
834 * request payload, with the overall packet size variable. ntpd can
835 * distinguish 16-octet digests by the overall request size being
836 * REQ_LEN_NOMAC + 4 + 16 with the auth bit enabled. When using a
837 * longer digest, that request size should be avoided.
839 * With the form used with 20-octet and larger digests, the timestamp,
840 * key ID, and digest are located by ntpd relative to the start of the
841 * packet, and the size of the digest is then implied by the packet
864 qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0);
865 qpkt.implementation = (u_char)implcode;
866 qpkt.request = (u_char)reqcode;
868 datasize = qitems * qsize;
869 if (datasize && qdata != NULL) {
870 memcpy(qpkt.u.data, qdata, datasize);
871 qpkt.err_nitems = ERR_NITEMS(0, qitems);
872 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize);
874 qpkt.err_nitems = ERR_NITEMS(0, 0);
875 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize); /* allow for optional first item */
878 if (!auth || (keyid_entered && info_auth_keyid == 0)) {
879 qpkt.auth_seq = AUTH_SEQ(0, 0);
880 return sendpkt(&qpkt, req_pkt_size);
883 if (info_auth_keyid == 0) {
884 key_id = getkeyid("Keyid: ");
886 fprintf(stderr, "Invalid key identifier\n");
889 info_auth_keyid = key_id;
891 if (!authistrusted(info_auth_keyid)) {
892 pass = getpass_keytype(info_auth_keytype);
893 if ('\0' == pass[0]) {
894 fprintf(stderr, "Invalid password\n");
897 authusekey(info_auth_keyid, info_auth_keytype,
899 authtrust(info_auth_keyid, 1);
901 qpkt.auth_seq = AUTH_SEQ(1, 0);
902 if (info_auth_hashlen > 16) {
904 * Only ntpd which expects REQ_LEN_NOMAC plus maclen
905 * octets in an authenticated request using a 16 octet
906 * digest (that is, a newer ntpd) will handle digests
907 * larger than 16 octets, so for longer digests, do
908 * not attempt to shorten the requests for downlevel
909 * ntpd compatibility.
911 if (REQ_LEN_NOMAC != req_pkt_size)
913 reqsize = REQ_LEN_HDR + datasize + sizeof(*ptstamp);
914 /* align to 32 bits */
915 reqsize = (reqsize + 3) & ~3;
917 reqsize = req_pkt_size;
918 ptstamp = (void *)((char *)&qpkt + reqsize);
921 L_ADD(&ts, &delay_time);
922 HTONL_FP(&ts, ptstamp);
923 maclen = authencrypt(
924 info_auth_keyid, (void *)&qpkt, size2int_chk(reqsize));
926 fprintf(stderr, "Key not found\n");
928 } else if (maclen != (int)(info_auth_hashlen + sizeof(keyid_t))) {
930 "%zu octet MAC, %zu expected with %zu octet digest\n",
931 maclen, (info_auth_hashlen + sizeof(keyid_t)),
935 return sendpkt(&qpkt, reqsize + maclen);
940 * doquery - send a request and process the response
960 struct sock_timeval tvzero;
963 * Check to make sure host is open
966 (void) fprintf(stderr, "***No host open, use `host' command\n");
971 * Poll the socket and clear out any pending data
975 tvzero.tv_sec = tvzero.tv_usec = 0;
977 FD_SET(sockfd, &fds);
978 res = select(sockfd+1, &fds, NULL, NULL, &tvzero);
980 warning("polling select");
984 (void) recv(sockfd, junk, sizeof junk, 0);
991 res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata);
996 * Get the response. If we got a standard error, print a message
998 res = getresponse(implcode, reqcode, ritems, rsize, rdata, esize);
1001 * Try to be compatible with older implementations of ntpd.
1003 if (res == INFO_ERR_FMT && req_pkt_size != 48) {
1006 oldsize = req_pkt_size;
1008 switch(req_pkt_size) {
1016 if (impl_ver == IMPL_XNTPD) {
1018 "***Warning changing to older implementation\n");
1019 return INFO_ERR_IMPL;
1023 "***Warning changing the request packet size from %d to %d\n",
1024 oldsize, req_pkt_size);
1028 /* log error message if not told to be quiet */
1029 if ((res > 0) && (((1 << res) & quiet_mask) == 0)) {
1032 /* Give us a chance to try the older implementation. */
1033 if (implcode == IMPL_XNTPD)
1035 (void) fprintf(stderr,
1036 "***Server implementation incompatible with our own\n");
1039 (void) fprintf(stderr,
1040 "***Server doesn't implement this request\n");
1043 (void) fprintf(stderr,
1044 "***Server reports a format error in the received packet (shouldn't happen)\n");
1046 case INFO_ERR_NODATA:
1047 (void) fprintf(stderr,
1048 "***Server reports data not found\n");
1051 (void) fprintf(stderr, "***Permission denied\n");
1054 (void) fprintf(stderr, "***Request timed out\n");
1056 case ERR_INCOMPLETE:
1057 (void) fprintf(stderr,
1058 "***Response from server was incomplete\n");
1061 (void) fprintf(stderr,
1062 "***Server returns unknown error code %d\n", res);
1071 * getcmds - read commands from the standard input and execute them
1079 ntp_readline_init(interactive ? prompt : NULL);
1082 line = ntp_readline(&count);
1089 ntp_readline_uninit();
1093 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
1095 * abortcmd - catch interrupts and abort the current command
1103 if (current_output == stdout)
1104 (void) fflush(stdout);
1106 (void) fflush(stderr);
1107 if (jump) longjmp(interrupt_buf, 1);
1109 #endif /* SYS_WINNT */
1112 * docmd - decode the command line and execute a command
1119 char *tokens[1+MAXARGS+MOREARGS+2];
1126 ai_fam_templ = ai_fam_default;
1128 * Tokenize the command line. If nothing on it, return.
1130 if (strlen(cmdline) >= MAXLINE) {
1131 fprintf(stderr, "***Command ignored, more than %d characters:\n%s\n",
1132 MAXLINE - 1, cmdline);
1135 tokenize(cmdline, tokens, &ntok);
1140 * Find the appropriate command description.
1142 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1144 (void) fprintf(stderr, "***Command `%s' unknown\n",
1147 } else if (i >= 2) {
1148 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1154 * Save the keyword, then walk through the arguments, interpreting
1157 pcmd.keyword = tokens[0];
1160 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) {
1161 if ((i+ti) >= ntok) {
1162 if (!(xcmd->arg[i] & OPT)) {
1163 printusage(xcmd, stderr);
1168 if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>'))
1170 rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]);
1181 /* Any extra args are assumed to be "OPT|NTP_STR". */
1182 for ( ; i < MAXARGS + MOREARGS;) {
1185 rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]);
1197 if (i < ntok && *tokens[i] == '>') {
1200 if (*(tokens[i]+1) != '\0')
1201 fname = tokens[i]+1;
1202 else if ((i+1) < ntok)
1203 fname = tokens[i+1];
1205 (void) fprintf(stderr, "***No file for redirect\n");
1209 current_output = fopen(fname, "w");
1210 if (current_output == NULL) {
1211 (void) fprintf(stderr, "***Error opening %s: ", fname);
1216 current_output = stdout;
1219 if (interactive && setjmp(interrupt_buf)) {
1223 (xcmd->handler)(&pcmd, current_output);
1225 if (current_output != stdout)
1226 (void) fclose(current_output);
1227 current_output = NULL;
1233 * tokenize - turn a command line into tokens
1242 register const char *cp;
1244 static char tspace[MAXLINE];
1248 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1250 while (ISSPACE(*cp))
1256 } while (!ISSPACE(*cp) && !ISEOL(*cp));
1265 * findcmd - find a command in a command description table
1270 struct xcmd *clist1,
1271 struct xcmd *clist2,
1275 register struct xcmd *cl;
1278 struct xcmd *nearmatch = NULL;
1285 else if (clist2 != 0)
1291 for (cl = clist; cl->keyword != 0; cl++) {
1292 /* do a first character check, for efficiency */
1293 if (*str != *(cl->keyword))
1295 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1297 * Could be extact match, could be approximate.
1298 * Is exact if the length of the keyword is the
1301 if (*((cl->keyword) + clen) == '\0') {
1311 * See if there is more to do. If so, go again. Sorry about the
1312 * goto, too much looking at BSD sources...
1314 if (clist == clist1 && clist2 != 0) {
1320 * If we got extactly 1 near match, use it, else return number
1332 * getarg - interpret an argument token
1334 * string is always set.
1335 * type is set to the decoded type.
1337 * return: 0 - failure
1339 * -1 - skip to next token
1350 static const char *digits = "0123456789";
1354 argp->type = code & ~OPT;
1356 switch (argp->type) {
1360 if (!strcmp("-6", str)) {
1361 ai_fam_templ = AF_INET6;
1363 } else if (!strcmp("-4", str)) {
1364 ai_fam_templ = AF_INET;
1367 if (!getnetnum(str, &(argp->netnum), (char *)0, 0)) {
1382 cp = strchr(digits, *np);
1384 (void) fprintf(stderr,
1385 "***Illegal integer value %s\n", str);
1389 argp->uval += (u_long)(cp - digits);
1390 } while (*(++np) != '\0');
1393 if ((code & ~OPT) == NTP_UINT) {
1394 (void) fprintf(stderr,
1395 "***Value %s should be unsigned\n", str);
1398 argp->ival = -argp->ival;
1402 if (!strcmp("-6", str))
1404 else if (!strcmp("-4", str))
1407 (void) fprintf(stderr,
1408 "***Version must be either 4 or 6\n");
1419 * getnetnum - given a host name, return its net number
1420 * and (optional) full name
1430 struct addrinfo hints, *ai = NULL;
1433 hints.ai_flags = AI_CANONNAME;
1434 #ifdef AI_ADDRCONFIG
1435 hints.ai_flags |= AI_ADDRCONFIG;
1439 * decodenetnum only works with addresses, but handles syntax
1440 * that getaddrinfo doesn't: [2001::1]:1234
1442 if (decodenetnum(hname, num)) {
1443 if (fullhost != NULL)
1444 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1445 LENHOSTNAME, NULL, 0, 0);
1447 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1448 INSIST(sizeof(*num) >= ai->ai_addrlen);
1449 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1450 if (fullhost != NULL) {
1451 if (ai->ai_canonname != NULL)
1452 strlcpy(fullhost, ai->ai_canonname,
1455 getnameinfo(&num->sa, SOCKLEN(num),
1456 fullhost, LENHOSTNAME, NULL,
1461 fprintf(stderr, "***Can't find host %s\n", hname);
1468 * nntohost - convert network number to host name. This routine enforces
1469 * the showhostnames setting.
1476 if (!showhostnames || SOCK_UNSPEC(netnum))
1477 return stoa(netnum);
1478 else if (ISREFCLOCKADR(netnum))
1479 return refnumtoa(netnum);
1481 return socktohost(netnum);
1486 * Finally, the built in command handlers
1490 * help - tell about commands, or details of a particular command
1500 const char *list[100];
1506 if (pcmd->nargs == 0) {
1508 for (xcp = builtins; xcp->keyword != 0; xcp++) {
1509 if (*(xcp->keyword) != '?')
1510 list[words++] = xcp->keyword;
1512 for (xcp = opcmds; xcp->keyword != 0; xcp++)
1513 list[words++] = xcp->keyword;
1515 qsort((void *)list, words, sizeof(list[0]), helpsort);
1517 for (word = 0; word < words; word++) {
1518 length = strlen(list[word]);
1519 col = max(col, length);
1522 cols = SCREENWIDTH / ++col;
1523 rows = (words + cols - 1) / cols;
1525 fprintf(fp, "ntpdc commands:\n");
1527 for (row = 0; row < rows; row++) {
1528 for (word = row; word < words; word += rows)
1529 fprintf(fp, "%-*.*s", (int)col,
1530 (int)col - 1, list[word]);
1534 cmd = pcmd->argval[0].string;
1535 words = findcmd(cmd, builtins, opcmds, &xcp);
1538 "Command `%s' is unknown\n", cmd);
1540 } else if (words >= 2) {
1542 "Command `%s' is ambiguous\n", cmd);
1545 fprintf(fp, "function: %s\n", xcp->comment);
1546 printusage(xcp, fp);
1552 * helpsort - do hostname qsort comparisons
1560 const char * const * name1 = t1;
1561 const char * const * name2 = t2;
1563 return strcmp(*name1, *name2);
1568 * printusage - print usage information for a command
1579 (void) fprintf(fp, "usage: %s", xcp->keyword);
1580 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
1581 if (opt46 == 0 && (xcp->arg[i] & ~OPT) == NTP_ADD) {
1582 (void) fprintf(fp, " [ -4|-6 ]");
1585 if (xcp->arg[i] & OPT)
1586 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
1588 (void) fprintf(fp, " %s", xcp->desc[i]);
1590 (void) fprintf(fp, "\n");
1595 * timeout - set time out time
1605 if (pcmd->nargs == 0) {
1606 val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
1607 (void) fprintf(fp, "primary timeout %d ms\n", val);
1609 tvout.tv_sec = pcmd->argval[0].uval / 1000;
1610 tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000))
1617 * my_delay - set delay for auth requests
1628 if (pcmd->nargs == 0) {
1629 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
1630 (void) fprintf(fp, "delay %lu ms\n", val);
1632 if (pcmd->argval[0].ival < 0) {
1634 val = (u_long)(-pcmd->argval[0].ival);
1637 val = (u_long)pcmd->argval[0].ival;
1640 delay_time.l_ui = val / 1000;
1642 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
1651 * host - set the host we are dealing with.
1661 if (pcmd->nargs == 0) {
1663 (void) fprintf(fp, "current host is %s\n", currenthost);
1665 (void) fprintf(fp, "no current host\n");
1670 if (pcmd->nargs == 2) {
1671 if (!strcmp("-4", pcmd->argval[i].string))
1672 ai_fam_templ = AF_INET;
1673 else if (!strcmp("-6", pcmd->argval[i].string))
1674 ai_fam_templ = AF_INET6;
1678 "current host remains %s\n", currenthost);
1680 (void) fprintf(fp, "still no current host\n");
1685 if (openhost(pcmd->argval[i].string)) {
1686 (void) fprintf(fp, "current host set to %s\n", currenthost);
1690 "current host remains %s\n", currenthost);
1692 (void) fprintf(fp, "still no current host\n");
1698 * keyid - get a keyid to use for authenticating requests
1706 if (pcmd->nargs == 0) {
1707 if (info_auth_keyid == 0 && !keyid_entered)
1708 (void) fprintf(fp, "no keyid defined\n");
1709 else if (info_auth_keyid == 0 && keyid_entered)
1710 (void) fprintf(fp, "no keyid will be sent\n");
1712 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
1714 info_auth_keyid = pcmd->argval[0].uval;
1721 * keytype - get type of key to use for authenticating requests
1729 const char * digest_name;
1734 fprintf(fp, "keytype is %s with %lu octet digests\n",
1735 keytype_name(info_auth_keytype),
1736 (u_long)info_auth_hashlen);
1740 digest_name = pcmd->argval[0].string;
1742 key_type = keytype_from_text(digest_name, &digest_len);
1745 fprintf(fp, "keytype must be 'md5'%s\n",
1747 " or a digest type provided by OpenSSL");
1754 info_auth_keytype = key_type;
1755 info_auth_hashlen = digest_len;
1760 * passwd - get an authentication key
1771 if (info_auth_keyid == 0) {
1772 info_auth_keyid = getkeyid("Keyid: ");
1773 if (info_auth_keyid == 0) {
1774 (void)fprintf(fp, "Keyid must be defined\n");
1778 if (pcmd->nargs >= 1)
1779 pass = pcmd->argval[0].string;
1781 pass = getpass_keytype(info_auth_keytype);
1782 if ('\0' == *pass) {
1783 fprintf(fp, "Password unchanged\n");
1787 authusekey(info_auth_keyid, info_auth_keytype, (u_char *)pass);
1788 authtrust(info_auth_keyid, 1);
1793 * hostnames - set the showhostnames flag
1801 if (pcmd->nargs == 0) {
1803 (void) fprintf(fp, "hostnames being shown\n");
1805 (void) fprintf(fp, "hostnames not being shown\n");
1807 if (STREQ(pcmd->argval[0].string, "yes"))
1809 else if (STREQ(pcmd->argval[0].string, "no"))
1812 (void)fprintf(stderr, "What?\n");
1818 * setdebug - set/change debugging level
1826 if (pcmd->nargs == 0) {
1827 (void) fprintf(fp, "debug level is %d\n", debug);
1829 } else if (STREQ(pcmd->argval[0].string, "no")) {
1831 } else if (STREQ(pcmd->argval[0].string, "more")) {
1833 } else if (STREQ(pcmd->argval[0].string, "less")) {
1836 (void) fprintf(fp, "What?\n");
1839 (void) fprintf(fp, "debug level set to %d\n", debug);
1844 * quit - stop this nonsense
1854 closesocket(sockfd);
1860 * version - print the current version number
1870 (void) fprintf(fp, "%s\n", Version);
1875 static void __attribute__((__format__(__printf__, 1, 0)))
1876 vwarning(const char *fmt, va_list ap)
1879 (void) fprintf(stderr, "%s: ", progname);
1880 vfprintf(stderr, fmt, ap);
1881 (void) fprintf(stderr, ": %s\n", strerror(serrno));
1885 * warning - print a warning message
1887 static void __attribute__((__format__(__printf__, 1, 2)))
1901 * error - print a message and exit
1903 static void __attribute__((__format__(__printf__, 1, 2)))
1917 * getkeyid - prompt the user for a keyid to use
1921 const char *keyprompt
1931 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
1933 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
1934 #endif /* SYS_WINNT */
1937 setbuf(fi, (char *)NULL);
1938 fprintf(stderr, "%s", keyprompt); fflush(stderr);
1939 for (i = 0, ilim = COUNTOF(pbuf) - 1;
1940 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
1942 pbuf[i++] = (char)c;
1947 return (u_long) atoi(pbuf);