2 * ntpq - query an NTP server using mode 6 commands
21 #include <isc/result.h>
24 #include "ntp_assert.h"
25 #include "ntp_stdlib.h"
26 #include "ntp_unixtime.h"
27 #include "ntp_calendar.h"
28 #include "ntp_select.h"
29 #include "ntp_assert.h"
30 #include "lib_strbuf.h"
31 #include "ntp_lineedit.h"
32 #include "ntp_debug.h"
34 #include "openssl/evp.h"
35 #include "openssl/objects.h"
36 #include "openssl/err.h"
38 #include <ssl_applink.c>
40 #include "ntp_libopts.h"
41 #include "ntpq-opts.h"
43 #ifdef SYS_VXWORKS /* vxWorks needs mode flag -casey*/
44 # define open(name, flags) open(name, flags, 0777)
45 # define SERVER_PORT_NUM 123
48 /* we use COMMAND as an autogen keyword */
54 * Because we potentially understand a lot of commands we will run
55 * interactive if connected to a terminal.
57 int interactive = 0; /* set to 1 when we should prompt */
58 const char *prompt = "ntpq> "; /* prompt to ask him about */
61 * use old readvars behavior? --old-rv processing in ntpq resets
62 * this value based on the presence or absence of --old-rv. It is
63 * initialized to 1 here to maintain backward compatibility with
64 * libntpq clients such as ntpsnmpd, which are free to reset it as
73 s_char sys_precision; /* local clock precision (log2 s) */
76 * Keyid used for authenticated requests. Obtained on the fly.
78 u_long info_auth_keyid = 0;
80 static int info_auth_keytype = NID_md5; /* MD5 */
81 static size_t info_auth_hashlen = 16; /* MD5 */
82 u_long current_time; /* needed by authkeys; not used */
85 * Flag which indicates we should always send authenticated requests
90 * Flag which indicates raw mode output.
95 * Packet version number we use
97 u_char pktversion = NTP_OLDVERSION + 1;
100 * Don't jump if no set jmp.
102 volatile int jump = 0;
108 #define HA 1 /* host address */
109 #define NA 2 /* network address */
110 #define LP 3 /* leap (print in binary) */
111 #define RF 4 /* refid (sometimes string, sometimes not) */
112 #define AR 5 /* array of times */
113 #define FX 6 /* test flags */
114 #define TS 7 /* l_fp timestamp in hex */
115 #define OC 8 /* integer, print in octal */
116 #define EOV 255 /* end of table */
119 * For the most part ntpq simply displays what ntpd provides in the
120 * mostly plain-text mode 6 responses. A few variable names are by
121 * default "cooked" to provide more human-friendly output.
123 const var_format cookedvars[] = {
134 { "peeradr", HA }, /* compat with others */
137 { "filtoffset", AR },
139 { "filterror", AR }, /* compat with others */
147 static const char *tstflagnames[] = {
148 "pkt_dup", /* TEST1 */
149 "pkt_bogus", /* TEST2 */
150 "pkt_unsync", /* TEST3 */
151 "pkt_denied", /* TEST4 */
152 "pkt_auth", /* TEST5 */
153 "pkt_stratum", /* TEST6 */
154 "pkt_header", /* TEST7 */
155 "pkt_autokey", /* TEST8 */
156 "pkt_crypto", /* TEST9 */
157 "peer_stratum", /* TEST10 */
158 "peer_dist", /* TEST11 */
159 "peer_loop", /* TEST12 */
160 "peer_unreach" /* TEST13 */
164 int ntpqmain (int, char **);
166 * Built in command handler declarations
168 static int openhost (const char *, int);
169 static void dump_hex_printable(const void *, size_t);
170 static int sendpkt (void *, size_t);
171 static int getresponse (int, int, u_short *, int *, const char **, int);
172 static int sendrequest (int, associd_t, int, int, const char *);
173 static char * tstflags (u_long);
175 static void getcmds (void);
177 static RETSIGTYPE abortcmd (int);
178 #endif /* SYS_WINNT */
179 static void docmd (const char *);
180 static void tokenize (const char *, char **, int *);
181 static int getarg (const char *, int, arg_v *);
182 #endif /* BUILD_AS_LIB */
183 static int findcmd (const char *, struct xcmd *,
184 struct xcmd *, struct xcmd **);
185 static int rtdatetolfp (char *, l_fp *);
186 static int decodearr (char *, int *, l_fp *);
187 static void help (struct parse *, FILE *);
188 static int helpsort (const void *, const void *);
189 static void printusage (struct xcmd *, FILE *);
190 static void timeout (struct parse *, FILE *);
191 static void auth_delay (struct parse *, FILE *);
192 static void host (struct parse *, FILE *);
193 static void ntp_poll (struct parse *, FILE *);
194 static void keyid (struct parse *, FILE *);
195 static void keytype (struct parse *, FILE *);
196 static void passwd (struct parse *, FILE *);
197 static void hostnames (struct parse *, FILE *);
198 static void setdebug (struct parse *, FILE *);
199 static void quit (struct parse *, FILE *);
200 static void version (struct parse *, FILE *);
201 static void raw (struct parse *, FILE *);
202 static void cooked (struct parse *, FILE *);
203 static void authenticate (struct parse *, FILE *);
204 static void ntpversion (struct parse *, FILE *);
205 static void warning (const char *, ...)
206 __attribute__((__format__(__printf__, 1, 2)));
207 static void error (const char *, ...)
208 __attribute__((__format__(__printf__, 1, 2)));
209 static u_long getkeyid (const char *);
210 static void atoascii (const char *, size_t, char *, size_t);
211 static void cookedprint (int, int, const char *, int, int, FILE *);
212 static void rawprint (int, int, const char *, int, int, FILE *);
213 static void startoutput (void);
214 static void output (FILE *, const char *, const char *);
215 static void endoutput (FILE *);
216 static void outputarr (FILE *, char *, int, l_fp *);
217 static int assoccmp (const void *, const void *);
218 u_short varfmt (const char *);
220 void ntpq_custom_opt_handler (tOptions *, tOptDesc *);
223 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
224 static void list_md_fn(const EVP_MD *m, const char *from,
225 const char *to, void *arg );
228 static char *list_digest_names(void);
231 * Built-in commands we understand
233 struct xcmd builtins[] = {
234 { "?", help, { OPT|NTP_STR, NO, NO, NO },
235 { "command", "", "", "" },
236 "tell the use and syntax of commands" },
237 { "help", help, { OPT|NTP_STR, NO, NO, NO },
238 { "command", "", "", "" },
239 "tell the use and syntax of commands" },
240 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
241 { "msec", "", "", "" },
242 "set the primary receive time out" },
243 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
244 { "msec", "", "", "" },
245 "set the delay added to encryption time stamps" },
246 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
247 { "-4|-6", "hostname", "", "" },
248 "specify the host whose NTP server we talk to" },
249 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
250 { "n", "verbose", "", "" },
251 "poll an NTP server in client mode `n' times" },
252 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
254 "specify a password to use for authenticated requests"},
255 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
256 { "yes|no", "", "", "" },
257 "specify whether hostnames or net numbers are printed"},
258 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
259 { "no|more|less", "", "", "" },
260 "set/change debugging level" },
261 { "quit", quit, { NO, NO, NO, NO },
264 { "exit", quit, { NO, NO, NO, NO },
267 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
268 { "key#", "", "", "" },
269 "set keyid to use for authenticated requests" },
270 { "version", version, { NO, NO, NO, NO },
272 "print version number" },
273 { "raw", raw, { NO, NO, NO, NO },
275 "do raw mode variable output" },
276 { "cooked", cooked, { NO, NO, NO, NO },
278 "do cooked mode variable output" },
279 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
280 { "yes|no", "", "", "" },
281 "always authenticate requests to this server" },
282 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
283 { "version number", "", "", "" },
284 "set the NTP version number to use for requests" },
285 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
286 { "key type %s", "", "", "" },
288 { 0, 0, { NO, NO, NO, NO },
289 { "", "", "", "" }, "" }
294 * Default values we use.
296 #define DEFHOST "localhost" /* default host name */
297 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
298 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
300 * Requests are automatically retried once, so total timeout with no
301 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
302 * extreme, a request eliciting 32 packets of responses each for some
303 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
304 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
305 * 93 seconds to fail each of two times, or 186 seconds.
306 * Some commands involve a series of requests, such as "peers" and
307 * "mrulist", so the cumulative timeouts are even longer for those.
309 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
310 #define LENHOSTNAME 256 /* host name is 256 characters long */
311 #define MAXCMDS 100 /* maximum commands on cmd line */
312 #define MAXHOSTS 200 /* maximum hosts on cmd line */
313 #define MAXLINE 512 /* maximum line length */
314 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
315 #define MAXVARLEN 256 /* maximum length of a variable name */
316 #define MAXVALLEN 2048 /* maximum length of a variable value */
317 #define MAXOUTLINE 72 /* maximum length of an output line */
318 #define SCREENWIDTH 76 /* nominal screen width in columns */
321 * Some variables used and manipulated locally
323 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
324 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
325 l_fp delay_time; /* delay time */
326 char currenthost[LENHOSTNAME]; /* current host name */
327 int currenthostisnum; /* is prior text from IP? */
328 struct sockaddr_in hostaddr; /* host address */
329 int showhostnames = 1; /* show host names by default */
330 int wideremote = 0; /* show wide remote names? */
332 int ai_fam_templ; /* address family */
333 int ai_fam_default; /* default address family */
334 SOCKET sockfd; /* fd socket is opened on */
335 int havehost = 0; /* set to 1 when host open */
337 struct servent *server_entry = NULL; /* server entry for ntp */
341 * Sequence number used for requests. It is incremented before
347 * Holds data returned from queries. Declare buffer long to be sure of
350 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
351 long pktdata[DATASIZE/sizeof(long)];
354 * assoc_cache[] is a dynamic array which allows references to
355 * associations using &1 ... &N for n associations, avoiding manual
356 * lookup of the current association IDs for a given ntpd. It also
357 * caches the status word for each association, retrieved incidentally.
359 struct association * assoc_cache;
360 u_int assoc_cache_slots;/* count of allocated array entries */
361 u_int numassoc; /* number of cached associations */
364 * For commands typed on the command line (with the -c option)
367 const char *ccmds[MAXCMDS];
368 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
371 * When multiple hosts are specified.
376 chost chosts[MAXHOSTS];
377 #define ADDHOST(cp) \
379 if (numhosts < MAXHOSTS) { \
380 chosts[numhosts].name = (cp); \
381 chosts[numhosts].fam = ai_fam_templ; \
387 * Macro definitions we use
389 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
390 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
391 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
394 * Jump buffer for longjumping back to the command level
396 jmp_buf interrupt_buf;
399 * Points at file being currently printed into
401 FILE *current_output;
404 * Command table imported from ntpdc_ops.c
406 extern struct xcmd opcmds[];
410 #ifdef NO_MAIN_ALLOWED
412 CALL(ntpq,"ntpq",ntpqmain);
414 void clear_globals(void)
416 extern int ntp_optind;
417 showhostnames = 0; /* don'tshow host names by default */
419 server_entry = NULL; /* server entry for ntp */
420 havehost = 0; /* set to 1 when host open */
421 numassoc = 0; /* number of cached associations */
425 #endif /* !BUILD_AS_LIB */
426 #endif /* NO_MAIN_ALLOWED */
429 * main - parse arguments and handle options
431 #ifndef NO_MAIN_ALLOWED
438 return ntpqmain(argc, argv);
455 taskPrioritySet(taskIdSelf(), 100 );
459 delay_time.l_uf = DEFDELAY;
461 init_lib(); /* sets up ipv4_works, ipv6_works */
465 /* Check to see if we have IPv6. Otherwise default to IPv4 */
467 ai_fam_default = AF_INET;
469 /* Fixup keytype's help based on available digest names */
475 list = list_digest_names();
476 for (icmd = 0; icmd < sizeof(builtins)/sizeof(builtins[0]); icmd++) {
477 if (strcmp("keytype", builtins[icmd].keyword) == 0)
482 /* This should only "trip" if "keytype" is removed from builtins */
483 INSIST(icmd < sizeof(builtins)/sizeof(builtins[0]));
486 builtins[icmd].desc[0] = "digest-name";
487 fmt = "set key type to use for authenticated requests, one of:%s";
489 builtins[icmd].desc[0] = "md5";
490 fmt = "set key type to use for authenticated requests (%s)";
492 msg = malloc(strlen(fmt) + strlen(list) - strlen("%s") +1);
493 sprintf(msg, fmt, list);
494 builtins[icmd].comment = msg;
501 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
507 * Process options other than -c and -p, which are specially
508 * handled by ntpq_custom_opt_handler().
511 debug = OPT_VALUE_SET_DEBUG_LEVEL;
514 ai_fam_templ = AF_INET;
515 else if (HAVE_OPT(IPV6))
516 ai_fam_templ = AF_INET6;
518 ai_fam_templ = ai_fam_default;
520 if (HAVE_OPT(INTERACTIVE))
523 if (HAVE_OPT(NUMERIC))
529 old_rv = HAVE_OPT(OLD_RV);
534 for (ihost = 0; ihost < (u_int)argc; ihost++) {
535 if ('-' == *argv[ihost]) {
537 // If I really cared I'd also check:
538 // 0 == argv[ihost][2]
540 // and there are other cases as well...
542 if ('4' == argv[ihost][1]) {
543 ai_fam_templ = AF_INET;
545 } else if ('6' == argv[ihost][1]) {
546 ai_fam_templ = AF_INET6;
549 // XXX Throw a usage error
552 ADDHOST(argv[ihost]);
556 if (numcmds == 0 && interactive == 0
557 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
561 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
563 (void) signal_no_reset(SIGINT, abortcmd);
564 #endif /* SYS_WINNT */
567 (void) openhost(chosts[0].name, chosts[0].fam);
570 for (ihost = 0; ihost < numhosts; ihost++) {
571 if (openhost(chosts[ihost].name, chosts[ihost].fam))
572 for (icmd = 0; icmd < numcmds; icmd++)
578 #endif /* SYS_WINNT */
581 #endif /* !BUILD_AS_LIB */
584 * openhost - open a socket to a host
592 const char svc[] = "ntp";
593 char temphost[LENHOSTNAME];
595 struct addrinfo hints, *ai;
598 register const char *cp;
599 char name[LENHOSTNAME];
602 * We need to get by the [] if they were entered
609 for (i = 0; *cp && *cp != ']'; cp++, i++)
620 * First try to resolve it as an ip address and if that fails,
621 * do a fullblown (dns) lookup. That way we only use the dns
622 * when it is needed and work around some implementations that
623 * will return an "IPv4-mapped IPv6 address" address if you
624 * give it an IPv4 address to lookup.
627 hints.ai_family = fam;
628 hints.ai_protocol = IPPROTO_UDP;
629 hints.ai_socktype = SOCK_DGRAM;
630 hints.ai_flags = Z_AI_NUMERICHOST;
633 a_info = getaddrinfo(hname, svc, &hints, &ai);
634 if (a_info == EAI_NONAME
636 || a_info == EAI_NODATA
639 hints.ai_flags = AI_CANONNAME;
641 hints.ai_flags |= AI_ADDRCONFIG;
643 a_info = getaddrinfo(hname, svc, &hints, &ai);
646 /* Some older implementations don't like AI_ADDRCONFIG. */
647 if (a_info == EAI_BADFLAGS) {
648 hints.ai_flags &= ~AI_ADDRCONFIG;
649 a_info = getaddrinfo(hname, svc, &hints, &ai);
653 fprintf(stderr, "%s\n", gai_strerror(a_info));
659 octets = min(sizeof(addr), ai->ai_addrlen);
660 memcpy(&addr, ai->ai_addr, octets);
662 if (ai->ai_canonname == NULL) {
663 strlcpy(temphost, stoa(&addr), sizeof(temphost));
664 currenthostisnum = TRUE;
666 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
667 currenthostisnum = FALSE;
671 printf("Opening host %s (%s)\n",
673 (ai->ai_family == AF_INET)
675 : (ai->ai_family == AF_INET6)
682 printf("Closing old host %s\n", currenthost);
686 strlcpy(currenthost, temphost, sizeof(currenthost));
688 /* port maps to the same location in both families */
689 s_port = NSRCPORT(&addr);
691 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
692 if (ai->ai_family == AF_INET)
693 *(struct sockaddr_in *)&hostaddr=
694 *((struct sockaddr_in *)ai->ai_addr);
696 *(struct sockaddr_in6 *)&hostaddr=
697 *((struct sockaddr_in6 *)ai->ai_addr);
698 #endif /* SYS_VXWORKS */
702 int optionValue = SO_SYNCHRONOUS_NONALERT;
705 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
706 (char *)&optionValue, sizeof(optionValue));
709 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
715 #endif /* SYS_WINNT */
717 sockfd = socket(ai->ai_family, ai->ai_socktype,
719 if (sockfd == INVALID_SOCKET) {
726 #ifdef NEED_RCVBUF_SLOP
728 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
729 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
730 &rbufsize, sizeof(int)) == -1)
738 (connect(sockfd, (struct sockaddr *)&hostaddr,
739 sizeof(hostaddr)) == -1)
741 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
742 ai->ai_addrlen) == -1)
743 #endif /* SYS_VXWORKS */
764 const char * rowstart;
772 rowlen = min(16, len);
773 for (idx = 0; idx < rowlen; idx++) {
775 printf("%02x ", uch);
777 for ( ; idx < 16 ; idx++)
780 for (idx = 0; idx < rowlen; idx++) {
782 printf("%c", (isprint(uch))
792 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
794 * sendpkt - send a packet to the remote host
803 printf("Sending %zu octets\n", xdatalen);
805 if (send(sockfd, xdata, (size_t)xdatalen, 0) == -1) {
806 warning("write to %s failed", currenthost);
811 printf("Request packet:\n");
812 dump_hex_printable(xdata, xdatalen);
818 * getresponse - get a (series of) response packet(s) and return the data
830 struct ntp_control rpkt;
831 struct sock_timeval tvo;
832 u_short offsets[MAXFRAGS+1];
833 u_short counts[MAXFRAGS+1];
846 * This is pretty tricky. We may get between 1 and MAXFRAG packets
847 * back in response to the request. We peel the data out of
848 * each packet and collect it in one long block. When the last
849 * packet in the sequence is received we'll know how much data we
850 * should have had. Note we use one long time out, should reconsider.
855 *rdata = (char *)pktdata;
863 * Loop until we have an error or a complete response. Nearly all
864 * code paths to loop again use continue.
873 FD_SET(sockfd, &fds);
874 n = select(sockfd + 1, &fds, NULL, NULL, &tvo);
877 warning("select fails");
882 * Timed out. Return what we have
887 "%s: timed out, nothing received\n",
893 "%s: timed out with incomplete data\n",
897 "ERR_INCOMPLETE: Received fragments:\n");
898 for (f = 0; f < numfrags; f++)
900 "%2u: %5d %5d\t%3d octets\n",
901 (u_int)f, offsets[f],
906 "last fragment %sreceived\n",
911 return ERR_INCOMPLETE;
914 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
921 printf("Response packet:\n");
922 dump_hex_printable(&rpkt, n);
926 * Check for format errors. Bug proofing.
928 if (n < (int)CTL_HEADER_LEN) {
930 printf("Short (%d byte) packet received\n", n);
933 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
934 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
936 printf("Packet received with version %d\n",
937 PKT_VERSION(rpkt.li_vn_mode));
940 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
942 printf("Packet received with mode %d\n",
943 PKT_MODE(rpkt.li_vn_mode));
946 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
948 printf("Received request packet, wanted response\n");
953 * Check opcode and sequence number for a match.
954 * Could be old data getting to us.
956 if (ntohs(rpkt.sequence) != sequence) {
958 printf("Received sequnce number %d, wanted %d\n",
959 ntohs(rpkt.sequence), sequence);
962 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
965 "Received opcode %d, wanted %d (sequence number okay)\n",
966 CTL_OP(rpkt.r_m_e_op), opcode);
971 * Check the error code. If non-zero, return it.
973 if (CTL_ISERROR(rpkt.r_m_e_op)) {
974 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
975 if (CTL_ISMORE(rpkt.r_m_e_op))
976 TRACE(1, ("Error code %d received on not-final packet\n",
978 if (errcode == CERR_UNSPEC)
984 * Check the association ID to make sure it matches what
987 if (ntohs(rpkt.associd) != associd) {
988 TRACE(1, ("Association ID %d doesn't match expected %d\n",
989 ntohs(rpkt.associd), associd));
991 * Hack for silly fuzzballs which, at the time of writing,
992 * return an assID of sys.peer when queried for system variables.
1000 * Collect offset and count. Make sure they make sense.
1002 offset = ntohs(rpkt.offset);
1003 count = ntohs(rpkt.count);
1006 * validate received payload size is padded to next 32-bit
1007 * boundary and no smaller than claimed by rpkt.count
1010 TRACE(1, ("Response packet not padded, size = %d\n",
1015 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1017 if (n < shouldbesize) {
1018 printf("Response packet claims %u octets payload, above %ld received\n",
1019 count, (long)n - CTL_HEADER_LEN);
1020 return ERR_INCOMPLETE;
1023 if (debug >= 3 && shouldbesize > n) {
1029 * Usually we ignore authentication, but for debugging purposes
1032 /* round to 8 octet boundary */
1033 shouldbesize = (shouldbesize + 7) & ~7;
1035 maclen = n - shouldbesize;
1036 if (maclen >= (int)MIN_MAC_LEN) {
1038 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1039 n, shouldbesize, maclen);
1040 lpkt = (u_int32 *)&rpkt;
1041 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1042 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1043 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1044 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1045 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1046 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1047 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1048 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1049 printf("Authenticated with keyid %lu\n", (u_long)key);
1050 if (key != 0 && key != info_auth_keyid) {
1051 printf("We don't know that key\n");
1053 if (authdecrypt(key, (u_int32 *)&rpkt,
1054 n - maclen, maclen)) {
1055 printf("Auth okay!\n");
1057 printf("Auth failed!\n");
1063 TRACE(2, ("Got packet, size = %d\n", n));
1064 if (count > (n - CTL_HEADER_LEN)) {
1065 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1066 count, (long)n - CTL_HEADER_LEN));
1069 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1070 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1073 if (offset + count > sizeof(pktdata)) {
1074 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1078 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1079 TRACE(1, ("Received second last fragment packet\n"));
1084 * So far, so good. Record this fragment, making sure it doesn't
1087 TRACE(2, ("Packet okay\n"));
1089 if (numfrags > (MAXFRAGS - 1)) {
1090 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1096 * Find the position for the fragment relative to any
1097 * previously received.
1100 f < numfrags && offsets[f] < offset;
1105 if (f < numfrags && offset == offsets[f]) {
1106 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1107 count, offset, counts[f], offsets[f]));
1111 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1112 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1113 offset, counts[f-1], offsets[f-1]));
1117 if (f < numfrags && (offset + count) > offsets[f]) {
1118 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1119 count, offset, offsets[f]));
1123 for (ff = numfrags; ff > f; ff--) {
1124 offsets[ff] = offsets[ff-1];
1125 counts[ff] = counts[ff-1];
1127 offsets[f] = offset;
1132 * Got that stuffed in right. Figure out if this was the last.
1133 * Record status info out of the last packet.
1135 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1138 *rstatus = ntohs(rpkt.status);
1142 * Copy the data into the data buffer.
1144 memcpy((char *)pktdata + offset, &rpkt.u, count);
1147 * If we've seen the last fragment, look for holes in the sequence.
1148 * If there aren't any, we're done.
1150 if (seenlastfrag && offsets[0] == 0) {
1151 for (f = 1; f < numfrags; f++)
1152 if (offsets[f-1] + counts[f-1] !=
1155 if (f == numfrags) {
1156 *rsize = offsets[f-1] + counts[f-1];
1157 TRACE(1, ("%lu packets reassembled into response\n",
1162 } /* giant for (;;) collecting response packets */
1163 } /* getresponse() */
1167 * sendrequest - format and send a request packet
1178 struct ntp_control qpkt;
1185 * Check to make sure the data will fit in one packet
1187 if (qsize > CTL_MAX_DATA_LEN) {
1189 "***Internal error! qsize (%d) too large\n",
1195 * Fill in the packet
1197 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1198 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1199 qpkt.sequence = htons(sequence);
1201 qpkt.associd = htons((u_short)associd);
1203 qpkt.count = htons((u_short)qsize);
1205 pktsize = CTL_HEADER_LEN;
1208 * If we have data, copy and pad it out to a 32-bit boundary.
1211 memcpy(&qpkt.u, qdata, (size_t)qsize);
1213 while (pktsize & (sizeof(u_int32) - 1)) {
1214 qpkt.u.data[qsize++] = 0;
1220 * If it isn't authenticated we can just send it. Otherwise
1221 * we're going to have to think about it a little.
1223 if (!auth && !always_auth) {
1224 return sendpkt(&qpkt, pktsize);
1228 * Pad out packet to a multiple of 8 octets to be sure
1229 * receiver can handle it.
1231 while (pktsize & 7) {
1232 qpkt.u.data[qsize++] = 0;
1237 * Get the keyid and the password if we don't have one.
1239 if (info_auth_keyid == 0) {
1240 key_id = getkeyid("Keyid: ");
1241 if (key_id == 0 || key_id > NTP_MAXKEY) {
1243 "Invalid key identifier\n");
1246 info_auth_keyid = key_id;
1248 if (!authistrusted(info_auth_keyid)) {
1249 pass = getpass_keytype(info_auth_keytype);
1250 if ('\0' == pass[0]) {
1251 fprintf(stderr, "Invalid password\n");
1254 authusekey(info_auth_keyid, info_auth_keytype,
1256 authtrust(info_auth_keyid, 1);
1260 * Do the encryption.
1262 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1264 fprintf(stderr, "Key not found\n");
1266 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1268 "%d octet MAC, %zu expected with %zu octet digest\n",
1269 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1274 return sendpkt((char *)&qpkt, pktsize + maclen);
1279 * show_error_msg - display the error text for a mode 6 error response.
1288 fprintf(stderr, "server=%s ", currenthost);
1294 "***Server reports a bad format request packet\n");
1297 case CERR_PERMISSION:
1299 "***Server disallowed request (authentication?)\n");
1304 "***Server reports a bad opcode in request\n");
1309 "***Association ID %d unknown to server\n",
1313 case CERR_UNKNOWNVAR:
1315 "***A request variable unknown to the server\n");
1320 "***Server indicates a request variable was bad\n");
1325 "***Server returned an unspecified error\n");
1329 fprintf(stderr, "***Request timed out\n");
1332 case ERR_INCOMPLETE:
1334 "***Response from server was incomplete\n");
1339 "***Buffer size exceeded for returned data\n");
1344 "***Server returns unknown error code %d\n",
1350 * doquery - send a request and process the response, displaying
1351 * error messages for any error responses.
1365 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1366 rsize, rdata, FALSE);
1371 * doqueryex - send a request and process the response, optionally
1372 * displaying error messages for any error responses.
1391 * Check to make sure host is open
1394 fprintf(stderr, "***No host open, use `host' command\n");
1405 res = sendrequest(opcode, associd, auth, qsize, qdata);
1410 * Get the response. If we got a standard error, print a message
1412 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1415 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1416 if (res == ERR_INCOMPLETE) {
1418 * better bump the sequence so we don't
1419 * get confused about differing fragments.
1427 show_error_msg(res, associd);
1434 #ifndef BUILD_AS_LIB
1436 * getcmds - read commands from the standard input and execute them
1444 ntp_readline_init(interactive ? prompt : NULL);
1447 line = ntp_readline(&count);
1454 ntp_readline_uninit();
1456 #endif /* !BUILD_AS_LIB */
1459 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1461 * abortcmd - catch interrupts and abort the current command
1468 if (current_output == stdout)
1469 (void) fflush(stdout);
1471 (void) fflush(stderr);
1472 if (jump) longjmp(interrupt_buf, 1);
1474 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1477 #ifndef BUILD_AS_LIB
1479 * docmd - decode the command line and execute a command
1486 char *tokens[1+MAXARGS+2];
1493 * Tokenize the command line. If nothing on it, return.
1495 tokenize(cmdline, tokens, &ntok);
1500 * Find the appropriate command description.
1502 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1504 (void) fprintf(stderr, "***Command `%s' unknown\n",
1507 } else if (i >= 2) {
1508 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1513 /* Warn about ignored extra args */
1514 for (i = MAXARGS + 1; i < ntok ; ++i) {
1515 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1519 * Save the keyword, then walk through the arguments, interpreting
1522 pcmd.keyword = tokens[0];
1524 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1525 if ((i+1) >= ntok) {
1526 if (!(xcmd->arg[i] & OPT)) {
1527 printusage(xcmd, stderr);
1532 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1534 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1540 if (i < ntok && *tokens[i] == '>') {
1543 if (*(tokens[i]+1) != '\0')
1544 fname = tokens[i]+1;
1545 else if ((i+1) < ntok)
1546 fname = tokens[i+1];
1548 (void) fprintf(stderr, "***No file for redirect\n");
1552 current_output = fopen(fname, "w");
1553 if (current_output == NULL) {
1554 (void) fprintf(stderr, "***Error opening %s: ", fname);
1558 i = 1; /* flag we need a close */
1560 current_output = stdout;
1561 i = 0; /* flag no close */
1564 if (interactive && setjmp(interrupt_buf)) {
1569 (xcmd->handler)(&pcmd, current_output);
1570 jump = 0; /* HMS: 961106: was after fclose() */
1571 if (i) (void) fclose(current_output);
1579 * tokenize - turn a command line into tokens
1581 * SK: Modified to allow a quoted string
1583 * HMS: If the first character of the first token is a ':' then (after
1584 * eating inter-token whitespace) the 2nd token is the rest of the line.
1594 register const char *cp;
1596 static char tspace[MAXLINE];
1600 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1603 /* Skip inter-token whitespace */
1604 while (ISSPACE(*cp))
1607 /* If we're at EOL we're done */
1611 /* If this is the 2nd token and the first token begins
1612 * with a ':', then just grab to EOL.
1615 if (*ntok == 1 && tokens[0][0] == ':') {
1617 if (sp - tspace >= MAXLINE)
1620 } while (!ISEOL(*cp));
1623 /* Check if this token begins with a double quote.
1624 * If yes, continue reading till the next double quote
1626 else if (*cp == '\"') {
1629 if (sp - tspace >= MAXLINE)
1632 } while ((*cp != '\"') && !ISEOL(*cp));
1633 /* HMS: a missing closing " should be an error */
1637 if (sp - tspace >= MAXLINE)
1640 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1641 /* HMS: Why check for a " in the previous line? */
1644 if (sp - tspace >= MAXLINE)
1653 "***Line `%s' is too big\n",
1660 * getarg - interpret an argument token
1671 switch (code & ~OPT) {
1677 if (!getnetnum(str, &argp->netnum, NULL, 0))
1682 if ('&' == str[0]) {
1683 if (!atouint(&str[1], &ul)) {
1685 "***Association index `%s' invalid/undecodable\n",
1689 if (0 == numassoc) {
1691 if (0 == numassoc) {
1693 "***No associations found, `%s' unknown\n",
1698 ul = min(ul, numassoc);
1699 argp->uval = assoc_cache[ul - 1].assid;
1702 if (!atouint(str, &argp->uval)) {
1703 fprintf(stderr, "***Illegal unsigned value %s\n",
1710 if (!atoint(str, &argp->ival)) {
1711 fprintf(stderr, "***Illegal integer value %s\n",
1718 if (!strcmp("-6", str)) {
1720 } else if (!strcmp("-4", str)) {
1723 fprintf(stderr, "***Version must be either 4 or 6\n");
1731 #endif /* !BUILD_AS_LIB */
1735 * findcmd - find a command in a command description table
1740 struct xcmd * clist1,
1741 struct xcmd * clist2,
1748 struct xcmd *nearmatch = NULL;
1755 else if (clist2 != 0)
1761 for (cl = clist; cl->keyword != 0; cl++) {
1762 /* do a first character check, for efficiency */
1763 if (*str != *(cl->keyword))
1765 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1767 * Could be extact match, could be approximate.
1768 * Is exact if the length of the keyword is the
1771 if (*((cl->keyword) + clen) == '\0') {
1781 * See if there is more to do. If so, go again. Sorry about the
1782 * goto, too much looking at BSD sources...
1784 if (clist == clist1 && clist2 != 0) {
1790 * If we got extactly 1 near match, use it, else return number
1802 * getnetnum - given a host name, return its net number
1803 * and (optional) full name
1813 struct addrinfo hints, *ai = NULL;
1816 hints.ai_flags = AI_CANONNAME;
1817 #ifdef AI_ADDRCONFIG
1818 hints.ai_flags |= AI_ADDRCONFIG;
1822 * decodenetnum only works with addresses, but handles syntax
1823 * that getaddrinfo doesn't: [2001::1]:1234
1825 if (decodenetnum(hname, num)) {
1826 if (fullhost != NULL)
1827 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1828 LENHOSTNAME, NULL, 0, 0);
1830 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1831 INSIST(sizeof(*num) >= ai->ai_addrlen);
1832 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1833 if (fullhost != NULL) {
1834 if (ai->ai_canonname != NULL)
1835 strlcpy(fullhost, ai->ai_canonname,
1838 getnameinfo(&num->sa, SOCKLEN(num),
1839 fullhost, LENHOSTNAME, NULL,
1845 fprintf(stderr, "***Can't find host %s\n", hname);
1852 * nntohost - convert network number to host name. This routine enforces
1853 * the showhostnames setting.
1860 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1865 * nntohost_col - convert network number to host name in fixed width.
1866 * This routine enforces the showhostnames setting.
1867 * When displaying hostnames longer than the width,
1868 * the first part of the hostname is displayed. When
1869 * displaying numeric addresses longer than the width,
1870 * Such as IPv6 addresses, the caller decides whether
1871 * the first or last of the numeric address is used.
1877 int preserve_lowaddrbits
1882 if (!showhostnames || SOCK_UNSPEC(addr)) {
1883 if (preserve_lowaddrbits)
1884 out = trunc_left(stoa(addr), width);
1886 out = trunc_right(stoa(addr), width);
1887 } else if (ISREFCLOCKADR(addr)) {
1888 out = refnumtoa(addr);
1890 out = trunc_right(socktohost(addr), width);
1897 * nntohostp() is the same as nntohost() plus a :port suffix
1907 if (!showhostnames || SOCK_UNSPEC(netnum))
1908 return sptoa(netnum);
1909 else if (ISREFCLOCKADR(netnum))
1910 return refnumtoa(netnum);
1912 hostn = socktohost(netnum);
1914 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1920 * rtdatetolfp - decode an RT-11 date into an l_fp
1930 struct calendar cal;
1936 * An RT-11 date looks like:
1938 * d[d]-Mth-y[y] hh:mm:ss
1940 * (No docs, but assume 4-digit years are also legal...)
1942 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
1945 if (!isdigit((int)*cp)) {
1948 * Catch special case
1956 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
1957 if (isdigit((int)*cp)) {
1958 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
1959 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
1965 for (i = 0; i < 3; i++)
1969 for (i = 0; i < 12; i++)
1970 if (STREQ(buf, months[i]))
1974 cal.month = (u_char)(i + 1);
1979 if (!isdigit((int)*cp))
1981 cal.year = (u_short)(*cp++ - '0');
1982 if (isdigit((int)*cp)) {
1983 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1984 cal.year = (u_short)(*cp++ - '0');
1986 if (isdigit((int)*cp)) {
1987 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1988 cal.year = (u_short)(cal.year + *cp++ - '0');
1990 if (isdigit((int)*cp)) {
1991 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1992 cal.year = (u_short)(cal.year + *cp++ - '0');
1996 * Catch special case. If cal.year == 0 this is a zero timestamp.
1998 if (cal.year == 0) {
2003 if (*cp++ != ' ' || !isdigit((int)*cp))
2005 cal.hour = (u_char)(*cp++ - '0');
2006 if (isdigit((int)*cp)) {
2007 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2008 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2011 if (*cp++ != ':' || !isdigit((int)*cp))
2013 cal.minute = (u_char)(*cp++ - '0');
2014 if (isdigit((int)*cp)) {
2015 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2016 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2019 if (*cp++ != ':' || !isdigit((int)*cp))
2021 cal.second = (u_char)(*cp++ - '0');
2022 if (isdigit((int)*cp)) {
2023 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2024 cal.second = (u_char)(cal.second + *cp++ - '0');
2028 * For RT-11, 1972 seems to be the pivot year
2035 lfp->l_ui = caltontp(&cal);
2042 * decodets - decode a timestamp into an l_fp format number, with
2043 * consideration of fuzzball formats.
2056 * If it starts with a 0x, decode as hex.
2058 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2059 return hextolfp(str+2, lfp);
2062 * If it starts with a '"', try it as an RT-11 date.
2067 while ('"' != *cp && '\0' != *cp &&
2068 b < COUNTOF(buf) - 1)
2071 return rtdatetolfp(buf, lfp);
2075 * Might still be hex. Check out the first character. Talk
2078 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2079 return hextolfp(str, lfp);
2082 * Try it as a decimal. If this fails, try as an unquoted
2083 * RT-11 date. This code should go away eventually.
2085 if (atolfp(str, lfp))
2088 return rtdatetolfp(str, lfp);
2093 * decodetime - decode a time value. It should be in milliseconds
2101 return mstolfp(str, lfp);
2106 * decodeint - decode an integer
2115 if (*(str+1) == 'x' || *(str+1) == 'X')
2116 return hextoint(str+2, (u_long *)val);
2117 return octtoint(str, (u_long *)val);
2119 return atoint(str, val);
2124 * decodeuint - decode an unsigned integer
2133 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2134 return (hextoint(str + 2, val));
2135 return (octtoint(str, val));
2137 return (atouint(str, val));
2142 * decodearr - decode an array of time values
2151 register char *cp, *bp;
2160 while (isspace((int)*cp))
2166 while (!isspace((int)*cp) && *cp != '\0')
2170 if (!decodetime(buf, lfp))
2180 * Finally, the built in command handlers
2184 * help - tell about commands, or details of a particular command
2192 struct xcmd *xcp = NULL; /* quiet warning */
2194 const char *list[100];
2200 if (pcmd->nargs == 0) {
2202 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2203 if (*(xcp->keyword) != '?' &&
2204 words < COUNTOF(list))
2205 list[words++] = xcp->keyword;
2207 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2208 if (words < COUNTOF(list))
2209 list[words++] = xcp->keyword;
2211 qsort((void *)list, words, sizeof(list[0]), helpsort);
2213 for (word = 0; word < words; word++) {
2214 length = strlen(list[word]);
2215 col = max(col, length);
2218 cols = SCREENWIDTH / ++col;
2219 rows = (words + cols - 1) / cols;
2221 fprintf(fp, "ntpq commands:\n");
2223 for (row = 0; row < rows; row++) {
2224 for (word = row; word < words; word += rows)
2225 fprintf(fp, "%-*.*s", (int)col,
2226 (int)col - 1, list[word]);
2230 cmd = pcmd->argval[0].string;
2231 words = findcmd(cmd, builtins, opcmds, &xcp);
2234 "Command `%s' is unknown\n", cmd);
2236 } else if (words >= 2) {
2238 "Command `%s' is ambiguous\n", cmd);
2241 fprintf(fp, "function: %s\n", xcp->comment);
2242 printusage(xcp, fp);
2248 * helpsort - do hostname qsort comparisons
2256 const char * const * name1 = t1;
2257 const char * const * name2 = t2;
2259 return strcmp(*name1, *name2);
2264 * printusage - print usage information for a command
2274 /* XXX: Do we need to warn about extra args here too? */
2276 (void) fprintf(fp, "usage: %s", xcp->keyword);
2277 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2278 if (xcp->arg[i] & OPT)
2279 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2281 (void) fprintf(fp, " %s", xcp->desc[i]);
2283 (void) fprintf(fp, "\n");
2288 * timeout - set time out time
2298 if (pcmd->nargs == 0) {
2299 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2300 (void) fprintf(fp, "primary timeout %d ms\n", val);
2302 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2303 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2310 * auth_delay - set delay for auth requests
2321 if (pcmd->nargs == 0) {
2322 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2323 (void) fprintf(fp, "delay %lu ms\n", val);
2325 if (pcmd->argval[0].ival < 0) {
2327 val = (u_long)(-pcmd->argval[0].ival);
2330 val = (u_long)pcmd->argval[0].ival;
2333 delay_time.l_ui = val / 1000;
2335 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2344 * host - set the host we are dealing with.
2354 if (pcmd->nargs == 0) {
2356 (void) fprintf(fp, "current host is %s\n",
2359 (void) fprintf(fp, "no current host\n");
2364 ai_fam_templ = ai_fam_default;
2365 if (pcmd->nargs == 2) {
2366 if (!strcmp("-4", pcmd->argval[i].string))
2367 ai_fam_templ = AF_INET;
2368 else if (!strcmp("-6", pcmd->argval[i].string))
2369 ai_fam_templ = AF_INET6;
2374 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2375 fprintf(fp, "current host set to %s\n", currenthost);
2379 fprintf(fp, "current host remains %s\n",
2382 fprintf(fp, "still no current host\n");
2388 * poll - do one (or more) polls of the host via NTP
2397 (void) fprintf(fp, "poll not implemented yet\n");
2402 * keyid - get a keyid to use for authenticating requests
2410 if (pcmd->nargs == 0) {
2411 if (info_auth_keyid == 0)
2412 (void) fprintf(fp, "no keyid defined\n");
2414 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2416 /* allow zero so that keyid can be cleared. */
2417 if(pcmd->argval[0].uval > NTP_MAXKEY)
2418 (void) fprintf(fp, "Invalid key identifier\n");
2419 info_auth_keyid = pcmd->argval[0].uval;
2424 * keytype - get type of key to use for authenticating requests
2432 const char * digest_name;
2437 fprintf(fp, "keytype is %s with %lu octet digests\n",
2438 keytype_name(info_auth_keytype),
2439 (u_long)info_auth_hashlen);
2443 digest_name = pcmd->argval[0].string;
2445 key_type = keytype_from_text(digest_name, &digest_len);
2448 fprintf(fp, "keytype is not valid. "
2450 "Type \"help keytype\" for the available digest types.\n");
2452 "Only \"md5\" is available.\n");
2457 info_auth_keytype = key_type;
2458 info_auth_hashlen = digest_len;
2463 * passwd - get an authentication key
2474 if (info_auth_keyid == 0) {
2475 info_auth_keyid = getkeyid("Keyid: ");
2476 if (info_auth_keyid == 0) {
2477 (void)fprintf(fp, "Keyid must be defined\n");
2481 if (pcmd->nargs >= 1)
2482 pass = pcmd->argval[0].string;
2484 pass = getpass_keytype(info_auth_keytype);
2485 if ('\0' == pass[0]) {
2486 fprintf(fp, "Password unchanged\n");
2490 authusekey(info_auth_keyid, info_auth_keytype,
2491 (const u_char *)pass);
2492 authtrust(info_auth_keyid, 1);
2497 * hostnames - set the showhostnames flag
2505 if (pcmd->nargs == 0) {
2507 (void) fprintf(fp, "hostnames being shown\n");
2509 (void) fprintf(fp, "hostnames not being shown\n");
2511 if (STREQ(pcmd->argval[0].string, "yes"))
2513 else if (STREQ(pcmd->argval[0].string, "no"))
2516 (void)fprintf(stderr, "What?\n");
2523 * setdebug - set/change debugging level
2531 if (pcmd->nargs == 0) {
2532 (void) fprintf(fp, "debug level is %d\n", debug);
2534 } else if (STREQ(pcmd->argval[0].string, "no")) {
2536 } else if (STREQ(pcmd->argval[0].string, "more")) {
2538 } else if (STREQ(pcmd->argval[0].string, "less")) {
2541 (void) fprintf(fp, "What?\n");
2544 (void) fprintf(fp, "debug level set to %d\n", debug);
2549 * quit - stop this nonsense
2559 closesocket(sockfd); /* cleanliness next to godliness */
2565 * version - print the current version number
2575 (void) fprintf(fp, "%s\n", Version);
2581 * raw - set raw mode output
2591 (void) fprintf(fp, "Output set to raw\n");
2596 * cooked - set cooked mode output
2606 (void) fprintf(fp, "Output set to cooked\n");
2612 * authenticate - always authenticate requests to this host
2620 if (pcmd->nargs == 0) {
2623 "authenticated requests being sent\n");
2626 "unauthenticated requests being sent\n");
2628 if (STREQ(pcmd->argval[0].string, "yes")) {
2630 } else if (STREQ(pcmd->argval[0].string, "no")) {
2633 (void)fprintf(stderr, "What?\n");
2639 * ntpversion - choose the NTP version to use
2647 if (pcmd->nargs == 0) {
2649 "NTP version being claimed is %d\n", pktversion);
2651 if (pcmd->argval[0].uval < NTP_OLDVERSION
2652 || pcmd->argval[0].uval > NTP_VERSION) {
2653 (void) fprintf(stderr, "versions %d to %d, please\n",
2654 NTP_OLDVERSION, NTP_VERSION);
2656 pktversion = (u_char) pcmd->argval[0].uval;
2662 static void __attribute__((__format__(__printf__, 1, 0)))
2663 vwarning(const char *fmt, va_list ap)
2666 (void) fprintf(stderr, "%s: ", progname);
2667 vfprintf(stderr, fmt, ap);
2668 (void) fprintf(stderr, ": %s", strerror(serrno));
2672 * warning - print a warning message
2674 static void __attribute__((__format__(__printf__, 1, 2)))
2688 * error - print a message and exit
2690 static void __attribute__((__format__(__printf__, 1, 2)))
2703 * getkeyid - prompt the user for a keyid to use
2707 const char *keyprompt
2717 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2719 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2720 #endif /* SYS_WINNT */
2723 setbuf(fi, (char *)NULL);
2724 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2725 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2726 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2728 pbuf[i++] = (char)c;
2733 return (u_long) atoi(pbuf);
2738 * atoascii - printable-ize possibly ascii data using the character
2739 * transformations cat -v uses.
2749 const u_char * pchIn;
2750 const u_char * pchInLimit;
2754 pchIn = (const u_char *)in;
2755 pchInLimit = pchIn + in_octets;
2756 pchOut = (u_char *)out;
2758 if (NULL == pchIn) {
2766 if (0 == --out_octets) { \
2773 for ( ; pchIn < pchInLimit; pchIn++) {
2784 ONEOUT((u_char)(c + '@'));
2785 } else if (0x7f == c) {
2798 * makeascii - print possibly ascii data using the character
2799 * transformations that cat -v uses.
2808 const u_char *data_u_char;
2812 data_u_char = (const u_char *)data;
2814 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2825 } else if (0x7f == c) {
2835 * asciize - same thing as makeascii except add a newline
2844 makeascii(length, data, fp);
2850 * truncate string to fit clipping excess at end.
2851 * "too long" -> "too l"
2852 * Used for hostnames.
2865 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2867 memcpy(out, src, width);
2878 * truncate string to fit by preserving right side and using '_' to hint
2879 * "too long" -> "_long"
2880 * Used for local IPv6 addresses, where low bits differentiate.
2893 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2896 memcpy(&out[1], &src[sl + 1 - width], width);
2906 * Some circular buffer space
2911 char circ_buf[NUMCB][CBLEN];
2915 * nextvar - find the next variable in the buffer
2930 static char name[MAXVARLEN];
2931 static char value[MAXVALLEN];
2934 cpend = cp + *datalen;
2937 * Space past commas and white space
2939 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
2945 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
2946 * over any white space and terminate it.
2948 srclen = strcspn(cp, ",=\r\n");
2949 srclen = min(srclen, (size_t)(cpend - cp));
2951 while (len > 0 && isspace((unsigned char)cp[len - 1]))
2954 memcpy(name, cp, len);
2960 * Check if we hit the end of the buffer or a ','. If so we are done.
2962 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
2966 *datalen = cpend - cp;
2972 * So far, so good. Copy out the value
2974 cp++; /* past '=' */
2975 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
2981 } while (np < cpend && '"' != *np);
2982 if (np < cpend && '"' == *np)
2985 while (np < cpend && ',' != *np && '\r' != *np)
2989 if (np > cpend || len >= sizeof(value) ||
2990 (np < cpend && ',' != *np && '\r' != *np))
2992 memcpy(value, cp, len);
2994 * Trim off any trailing whitespace
2996 while (len > 0 && isspace((unsigned char)value[len - 1]))
3001 * Return this. All done.
3003 if (np < cpend && ',' == *np)
3006 *datalen = cpend - np;
3013 varfmt(const char * varname)
3017 for (n = 0; n < COUNTOF(cookedvars); n++)
3018 if (!strcmp(varname, cookedvars[n].varname))
3019 return cookedvars[n].fmt;
3026 * printvars - print variables returned in response packet
3039 rawprint(sttype, length, data, status, quiet, fp);
3041 cookedprint(sttype, length, data, status, quiet, fp);
3046 * rawprint - do a printout of the data in raw mode
3062 * Essentially print the data as is. We reformat unprintables, though.
3065 cpend = data + length;
3068 (void) fprintf(fp, "status=0x%04x,\n", status);
3070 while (cp < cpend) {
3073 * If this is a \r and the next character is a
3074 * \n, supress this, else pretty print it. Otherwise
3075 * just output the character.
3077 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3078 makeascii(1, cp, fp);
3079 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3082 makeascii(1, cp, fp);
3089 * Global data used by the cooked output routines
3091 int out_chars; /* number of characters output */
3092 int out_linecount; /* number of characters output on this line */
3096 * startoutput - get ready to do cooked output
3107 * output - output a variable=value combination
3118 /* strlen of "name=value" */
3119 len = strlen(name) + 1 + strlen(value);
3121 if (out_chars != 0) {
3123 if ((out_linecount + len + 2) > MAXOUTLINE) {
3136 out_linecount += len;
3141 * endoutput - terminate a block of cooked output
3154 * outputarr - output an array of values
3172 * Hack to align delay and offset values
3174 for (i = (int)strlen(name); i < 11; i++)
3177 for (i = narr; i > 0; i--) {
3180 cp = lfptoms(lfp, 2);
3195 output(fp, name, buf);
3203 register char *cp, *s;
3206 register const char *sep;
3210 s = cp = circ_buf[nextcb];
3211 if (++nextcb >= NUMCB)
3213 cb = sizeof(circ_buf[0]);
3215 snprintf(cp, cb, "%02lx", val);
3219 strlcat(cp, " ok", cb);
3227 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3229 snprintf(cp, cb, "%s%s", sep,
3245 * cookedprint - output variables in cooked mode
3268 char bn[2 * MAXVARLEN];
3269 char bv[2 * MAXVALLEN];
3271 UNUSED_ARG(datatype);
3274 fprintf(fp, "status=%04x %s,\n", status,
3275 statustoa(datatype, status));
3278 while (nextvar(&length, &data, &name, &value)) {
3288 if (!decodets(value, &lfp))
3291 output(fp, name, prettydate(&lfp));
3294 case HA: /* fallthru */
3296 if (!decodenetnum(value, &hval)) {
3298 } else if (fmt == HA){
3299 output(fp, name, nntohost(&hval));
3301 output(fp, name, stoa(&hval));
3306 if (decodenetnum(value, &hval)) {
3307 if (ISREFCLOCKADR(&hval))
3311 output(fp, name, stoa(&hval));
3312 } else if (strlen(value) <= 4) {
3313 output(fp, name, value);
3320 if (!decodeuint(value, &uval) || uval > 3) {
3330 output(fp, name, b);
3335 if (!decodeuint(value, &uval)) {
3338 snprintf(b, sizeof(b), "%03lo", uval);
3339 output(fp, name, b);
3344 if (!decodearr(value, &narr, lfparr))
3347 outputarr(fp, name, narr, lfparr);
3351 if (!decodeuint(value, &uval))
3354 output(fp, name, tstflags(uval));
3358 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3364 if (output_raw != 0) {
3365 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3366 atoascii(value, MAXVALLEN, bv, sizeof(bv));
3367 if (output_raw != '*') {
3369 bv[len] = output_raw;
3380 * sortassoc - sort associations in the cache into ascending order
3386 qsort(assoc_cache, (size_t)numassoc,
3387 sizeof(assoc_cache[0]), &assoccmp);
3392 * assoccmp - compare two associations
3400 const struct association *ass1 = t1;
3401 const struct association *ass2 = t2;
3403 if (ass1->assid < ass2->assid)
3405 if (ass1->assid > ass2->assid)
3412 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3414 * The strategy is to add an assumed 4k page size at a time, leaving
3415 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3418 grow_assoc_cache(void)
3420 static size_t prior_sz;
3423 new_sz = prior_sz + 4 * 1024;
3424 if (0 == prior_sz) {
3425 new_sz -= 4 * sizeof(void *);
3427 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3429 assoc_cache_slots = new_sz / sizeof(assoc_cache[0]);
3434 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3436 * By default, autoopts loses the relative order of -c and -p options
3437 * on the command line. This routine replaces the default handler for
3438 * those routines and builds a list of commands to execute preserving
3442 ntpq_custom_opt_handler(
3447 switch (pOptDesc->optValue) {
3451 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3452 pOptDesc->optValue, pOptDesc->optValue);
3456 ADDCMD(pOptDesc->pzLastArg);
3465 * Obtain list of digest names
3469 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3475 #define K_PER_LINE 8
3476 #define K_NL_PFX_STR "\n "
3477 #define K_DELIM_STR ", "
3478 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3481 const char *name, *cp, **seen;
3482 struct hstate *hstate = arg;
3485 u_char digest[EVP_MAX_MD_SIZE];
3488 return; /* Ignore aliases */
3490 name = EVP_MD_name(m);
3492 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3494 for( cp = name; *cp; cp++ ) {
3498 len = (cp - name) + 1;
3500 /* There are duplicates. Discard if name has been seen. */
3502 for (seen = hstate->seen; *seen; seen++)
3503 if (!strcmp(*seen, name))
3505 n = (seen - hstate->seen) + 2;
3506 hstate->seen = realloc(hstate->seen, n * sizeof(*seen));
3507 hstate->seen[n-2] = name;
3508 hstate->seen[n-1] = NULL;
3510 /* Discard MACs that NTP won't accept.
3511 * Keep this consistent with keytype_from_text() in ssl_init.c.
3514 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3515 EVP_DigestFinal(&ctx, digest, &digest_len);
3516 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3519 if (hstate->list != NULL)
3520 len += strlen(hstate->list);
3521 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3523 if (hstate->list == NULL) {
3524 hstate->list = (char *)malloc(len);
3525 hstate->list[0] = '\0';
3527 hstate->list = (char *)realloc(hstate->list, len);
3529 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3530 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3532 if (hstate->idx >= K_PER_LINE)
3540 static char *list_digest_names(void)
3545 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3546 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3548 hstate.seen = (const char **)calloc(1, sizeof( const char * ));
3551 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3555 list = (char *)malloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3556 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3559 list = (char *)malloc(sizeof("md5"));
3560 strcpy(list, "md5");