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"
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
70 * How should we display the refid?
71 * REFID_HASH, REFID_IPV4
78 s_char sys_precision; /* local clock precision (log2 s) */
81 * Keyid used for authenticated requests. Obtained on the fly.
83 u_long info_auth_keyid = 0;
85 static int info_auth_keytype = NID_md5; /* MD5 */
86 static size_t info_auth_hashlen = 16; /* MD5 */
87 u_long current_time; /* needed by authkeys; not used */
90 * Flag which indicates we should always send authenticated requests
95 * Flag which indicates raw mode output.
100 * Packet version number we use
102 u_char pktversion = NTP_OLDVERSION + 1;
105 * Don't jump if no set jmp.
107 volatile int jump = 0;
113 #define HA 1 /* host address */
114 #define NA 2 /* network address */
115 #define LP 3 /* leap (print in binary) */
116 #define RF 4 /* refid (sometimes string, sometimes not) */
117 #define AR 5 /* array of times */
118 #define FX 6 /* test flags */
119 #define TS 7 /* l_fp timestamp in hex */
120 #define OC 8 /* integer, print in octal */
121 #define EOV 255 /* end of table */
124 * For the most part ntpq simply displays what ntpd provides in the
125 * mostly plain-text mode 6 responses. A few variable names are by
126 * default "cooked" to provide more human-friendly output.
128 const var_format cookedvars[] = {
139 { "peeradr", HA }, /* compat with others */
142 { "filtoffset", AR },
144 { "filterror", AR }, /* compat with others */
152 static const char *tstflagnames[] = {
153 "pkt_dup", /* TEST1 */
154 "pkt_bogus", /* TEST2 */
155 "pkt_unsync", /* TEST3 */
156 "pkt_denied", /* TEST4 */
157 "pkt_auth", /* TEST5 */
158 "pkt_stratum", /* TEST6 */
159 "pkt_header", /* TEST7 */
160 "pkt_autokey", /* TEST8 */
161 "pkt_crypto", /* TEST9 */
162 "peer_stratum", /* TEST10 */
163 "peer_dist", /* TEST11 */
164 "peer_loop", /* TEST12 */
165 "peer_unreach" /* TEST13 */
169 int ntpqmain (int, char **);
171 * Built in command handler declarations
173 static int openhost (const char *, int);
174 static void dump_hex_printable(const void *, size_t);
175 static int sendpkt (void *, size_t);
176 static int getresponse (int, int, u_short *, size_t *, const char **, int);
177 static int sendrequest (int, associd_t, int, size_t, const char *);
178 static char * tstflags (u_long);
180 static void getcmds (void);
182 static int abortcmd (void);
183 #endif /* SYS_WINNT */
184 static void docmd (const char *);
185 static void tokenize (const char *, char **, int *);
186 static int getarg (const char *, int, arg_v *);
187 #endif /* BUILD_AS_LIB */
188 static int findcmd (const char *, struct xcmd *,
189 struct xcmd *, struct xcmd **);
190 static int rtdatetolfp (char *, l_fp *);
191 static int decodearr (char *, int *, l_fp *);
192 static void help (struct parse *, FILE *);
193 static int helpsort (const void *, const void *);
194 static void printusage (struct xcmd *, FILE *);
195 static void timeout (struct parse *, FILE *);
196 static void auth_delay (struct parse *, FILE *);
197 static void host (struct parse *, FILE *);
198 static void ntp_poll (struct parse *, FILE *);
199 static void keyid (struct parse *, FILE *);
200 static void keytype (struct parse *, FILE *);
201 static void passwd (struct parse *, FILE *);
202 static void hostnames (struct parse *, FILE *);
203 static void setdebug (struct parse *, FILE *);
204 static void quit (struct parse *, FILE *);
205 static void showdrefid (struct parse *, FILE *);
206 static void version (struct parse *, FILE *);
207 static void raw (struct parse *, FILE *);
208 static void cooked (struct parse *, FILE *);
209 static void authenticate (struct parse *, FILE *);
210 static void ntpversion (struct parse *, FILE *);
211 static void warning (const char *, ...)
212 __attribute__((__format__(__printf__, 1, 2)));
213 static void error (const char *, ...)
214 __attribute__((__format__(__printf__, 1, 2)));
215 static u_long getkeyid (const char *);
216 static void atoascii (const char *, size_t, char *, size_t);
217 static void cookedprint (int, size_t, const char *, int, int, FILE *);
218 static void rawprint (int, size_t, const char *, int, int, FILE *);
219 static void startoutput (void);
220 static void output (FILE *, const char *, const char *);
221 static void endoutput (FILE *);
222 static void outputarr (FILE *, char *, int, l_fp *);
223 static int assoccmp (const void *, const void *);
224 static void on_ctrlc (void);
225 u_short varfmt (const char *);
226 static int my_easprintf (char**, const char *, ...) NTP_PRINTF(2, 3);
227 void ntpq_custom_opt_handler (tOptions *, tOptDesc *);
230 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
231 static void list_md_fn(const EVP_MD *m, const char *from,
232 const char *to, void *arg );
235 static char *list_digest_names(void);
238 * Built-in commands we understand
240 struct xcmd builtins[] = {
241 { "?", help, { OPT|NTP_STR, NO, NO, NO },
242 { "command", "", "", "" },
243 "tell the use and syntax of commands" },
244 { "help", help, { OPT|NTP_STR, NO, NO, NO },
245 { "command", "", "", "" },
246 "tell the use and syntax of commands" },
247 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
248 { "msec", "", "", "" },
249 "set the primary receive time out" },
250 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
251 { "msec", "", "", "" },
252 "set the delay added to encryption time stamps" },
253 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
254 { "-4|-6", "hostname", "", "" },
255 "specify the host whose NTP server we talk to" },
256 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
257 { "n", "verbose", "", "" },
258 "poll an NTP server in client mode `n' times" },
259 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
261 "specify a password to use for authenticated requests"},
262 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
263 { "yes|no", "", "", "" },
264 "specify whether hostnames or net numbers are printed"},
265 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
266 { "no|more|less", "", "", "" },
267 "set/change debugging level" },
268 { "quit", quit, { NO, NO, NO, NO },
271 { "exit", quit, { NO, NO, NO, NO },
274 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
275 { "key#", "", "", "" },
276 "set keyid to use for authenticated requests" },
277 { "drefid", showdrefid, { OPT|NTP_STR, NO, NO, NO },
278 { "hash|ipv4", "", "", "" },
279 "display refid's as IPv4 or hash" },
280 { "version", version, { NO, NO, NO, NO },
282 "print version number" },
283 { "raw", raw, { NO, NO, NO, NO },
285 "do raw mode variable output" },
286 { "cooked", cooked, { NO, NO, NO, NO },
288 "do cooked mode variable output" },
289 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
290 { "yes|no", "", "", "" },
291 "always authenticate requests to this server" },
292 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
293 { "version number", "", "", "" },
294 "set the NTP version number to use for requests" },
295 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
296 { "key type %s", "", "", "" },
298 { 0, 0, { NO, NO, NO, NO },
299 { "", "", "", "" }, "" }
304 * Default values we use.
306 #define DEFHOST "localhost" /* default host name */
307 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
308 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
310 * Requests are automatically retried once, so total timeout with no
311 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
312 * extreme, a request eliciting 32 packets of responses each for some
313 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
314 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
315 * 93 seconds to fail each of two times, or 186 seconds.
316 * Some commands involve a series of requests, such as "peers" and
317 * "mrulist", so the cumulative timeouts are even longer for those.
319 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
320 #define LENHOSTNAME 256 /* host name is 256 characters long */
321 #define MAXCMDS 100 /* maximum commands on cmd line */
322 #define MAXHOSTS 200 /* maximum hosts on cmd line */
323 #define MAXLINE 512 /* maximum line length */
324 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
325 #define MAXVARLEN 256 /* maximum length of a variable name */
326 #define MAXVALLEN 2048 /* maximum length of a variable value */
327 #define MAXOUTLINE 72 /* maximum length of an output line */
328 #define SCREENWIDTH 76 /* nominal screen width in columns */
331 * Some variables used and manipulated locally
333 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
334 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
335 l_fp delay_time; /* delay time */
336 char currenthost[LENHOSTNAME]; /* current host name */
337 int currenthostisnum; /* is prior text from IP? */
338 struct sockaddr_in hostaddr; /* host address */
339 int showhostnames = 1; /* show host names by default */
340 int wideremote = 0; /* show wide remote names? */
342 int ai_fam_templ; /* address family */
343 int ai_fam_default; /* default address family */
344 SOCKET sockfd; /* fd socket is opened on */
345 int havehost = 0; /* set to 1 when host open */
347 struct servent *server_entry = NULL; /* server entry for ntp */
351 * Sequence number used for requests. It is incremented before
357 * Holds data returned from queries. Declare buffer long to be sure of
360 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
361 long pktdata[DATASIZE/sizeof(long)];
364 * assoc_cache[] is a dynamic array which allows references to
365 * associations using &1 ... &N for n associations, avoiding manual
366 * lookup of the current association IDs for a given ntpd. It also
367 * caches the status word for each association, retrieved incidentally.
369 struct association * assoc_cache;
370 u_int assoc_cache_slots;/* count of allocated array entries */
371 u_int numassoc; /* number of cached associations */
374 * For commands typed on the command line (with the -c option)
377 const char *ccmds[MAXCMDS];
378 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
381 * When multiple hosts are specified.
386 chost chosts[MAXHOSTS];
387 #define ADDHOST(cp) \
389 if (numhosts < MAXHOSTS) { \
390 chosts[numhosts].name = (cp); \
391 chosts[numhosts].fam = ai_fam_templ; \
397 * Macro definitions we use
399 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
400 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
401 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
404 * Jump buffer for longjumping back to the command level
406 jmp_buf interrupt_buf;
409 * Points at file being currently printed into
411 FILE *current_output;
414 * Command table imported from ntpdc_ops.c
416 extern struct xcmd opcmds[];
418 char const *progname;
420 #ifdef NO_MAIN_ALLOWED
422 CALL(ntpq,"ntpq",ntpqmain);
424 void clear_globals(void)
426 extern int ntp_optind;
427 showhostnames = 0; /* don'tshow host names by default */
429 server_entry = NULL; /* server entry for ntp */
430 havehost = 0; /* set to 1 when host open */
431 numassoc = 0; /* number of cached associations */
435 #endif /* !BUILD_AS_LIB */
436 #endif /* NO_MAIN_ALLOWED */
439 * main - parse arguments and handle options
441 #ifndef NO_MAIN_ALLOWED
448 return ntpqmain(argc, argv);
465 taskPrioritySet(taskIdSelf(), 100 );
469 delay_time.l_uf = DEFDELAY;
471 init_lib(); /* sets up ipv4_works, ipv6_works */
475 /* Check to see if we have IPv6. Otherwise default to IPv4 */
477 ai_fam_default = AF_INET;
479 /* Fixup keytype's help based on available digest names */
485 list = list_digest_names();
486 for (icmd = 0; icmd < sizeof(builtins)/sizeof(builtins[0]); icmd++) {
487 if (strcmp("keytype", builtins[icmd].keyword) == 0)
492 /* This should only "trip" if "keytype" is removed from builtins */
493 INSIST(icmd < sizeof(builtins)/sizeof(builtins[0]));
496 builtins[icmd].desc[0] = "digest-name";
498 "set key type to use for authenticated requests, one of:%s",
501 builtins[icmd].desc[0] = "md5";
503 "set key type to use for authenticated requests (%s)",
506 builtins[icmd].comment = msg;
513 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
519 * Process options other than -c and -p, which are specially
520 * handled by ntpq_custom_opt_handler().
523 debug = OPT_VALUE_SET_DEBUG_LEVEL;
526 ai_fam_templ = AF_INET;
527 else if (HAVE_OPT(IPV6))
528 ai_fam_templ = AF_INET6;
530 ai_fam_templ = ai_fam_default;
532 if (HAVE_OPT(INTERACTIVE))
535 if (HAVE_OPT(NUMERIC))
541 old_rv = HAVE_OPT(OLD_RV);
543 drefid = OPT_VALUE_REFID;
548 for (ihost = 0; ihost < (u_int)argc; ihost++) {
549 if ('-' == *argv[ihost]) {
551 // If I really cared I'd also check:
552 // 0 == argv[ihost][2]
554 // and there are other cases as well...
556 if ('4' == argv[ihost][1]) {
557 ai_fam_templ = AF_INET;
559 } else if ('6' == argv[ihost][1]) {
560 ai_fam_templ = AF_INET6;
563 // XXX Throw a usage error
566 ADDHOST(argv[ihost]);
570 if (numcmds == 0 && interactive == 0
571 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
575 set_ctrl_c_hook(on_ctrlc);
576 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
578 push_ctrl_c_handler(abortcmd);
579 #endif /* SYS_WINNT */
582 (void) openhost(chosts[0].name, chosts[0].fam);
585 for (ihost = 0; ihost < numhosts; ihost++) {
586 if (openhost(chosts[ihost].name, chosts[ihost].fam))
587 for (icmd = 0; icmd < numcmds; icmd++)
593 #endif /* SYS_WINNT */
596 #endif /* !BUILD_AS_LIB */
599 * openhost - open a socket to a host
607 const char svc[] = "ntp";
608 char temphost[LENHOSTNAME];
610 struct addrinfo hints, *ai;
613 register const char *cp;
614 char name[LENHOSTNAME];
617 * We need to get by the [] if they were entered
624 for (i = 0; *cp && *cp != ']'; cp++, i++)
635 * First try to resolve it as an ip address and if that fails,
636 * do a fullblown (dns) lookup. That way we only use the dns
637 * when it is needed and work around some implementations that
638 * will return an "IPv4-mapped IPv6 address" address if you
639 * give it an IPv4 address to lookup.
642 hints.ai_family = fam;
643 hints.ai_protocol = IPPROTO_UDP;
644 hints.ai_socktype = SOCK_DGRAM;
645 hints.ai_flags = Z_AI_NUMERICHOST;
648 a_info = getaddrinfo(hname, svc, &hints, &ai);
649 if (a_info == EAI_NONAME
651 || a_info == EAI_NODATA
654 hints.ai_flags = AI_CANONNAME;
656 hints.ai_flags |= AI_ADDRCONFIG;
658 a_info = getaddrinfo(hname, svc, &hints, &ai);
661 /* Some older implementations don't like AI_ADDRCONFIG. */
662 if (a_info == EAI_BADFLAGS) {
663 hints.ai_flags &= ~AI_ADDRCONFIG;
664 a_info = getaddrinfo(hname, svc, &hints, &ai);
668 fprintf(stderr, "%s\n", gai_strerror(a_info));
674 octets = min(sizeof(addr), ai->ai_addrlen);
675 memcpy(&addr, ai->ai_addr, octets);
677 if (ai->ai_canonname == NULL) {
678 strlcpy(temphost, stoa(&addr), sizeof(temphost));
679 currenthostisnum = TRUE;
681 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
682 currenthostisnum = FALSE;
686 printf("Opening host %s (%s)\n",
688 (ai->ai_family == AF_INET)
690 : (ai->ai_family == AF_INET6)
697 printf("Closing old host %s\n", currenthost);
701 strlcpy(currenthost, temphost, sizeof(currenthost));
703 /* port maps to the same location in both families */
704 s_port = NSRCPORT(&addr);
706 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
707 if (ai->ai_family == AF_INET)
708 *(struct sockaddr_in *)&hostaddr=
709 *((struct sockaddr_in *)ai->ai_addr);
711 *(struct sockaddr_in6 *)&hostaddr=
712 *((struct sockaddr_in6 *)ai->ai_addr);
713 #endif /* SYS_VXWORKS */
717 int optionValue = SO_SYNCHRONOUS_NONALERT;
720 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
721 (char *)&optionValue, sizeof(optionValue));
724 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
730 #endif /* SYS_WINNT */
732 sockfd = socket(ai->ai_family, ai->ai_socktype,
734 if (sockfd == INVALID_SOCKET) {
741 #ifdef NEED_RCVBUF_SLOP
743 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
744 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
745 &rbufsize, sizeof(int)) == -1)
753 (connect(sockfd, (struct sockaddr *)&hostaddr,
754 sizeof(hostaddr)) == -1)
756 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
757 ai->ai_addrlen) == -1)
758 #endif /* SYS_VXWORKS */
779 const char * rowstart;
787 rowlen = min(16, len);
788 for (idx = 0; idx < rowlen; idx++) {
790 printf("%02x ", uch);
792 for ( ; idx < 16 ; idx++)
795 for (idx = 0; idx < rowlen; idx++) {
797 printf("%c", (isprint(uch))
807 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
809 * sendpkt - send a packet to the remote host
818 printf("Sending %zu octets\n", xdatalen);
820 if (send(sockfd, xdata, xdatalen, 0) == -1) {
821 warning("write to %s failed", currenthost);
826 printf("Request packet:\n");
827 dump_hex_printable(xdata, xdatalen);
833 * getresponse - get a (series of) response packet(s) and return the data
845 struct ntp_control rpkt;
846 struct sock_timeval tvo;
847 u_short offsets[MAXFRAGS+1];
848 u_short counts[MAXFRAGS+1];
859 /* absolute timeout checks. Not 'time_t' by intention! */
860 uint32_t tobase; /* base value for timeout */
861 uint32_t tospan; /* timeout span (max delay) */
862 uint32_t todiff; /* current delay */
865 * This is pretty tricky. We may get between 1 and MAXFRAG packets
866 * back in response to the request. We peel the data out of
867 * each packet and collect it in one long block. When the last
868 * packet in the sequence is received we'll know how much data we
869 * should have had. Note we use one long time out, should reconsider.
874 *rdata = (char *)pktdata;
879 tobase = (uint32_t)time(NULL);
884 * Loop until we have an error or a complete response. Nearly all
885 * code paths to loop again use continue.
893 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
895 FD_SET(sockfd, &fds);
896 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
898 #if !defined(SYS_WINNT) && defined(EINTR)
899 /* Windows does not know about EINTR (until very
900 * recently) and the handling of console events
901 * is *very* different from POSIX/UNIX signal
904 * Under non-windows targets we map EINTR as
905 * 'last packet was received' and try to exit
906 * the receive sequence.
908 if (errno == EINTR) {
913 warning("select fails");
918 * Check if this is already too late. Trash the data and
919 * fake a timeout if this is so.
921 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
922 if ((n > 0) && (todiff > tospan)) {
923 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
924 n = 0; /* faked timeout return from 'select()'*/
929 * Timed out. Return what we have
934 "%s: timed out, nothing received\n",
940 "%s: timed out with incomplete data\n",
944 "ERR_INCOMPLETE: Received fragments:\n");
945 for (f = 0; f < numfrags; f++)
947 "%2u: %5d %5d\t%3d octets\n",
948 (u_int)f, offsets[f],
953 "last fragment %sreceived\n",
958 return ERR_INCOMPLETE;
961 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
968 printf("Response packet:\n");
969 dump_hex_printable(&rpkt, n);
973 * Check for format errors. Bug proofing.
975 if (n < (int)CTL_HEADER_LEN) {
977 printf("Short (%d byte) packet received\n", n);
980 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
981 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
983 printf("Packet received with version %d\n",
984 PKT_VERSION(rpkt.li_vn_mode));
987 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
989 printf("Packet received with mode %d\n",
990 PKT_MODE(rpkt.li_vn_mode));
993 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
995 printf("Received request packet, wanted response\n");
1000 * Check opcode and sequence number for a match.
1001 * Could be old data getting to us.
1003 if (ntohs(rpkt.sequence) != sequence) {
1005 printf("Received sequnce number %d, wanted %d\n",
1006 ntohs(rpkt.sequence), sequence);
1009 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1012 "Received opcode %d, wanted %d (sequence number okay)\n",
1013 CTL_OP(rpkt.r_m_e_op), opcode);
1018 * Check the error code. If non-zero, return it.
1020 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1021 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1022 if (CTL_ISMORE(rpkt.r_m_e_op))
1023 TRACE(1, ("Error code %d received on not-final packet\n",
1025 if (errcode == CERR_UNSPEC)
1031 * Check the association ID to make sure it matches what
1034 if (ntohs(rpkt.associd) != associd) {
1035 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1036 ntohs(rpkt.associd), associd));
1038 * Hack for silly fuzzballs which, at the time of writing,
1039 * return an assID of sys.peer when queried for system variables.
1047 * Collect offset and count. Make sure they make sense.
1049 offset = ntohs(rpkt.offset);
1050 count = ntohs(rpkt.count);
1053 * validate received payload size is padded to next 32-bit
1054 * boundary and no smaller than claimed by rpkt.count
1057 TRACE(1, ("Response packet not padded, size = %d\n",
1062 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1064 if (n < shouldbesize) {
1065 printf("Response packet claims %u octets payload, above %ld received\n",
1066 count, (long)n - CTL_HEADER_LEN);
1067 return ERR_INCOMPLETE;
1070 if (debug >= 3 && shouldbesize > n) {
1076 * Usually we ignore authentication, but for debugging purposes
1079 /* round to 8 octet boundary */
1080 shouldbesize = (shouldbesize + 7) & ~7;
1082 maclen = n - shouldbesize;
1083 if (maclen >= (int)MIN_MAC_LEN) {
1085 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1086 n, shouldbesize, maclen);
1087 lpkt = (u_int32 *)&rpkt;
1088 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1089 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1090 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1091 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1092 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1093 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1094 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1095 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1096 printf("Authenticated with keyid %lu\n", (u_long)key);
1097 if (key != 0 && key != info_auth_keyid) {
1098 printf("We don't know that key\n");
1100 if (authdecrypt(key, (u_int32 *)&rpkt,
1101 n - maclen, maclen)) {
1102 printf("Auth okay!\n");
1104 printf("Auth failed!\n");
1110 TRACE(2, ("Got packet, size = %d\n", n));
1111 if (count > (n - CTL_HEADER_LEN)) {
1112 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1113 count, (long)n - CTL_HEADER_LEN));
1116 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1117 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1120 if (offset + count > sizeof(pktdata)) {
1121 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1125 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1126 TRACE(1, ("Received second last fragment packet\n"));
1131 * So far, so good. Record this fragment, making sure it doesn't
1134 TRACE(2, ("Packet okay\n"));
1136 if (numfrags > (MAXFRAGS - 1)) {
1137 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1143 * Find the position for the fragment relative to any
1144 * previously received.
1147 f < numfrags && offsets[f] < offset;
1152 if (f < numfrags && offset == offsets[f]) {
1153 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1154 count, offset, counts[f], offsets[f]));
1158 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1159 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1160 offset, counts[f-1], offsets[f-1]));
1164 if (f < numfrags && (offset + count) > offsets[f]) {
1165 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1166 count, offset, offsets[f]));
1170 for (ff = numfrags; ff > f; ff--) {
1171 offsets[ff] = offsets[ff-1];
1172 counts[ff] = counts[ff-1];
1174 offsets[f] = offset;
1179 * Got that stuffed in right. Figure out if this was the last.
1180 * Record status info out of the last packet.
1182 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1185 *rstatus = ntohs(rpkt.status);
1189 * Copy the data into the data buffer, and bump the
1190 * timout base in case we need more.
1192 memcpy((char *)pktdata + offset, &rpkt.u, count);
1193 tobase = (uint32_t)time(NULL);
1196 * If we've seen the last fragment, look for holes in the sequence.
1197 * If there aren't any, we're done.
1200 if (seenlastfrag && offsets[0] == 0) {
1201 for (f = 1; f < numfrags; f++)
1202 if (offsets[f-1] + counts[f-1] !=
1205 if (f == numfrags) {
1206 *rsize = offsets[f-1] + counts[f-1];
1207 TRACE(1, ("%lu packets reassembled into response\n",
1212 } /* giant for (;;) collecting response packets */
1213 } /* getresponse() */
1217 * sendrequest - format and send a request packet
1228 struct ntp_control qpkt;
1235 * Check to make sure the data will fit in one packet
1237 if (qsize > CTL_MAX_DATA_LEN) {
1239 "***Internal error! qsize (%zu) too large\n",
1245 * Fill in the packet
1247 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1248 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1249 qpkt.sequence = htons(sequence);
1251 qpkt.associd = htons((u_short)associd);
1253 qpkt.count = htons((u_short)qsize);
1255 pktsize = CTL_HEADER_LEN;
1258 * If we have data, copy and pad it out to a 32-bit boundary.
1261 memcpy(&qpkt.u, qdata, (size_t)qsize);
1263 while (pktsize & (sizeof(u_int32) - 1)) {
1264 qpkt.u.data[qsize++] = 0;
1270 * If it isn't authenticated we can just send it. Otherwise
1271 * we're going to have to think about it a little.
1273 if (!auth && !always_auth) {
1274 return sendpkt(&qpkt, pktsize);
1278 * Pad out packet to a multiple of 8 octets to be sure
1279 * receiver can handle it.
1281 while (pktsize & 7) {
1282 qpkt.u.data[qsize++] = 0;
1287 * Get the keyid and the password if we don't have one.
1289 if (info_auth_keyid == 0) {
1290 key_id = getkeyid("Keyid: ");
1291 if (key_id == 0 || key_id > NTP_MAXKEY) {
1293 "Invalid key identifier\n");
1296 info_auth_keyid = key_id;
1298 if (!authistrusted(info_auth_keyid)) {
1299 pass = getpass_keytype(info_auth_keytype);
1300 if ('\0' == pass[0]) {
1301 fprintf(stderr, "Invalid password\n");
1304 authusekey(info_auth_keyid, info_auth_keytype,
1306 authtrust(info_auth_keyid, 1);
1310 * Do the encryption.
1312 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1314 fprintf(stderr, "Key not found\n");
1316 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1318 "%zu octet MAC, %zu expected with %zu octet digest\n",
1319 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1324 return sendpkt((char *)&qpkt, pktsize + maclen);
1329 * show_error_msg - display the error text for a mode 6 error response.
1338 fprintf(stderr, "server=%s ", currenthost);
1344 "***Server reports a bad format request packet\n");
1347 case CERR_PERMISSION:
1349 "***Server disallowed request (authentication?)\n");
1354 "***Server reports a bad opcode in request\n");
1359 "***Association ID %d unknown to server\n",
1363 case CERR_UNKNOWNVAR:
1365 "***A request variable unknown to the server\n");
1370 "***Server indicates a request variable was bad\n");
1375 "***Server returned an unspecified error\n");
1379 fprintf(stderr, "***Request timed out\n");
1382 case ERR_INCOMPLETE:
1384 "***Response from server was incomplete\n");
1389 "***Buffer size exceeded for returned data\n");
1394 "***Server returns unknown error code %d\n",
1400 * doquery - send a request and process the response, displaying
1401 * error messages for any error responses.
1415 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1416 rsize, rdata, FALSE);
1421 * doqueryex - send a request and process the response, optionally
1422 * displaying error messages for any error responses.
1441 * Check to make sure host is open
1444 fprintf(stderr, "***No host open, use `host' command\n");
1455 res = sendrequest(opcode, associd, auth, qsize, qdata);
1460 * Get the response. If we got a standard error, print a message
1462 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1465 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1466 if (res == ERR_INCOMPLETE) {
1468 * better bump the sequence so we don't
1469 * get confused about differing fragments.
1477 show_error_msg(res, associd);
1484 #ifndef BUILD_AS_LIB
1486 * getcmds - read commands from the standard input and execute them
1494 ntp_readline_init(interactive ? prompt : NULL);
1497 line = ntp_readline(&count);
1504 ntp_readline_uninit();
1506 #endif /* !BUILD_AS_LIB */
1509 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1511 * abortcmd - catch interrupts and abort the current command
1516 if (current_output == stdout)
1517 (void) fflush(stdout);
1519 (void) fflush(stderr);
1522 longjmp(interrupt_buf, 1);
1526 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1529 #ifndef BUILD_AS_LIB
1531 * docmd - decode the command line and execute a command
1538 char *tokens[1+MAXARGS+2];
1545 * Tokenize the command line. If nothing on it, return.
1547 tokenize(cmdline, tokens, &ntok);
1552 * Find the appropriate command description.
1554 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1556 (void) fprintf(stderr, "***Command `%s' unknown\n",
1559 } else if (i >= 2) {
1560 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1565 /* Warn about ignored extra args */
1566 for (i = MAXARGS + 1; i < ntok ; ++i) {
1567 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1571 * Save the keyword, then walk through the arguments, interpreting
1574 pcmd.keyword = tokens[0];
1576 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1577 if ((i+1) >= ntok) {
1578 if (!(xcmd->arg[i] & OPT)) {
1579 printusage(xcmd, stderr);
1584 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1586 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1592 if (i < ntok && *tokens[i] == '>') {
1595 if (*(tokens[i]+1) != '\0')
1596 fname = tokens[i]+1;
1597 else if ((i+1) < ntok)
1598 fname = tokens[i+1];
1600 (void) fprintf(stderr, "***No file for redirect\n");
1604 current_output = fopen(fname, "w");
1605 if (current_output == NULL) {
1606 (void) fprintf(stderr, "***Error opening %s: ", fname);
1610 i = 1; /* flag we need a close */
1612 current_output = stdout;
1613 i = 0; /* flag no close */
1616 if (interactive && setjmp(interrupt_buf)) {
1621 (xcmd->handler)(&pcmd, current_output);
1622 jump = 0; /* HMS: 961106: was after fclose() */
1623 if (i) (void) fclose(current_output);
1631 * tokenize - turn a command line into tokens
1633 * SK: Modified to allow a quoted string
1635 * HMS: If the first character of the first token is a ':' then (after
1636 * eating inter-token whitespace) the 2nd token is the rest of the line.
1646 register const char *cp;
1648 static char tspace[MAXLINE];
1652 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1655 /* Skip inter-token whitespace */
1656 while (ISSPACE(*cp))
1659 /* If we're at EOL we're done */
1663 /* If this is the 2nd token and the first token begins
1664 * with a ':', then just grab to EOL.
1667 if (*ntok == 1 && tokens[0][0] == ':') {
1669 if (sp - tspace >= MAXLINE)
1672 } while (!ISEOL(*cp));
1675 /* Check if this token begins with a double quote.
1676 * If yes, continue reading till the next double quote
1678 else if (*cp == '\"') {
1681 if (sp - tspace >= MAXLINE)
1684 } while ((*cp != '\"') && !ISEOL(*cp));
1685 /* HMS: a missing closing " should be an error */
1689 if (sp - tspace >= MAXLINE)
1692 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1693 /* HMS: Why check for a " in the previous line? */
1696 if (sp - tspace >= MAXLINE)
1705 "***Line `%s' is too big\n",
1712 * getarg - interpret an argument token
1723 switch (code & ~OPT) {
1729 if (!getnetnum(str, &argp->netnum, NULL, 0))
1734 if ('&' == str[0]) {
1735 if (!atouint(&str[1], &ul)) {
1737 "***Association index `%s' invalid/undecodable\n",
1741 if (0 == numassoc) {
1743 if (0 == numassoc) {
1745 "***No associations found, `%s' unknown\n",
1750 ul = min(ul, numassoc);
1751 argp->uval = assoc_cache[ul - 1].assid;
1754 if (!atouint(str, &argp->uval)) {
1755 fprintf(stderr, "***Illegal unsigned value %s\n",
1762 if (!atoint(str, &argp->ival)) {
1763 fprintf(stderr, "***Illegal integer value %s\n",
1770 if (!strcmp("-6", str)) {
1772 } else if (!strcmp("-4", str)) {
1775 fprintf(stderr, "***Version must be either 4 or 6\n");
1783 #endif /* !BUILD_AS_LIB */
1787 * findcmd - find a command in a command description table
1792 struct xcmd * clist1,
1793 struct xcmd * clist2,
1800 struct xcmd *nearmatch = NULL;
1807 else if (clist2 != 0)
1813 for (cl = clist; cl->keyword != 0; cl++) {
1814 /* do a first character check, for efficiency */
1815 if (*str != *(cl->keyword))
1817 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1819 * Could be extact match, could be approximate.
1820 * Is exact if the length of the keyword is the
1823 if (*((cl->keyword) + clen) == '\0') {
1833 * See if there is more to do. If so, go again. Sorry about the
1834 * goto, too much looking at BSD sources...
1836 if (clist == clist1 && clist2 != 0) {
1842 * If we got extactly 1 near match, use it, else return number
1854 * getnetnum - given a host name, return its net number
1855 * and (optional) full name
1865 struct addrinfo hints, *ai = NULL;
1868 hints.ai_flags = AI_CANONNAME;
1869 #ifdef AI_ADDRCONFIG
1870 hints.ai_flags |= AI_ADDRCONFIG;
1874 * decodenetnum only works with addresses, but handles syntax
1875 * that getaddrinfo doesn't: [2001::1]:1234
1877 if (decodenetnum(hname, num)) {
1878 if (fullhost != NULL)
1879 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1880 LENHOSTNAME, NULL, 0, 0);
1882 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1883 INSIST(sizeof(*num) >= ai->ai_addrlen);
1884 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1885 if (fullhost != NULL) {
1886 if (ai->ai_canonname != NULL)
1887 strlcpy(fullhost, ai->ai_canonname,
1890 getnameinfo(&num->sa, SOCKLEN(num),
1891 fullhost, LENHOSTNAME, NULL,
1897 fprintf(stderr, "***Can't find host %s\n", hname);
1904 * nntohost - convert network number to host name. This routine enforces
1905 * the showhostnames setting.
1912 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1917 * nntohost_col - convert network number to host name in fixed width.
1918 * This routine enforces the showhostnames setting.
1919 * When displaying hostnames longer than the width,
1920 * the first part of the hostname is displayed. When
1921 * displaying numeric addresses longer than the width,
1922 * Such as IPv6 addresses, the caller decides whether
1923 * the first or last of the numeric address is used.
1929 int preserve_lowaddrbits
1934 if (!showhostnames || SOCK_UNSPEC(addr)) {
1935 if (preserve_lowaddrbits)
1936 out = trunc_left(stoa(addr), width);
1938 out = trunc_right(stoa(addr), width);
1939 } else if (ISREFCLOCKADR(addr)) {
1940 out = refnumtoa(addr);
1942 out = trunc_right(socktohost(addr), width);
1949 * nntohostp() is the same as nntohost() plus a :port suffix
1959 if (!showhostnames || SOCK_UNSPEC(netnum))
1960 return sptoa(netnum);
1961 else if (ISREFCLOCKADR(netnum))
1962 return refnumtoa(netnum);
1964 hostn = socktohost(netnum);
1966 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1972 * rtdatetolfp - decode an RT-11 date into an l_fp
1982 struct calendar cal;
1988 * An RT-11 date looks like:
1990 * d[d]-Mth-y[y] hh:mm:ss
1992 * (No docs, but assume 4-digit years are also legal...)
1994 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
1997 if (!isdigit((int)*cp)) {
2000 * Catch special case
2008 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2009 if (isdigit((int)*cp)) {
2010 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2011 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2017 for (i = 0; i < 3; i++)
2021 for (i = 0; i < 12; i++)
2022 if (STREQ(buf, months[i]))
2026 cal.month = (u_char)(i + 1);
2031 if (!isdigit((int)*cp))
2033 cal.year = (u_short)(*cp++ - '0');
2034 if (isdigit((int)*cp)) {
2035 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2036 cal.year = (u_short)(*cp++ - '0');
2038 if (isdigit((int)*cp)) {
2039 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2040 cal.year = (u_short)(cal.year + *cp++ - '0');
2042 if (isdigit((int)*cp)) {
2043 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2044 cal.year = (u_short)(cal.year + *cp++ - '0');
2048 * Catch special case. If cal.year == 0 this is a zero timestamp.
2050 if (cal.year == 0) {
2055 if (*cp++ != ' ' || !isdigit((int)*cp))
2057 cal.hour = (u_char)(*cp++ - '0');
2058 if (isdigit((int)*cp)) {
2059 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2060 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2063 if (*cp++ != ':' || !isdigit((int)*cp))
2065 cal.minute = (u_char)(*cp++ - '0');
2066 if (isdigit((int)*cp)) {
2067 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2068 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2071 if (*cp++ != ':' || !isdigit((int)*cp))
2073 cal.second = (u_char)(*cp++ - '0');
2074 if (isdigit((int)*cp)) {
2075 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2076 cal.second = (u_char)(cal.second + *cp++ - '0');
2080 * For RT-11, 1972 seems to be the pivot year
2087 lfp->l_ui = caltontp(&cal);
2094 * decodets - decode a timestamp into an l_fp format number, with
2095 * consideration of fuzzball formats.
2108 * If it starts with a 0x, decode as hex.
2110 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2111 return hextolfp(str+2, lfp);
2114 * If it starts with a '"', try it as an RT-11 date.
2119 while ('"' != *cp && '\0' != *cp &&
2120 b < COUNTOF(buf) - 1)
2123 return rtdatetolfp(buf, lfp);
2127 * Might still be hex. Check out the first character. Talk
2130 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2131 return hextolfp(str, lfp);
2134 * Try it as a decimal. If this fails, try as an unquoted
2135 * RT-11 date. This code should go away eventually.
2137 if (atolfp(str, lfp))
2140 return rtdatetolfp(str, lfp);
2145 * decodetime - decode a time value. It should be in milliseconds
2153 return mstolfp(str, lfp);
2158 * decodeint - decode an integer
2167 if (*(str+1) == 'x' || *(str+1) == 'X')
2168 return hextoint(str+2, (u_long *)val);
2169 return octtoint(str, (u_long *)val);
2171 return atoint(str, val);
2176 * decodeuint - decode an unsigned integer
2185 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2186 return (hextoint(str + 2, val));
2187 return (octtoint(str, val));
2189 return (atouint(str, val));
2194 * decodearr - decode an array of time values
2203 register char *cp, *bp;
2212 while (isspace((int)*cp))
2218 while (!isspace((int)*cp) && *cp != '\0')
2222 if (!decodetime(buf, lfp))
2232 * Finally, the built in command handlers
2236 * help - tell about commands, or details of a particular command
2244 struct xcmd *xcp = NULL; /* quiet warning */
2246 const char *list[100];
2252 if (pcmd->nargs == 0) {
2254 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2255 if (*(xcp->keyword) != '?' &&
2256 words < COUNTOF(list))
2257 list[words++] = xcp->keyword;
2259 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2260 if (words < COUNTOF(list))
2261 list[words++] = xcp->keyword;
2263 qsort((void *)list, words, sizeof(list[0]), helpsort);
2265 for (word = 0; word < words; word++) {
2266 length = strlen(list[word]);
2267 col = max(col, length);
2270 cols = SCREENWIDTH / ++col;
2271 rows = (words + cols - 1) / cols;
2273 fprintf(fp, "ntpq commands:\n");
2275 for (row = 0; row < rows; row++) {
2276 for (word = row; word < words; word += rows)
2277 fprintf(fp, "%-*.*s", (int)col,
2278 (int)col - 1, list[word]);
2282 cmd = pcmd->argval[0].string;
2283 words = findcmd(cmd, builtins, opcmds, &xcp);
2286 "Command `%s' is unknown\n", cmd);
2288 } else if (words >= 2) {
2290 "Command `%s' is ambiguous\n", cmd);
2293 fprintf(fp, "function: %s\n", xcp->comment);
2294 printusage(xcp, fp);
2300 * helpsort - do hostname qsort comparisons
2308 const char * const * name1 = t1;
2309 const char * const * name2 = t2;
2311 return strcmp(*name1, *name2);
2316 * printusage - print usage information for a command
2326 /* XXX: Do we need to warn about extra args here too? */
2328 (void) fprintf(fp, "usage: %s", xcp->keyword);
2329 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2330 if (xcp->arg[i] & OPT)
2331 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2333 (void) fprintf(fp, " %s", xcp->desc[i]);
2335 (void) fprintf(fp, "\n");
2340 * timeout - set time out time
2350 if (pcmd->nargs == 0) {
2351 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2352 (void) fprintf(fp, "primary timeout %d ms\n", val);
2354 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2355 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2362 * auth_delay - set delay for auth requests
2373 if (pcmd->nargs == 0) {
2374 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2375 (void) fprintf(fp, "delay %lu ms\n", val);
2377 if (pcmd->argval[0].ival < 0) {
2379 val = (u_long)(-pcmd->argval[0].ival);
2382 val = (u_long)pcmd->argval[0].ival;
2385 delay_time.l_ui = val / 1000;
2387 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2396 * host - set the host we are dealing with.
2406 if (pcmd->nargs == 0) {
2408 (void) fprintf(fp, "current host is %s\n",
2411 (void) fprintf(fp, "no current host\n");
2416 ai_fam_templ = ai_fam_default;
2417 if (pcmd->nargs == 2) {
2418 if (!strcmp("-4", pcmd->argval[i].string))
2419 ai_fam_templ = AF_INET;
2420 else if (!strcmp("-6", pcmd->argval[i].string))
2421 ai_fam_templ = AF_INET6;
2426 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2427 fprintf(fp, "current host set to %s\n", currenthost);
2431 fprintf(fp, "current host remains %s\n",
2434 fprintf(fp, "still no current host\n");
2440 * poll - do one (or more) polls of the host via NTP
2449 (void) fprintf(fp, "poll not implemented yet\n");
2454 * showdrefid2str - return a string explanation of the value of drefid
2457 showdrefid2str(void)
2471 * drefid - display/change "display hash"
2479 if (pcmd->nargs == 0) {
2480 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2482 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2483 drefid = REFID_HASH;
2484 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2485 drefid = REFID_IPV4;
2487 (void) fprintf(fp, "What?\n");
2490 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2495 * keyid - get a keyid to use for authenticating requests
2503 if (pcmd->nargs == 0) {
2504 if (info_auth_keyid == 0)
2505 (void) fprintf(fp, "no keyid defined\n");
2507 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2509 /* allow zero so that keyid can be cleared. */
2510 if(pcmd->argval[0].uval > NTP_MAXKEY)
2511 (void) fprintf(fp, "Invalid key identifier\n");
2512 info_auth_keyid = pcmd->argval[0].uval;
2517 * keytype - get type of key to use for authenticating requests
2525 const char * digest_name;
2530 fprintf(fp, "keytype is %s with %lu octet digests\n",
2531 keytype_name(info_auth_keytype),
2532 (u_long)info_auth_hashlen);
2536 digest_name = pcmd->argval[0].string;
2538 key_type = keytype_from_text(digest_name, &digest_len);
2541 fprintf(fp, "keytype is not valid. "
2543 "Type \"help keytype\" for the available digest types.\n");
2545 "Only \"md5\" is available.\n");
2550 info_auth_keytype = key_type;
2551 info_auth_hashlen = digest_len;
2556 * passwd - get an authentication key
2567 if (info_auth_keyid == 0) {
2568 info_auth_keyid = getkeyid("Keyid: ");
2569 if (info_auth_keyid == 0) {
2570 (void)fprintf(fp, "Keyid must be defined\n");
2574 if (pcmd->nargs >= 1)
2575 pass = pcmd->argval[0].string;
2577 pass = getpass_keytype(info_auth_keytype);
2578 if ('\0' == pass[0]) {
2579 fprintf(fp, "Password unchanged\n");
2583 authusekey(info_auth_keyid, info_auth_keytype,
2584 (const u_char *)pass);
2585 authtrust(info_auth_keyid, 1);
2590 * hostnames - set the showhostnames flag
2598 if (pcmd->nargs == 0) {
2600 (void) fprintf(fp, "hostnames being shown\n");
2602 (void) fprintf(fp, "hostnames not being shown\n");
2604 if (STREQ(pcmd->argval[0].string, "yes"))
2606 else if (STREQ(pcmd->argval[0].string, "no"))
2609 (void)fprintf(stderr, "What?\n");
2616 * setdebug - set/change debugging level
2624 if (pcmd->nargs == 0) {
2625 (void) fprintf(fp, "debug level is %d\n", debug);
2627 } else if (STREQ(pcmd->argval[0].string, "no")) {
2629 } else if (STREQ(pcmd->argval[0].string, "more")) {
2631 } else if (STREQ(pcmd->argval[0].string, "less")) {
2634 (void) fprintf(fp, "What?\n");
2637 (void) fprintf(fp, "debug level set to %d\n", debug);
2642 * quit - stop this nonsense
2652 closesocket(sockfd); /* cleanliness next to godliness */
2658 * version - print the current version number
2668 (void) fprintf(fp, "%s\n", Version);
2674 * raw - set raw mode output
2684 (void) fprintf(fp, "Output set to raw\n");
2689 * cooked - set cooked mode output
2699 (void) fprintf(fp, "Output set to cooked\n");
2705 * authenticate - always authenticate requests to this host
2713 if (pcmd->nargs == 0) {
2716 "authenticated requests being sent\n");
2719 "unauthenticated requests being sent\n");
2721 if (STREQ(pcmd->argval[0].string, "yes")) {
2723 } else if (STREQ(pcmd->argval[0].string, "no")) {
2726 (void)fprintf(stderr, "What?\n");
2732 * ntpversion - choose the NTP version to use
2740 if (pcmd->nargs == 0) {
2742 "NTP version being claimed is %d\n", pktversion);
2744 if (pcmd->argval[0].uval < NTP_OLDVERSION
2745 || pcmd->argval[0].uval > NTP_VERSION) {
2746 (void) fprintf(stderr, "versions %d to %d, please\n",
2747 NTP_OLDVERSION, NTP_VERSION);
2749 pktversion = (u_char) pcmd->argval[0].uval;
2755 static void __attribute__((__format__(__printf__, 1, 0)))
2756 vwarning(const char *fmt, va_list ap)
2759 (void) fprintf(stderr, "%s: ", progname);
2760 vfprintf(stderr, fmt, ap);
2761 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2765 * warning - print a warning message
2767 static void __attribute__((__format__(__printf__, 1, 2)))
2781 * error - print a message and exit
2783 static void __attribute__((__format__(__printf__, 1, 2)))
2796 * getkeyid - prompt the user for a keyid to use
2800 const char *keyprompt
2810 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2812 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2813 #endif /* SYS_WINNT */
2816 setbuf(fi, (char *)NULL);
2817 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2818 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2819 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2821 pbuf[i++] = (char)c;
2826 return (u_long) atoi(pbuf);
2831 * atoascii - printable-ize possibly ascii data using the character
2832 * transformations cat -v uses.
2842 const u_char * pchIn;
2843 const u_char * pchInLimit;
2847 pchIn = (const u_char *)in;
2848 pchInLimit = pchIn + in_octets;
2849 pchOut = (u_char *)out;
2851 if (NULL == pchIn) {
2859 if (0 == --out_octets) { \
2866 for ( ; pchIn < pchInLimit; pchIn++) {
2877 ONEOUT((u_char)(c + '@'));
2878 } else if (0x7f == c) {
2891 * makeascii - print possibly ascii data using the character
2892 * transformations that cat -v uses.
2901 const u_char *data_u_char;
2905 data_u_char = (const u_char *)data;
2907 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2918 } else if (0x7f == c) {
2928 * asciize - same thing as makeascii except add a newline
2937 makeascii(length, data, fp);
2943 * truncate string to fit clipping excess at end.
2944 * "too long" -> "too l"
2945 * Used for hostnames.
2958 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2960 memcpy(out, src, width);
2971 * truncate string to fit by preserving right side and using '_' to hint
2972 * "too long" -> "_long"
2973 * Used for local IPv6 addresses, where low bits differentiate.
2986 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2989 memcpy(&out[1], &src[sl + 1 - width], width);
2999 * Some circular buffer space
3004 char circ_buf[NUMCB][CBLEN];
3008 * nextvar - find the next variable in the buffer
3023 static char name[MAXVARLEN];
3024 static char value[MAXVALLEN];
3027 cpend = cp + *datalen;
3030 * Space past commas and white space
3032 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
3038 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
3039 * over any white space and terminate it.
3041 srclen = strcspn(cp, ",=\r\n");
3042 srclen = min(srclen, (size_t)(cpend - cp));
3044 while (len > 0 && isspace((unsigned char)cp[len - 1]))
3046 if (len >= sizeof(name))
3049 memcpy(name, cp, len);
3055 * Check if we hit the end of the buffer or a ','. If so we are done.
3057 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
3061 *datalen = size2int_sat(cpend - cp);
3067 * So far, so good. Copy out the value
3069 cp++; /* past '=' */
3070 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
3076 } while (np < cpend && '"' != *np);
3077 if (np < cpend && '"' == *np)
3080 while (np < cpend && ',' != *np && '\r' != *np)
3084 if (np > cpend || len >= sizeof(value) ||
3085 (np < cpend && ',' != *np && '\r' != *np))
3087 memcpy(value, cp, len);
3089 * Trim off any trailing whitespace
3091 while (len > 0 && isspace((unsigned char)value[len - 1]))
3096 * Return this. All done.
3098 if (np < cpend && ',' == *np)
3101 *datalen = size2int_sat(cpend - np);
3108 varfmt(const char * varname)
3112 for (n = 0; n < COUNTOF(cookedvars); n++)
3113 if (!strcmp(varname, cookedvars[n].varname))
3114 return cookedvars[n].fmt;
3121 * printvars - print variables returned in response packet
3134 rawprint(sttype, length, data, status, quiet, fp);
3136 cookedprint(sttype, length, data, status, quiet, fp);
3141 * rawprint - do a printout of the data in raw mode
3157 * Essentially print the data as is. We reformat unprintables, though.
3160 cpend = data + length;
3163 (void) fprintf(fp, "status=0x%04x,\n", status);
3165 while (cp < cpend) {
3168 * If this is a \r and the next character is a
3169 * \n, supress this, else pretty print it. Otherwise
3170 * just output the character.
3172 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3173 makeascii(1, cp, fp);
3174 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3177 makeascii(1, cp, fp);
3184 * Global data used by the cooked output routines
3186 int out_chars; /* number of characters output */
3187 int out_linecount; /* number of characters output on this line */
3191 * startoutput - get ready to do cooked output
3202 * output - output a variable=value combination
3213 /* strlen of "name=value" */
3214 len = size2int_sat(strlen(name) + 1 + strlen(value));
3216 if (out_chars != 0) {
3218 if ((out_linecount + len + 2) > MAXOUTLINE) {
3231 out_linecount += len;
3236 * endoutput - terminate a block of cooked output
3249 * outputarr - output an array of values
3267 * Hack to align delay and offset values
3269 for (i = (int)strlen(name); i < 11; i++)
3272 for (i = narr; i > 0; i--) {
3275 cp = lfptoms(lfp, 2);
3290 output(fp, name, buf);
3298 register char *cp, *s;
3301 register const char *sep;
3304 s = cp = circ_buf[nextcb];
3305 if (++nextcb >= NUMCB)
3307 cb = sizeof(circ_buf[0]);
3309 snprintf(cp, cb, "%02lx", val);
3313 strlcat(cp, " ok", cb);
3321 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3323 snprintf(cp, cb, "%s%s", sep,
3339 * cookedprint - output variables in cooked mode
3362 char bn[2 * MAXVARLEN];
3363 char bv[2 * MAXVALLEN];
3365 UNUSED_ARG(datatype);
3368 fprintf(fp, "status=%04x %s,\n", status,
3369 statustoa(datatype, status));
3372 while (nextvar(&length, &data, &name, &value)) {
3382 if (!decodets(value, &lfp))
3385 output(fp, name, prettydate(&lfp));
3388 case HA: /* fallthru */
3390 if (!decodenetnum(value, &hval)) {
3392 } else if (fmt == HA){
3393 output(fp, name, nntohost(&hval));
3395 output(fp, name, stoa(&hval));
3400 if (decodenetnum(value, &hval)) {
3401 if (ISREFCLOCKADR(&hval))
3405 output(fp, name, stoa(&hval));
3406 } else if (strlen(value) <= 4) {
3407 output(fp, name, value);
3414 if (!decodeuint(value, &uval) || uval > 3) {
3424 output(fp, name, b);
3429 if (!decodeuint(value, &uval)) {
3432 snprintf(b, sizeof(b), "%03lo", uval);
3433 output(fp, name, b);
3438 if (!decodearr(value, &narr, lfparr))
3441 outputarr(fp, name, narr, lfparr);
3445 if (!decodeuint(value, &uval))
3448 output(fp, name, tstflags(uval));
3452 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3458 if (output_raw != 0) {
3459 /* TALOS-CAN-0063: avoid buffer overrun */
3460 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3461 if (output_raw != '*') {
3462 atoascii(value, MAXVALLEN,
3463 bv, sizeof(bv) - 1);
3465 bv[len] = output_raw;
3468 atoascii(value, MAXVALLEN,
3479 * sortassoc - sort associations in the cache into ascending order
3485 qsort(assoc_cache, (size_t)numassoc,
3486 sizeof(assoc_cache[0]), &assoccmp);
3491 * assoccmp - compare two associations
3499 const struct association *ass1 = t1;
3500 const struct association *ass2 = t2;
3502 if (ass1->assid < ass2->assid)
3504 if (ass1->assid > ass2->assid)
3511 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3513 * The strategy is to add an assumed 4k page size at a time, leaving
3514 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3517 grow_assoc_cache(void)
3519 static size_t prior_sz;
3522 new_sz = prior_sz + 4 * 1024;
3523 if (0 == prior_sz) {
3524 new_sz -= 4 * sizeof(void *);
3526 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3528 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3533 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3535 * By default, autoopts loses the relative order of -c and -p options
3536 * on the command line. This routine replaces the default handler for
3537 * those routines and builds a list of commands to execute preserving
3541 ntpq_custom_opt_handler(
3546 switch (pOptDesc->optValue) {
3550 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3551 pOptDesc->optValue, pOptDesc->optValue);
3555 ADDCMD(pOptDesc->pzLastArg);
3564 * Obtain list of digest names
3568 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3574 #define K_PER_LINE 8
3575 #define K_NL_PFX_STR "\n "
3576 #define K_DELIM_STR ", "
3577 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3580 const char *name, *cp, **seen;
3581 struct hstate *hstate = arg;
3584 u_char digest[EVP_MAX_MD_SIZE];
3587 return; /* Ignore aliases */
3589 name = EVP_MD_name(m);
3591 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3593 for( cp = name; *cp; cp++ ) {
3597 len = (cp - name) + 1;
3599 /* There are duplicates. Discard if name has been seen. */
3601 for (seen = hstate->seen; *seen; seen++)
3602 if (!strcmp(*seen, name))
3604 n = (seen - hstate->seen) + 2;
3605 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3606 hstate->seen[n-2] = name;
3607 hstate->seen[n-1] = NULL;
3609 /* Discard MACs that NTP won't accept.
3610 * Keep this consistent with keytype_from_text() in ssl_init.c.
3613 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3614 EVP_DigestFinal(&ctx, digest, &digest_len);
3615 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3618 if (hstate->list != NULL)
3619 len += strlen(hstate->list);
3620 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3622 if (hstate->list == NULL) {
3623 hstate->list = (char *)emalloc(len);
3624 hstate->list[0] = '\0';
3626 hstate->list = (char *)erealloc(hstate->list, len);
3628 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3629 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3631 if (hstate->idx >= K_PER_LINE)
3639 static char *list_digest_names(void)
3644 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3645 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3647 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3650 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3654 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3655 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3658 list = (char *)emalloc(sizeof("md5"));
3659 strcpy(list, "md5");
3665 #define CTRLC_STACK_MAX 4
3666 static volatile size_t ctrlc_stack_len = 0;
3667 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3672 push_ctrl_c_handler(
3676 size_t size = ctrlc_stack_len;
3677 if (func && (size < CTRLC_STACK_MAX)) {
3678 ctrlc_stack[size] = func;
3679 ctrlc_stack_len = size + 1;
3690 size_t size = ctrlc_stack_len;
3693 if (func == NULL || func == ctrlc_stack[size]) {
3694 ctrlc_stack_len = size;
3704 size_t size = ctrlc_stack_len;
3706 if ((*ctrlc_stack[--size])())
3720 char * buf = emalloc(len);
3723 /* Note: we expect the memory allocation to fail long before the
3724 * increment in buffer size actually overflows.
3726 buf = (buf) ? erealloc(buf, len) : emalloc(len);
3729 prc = vsnprintf(buf, len, fmt, va);
3733 /* might be very old vsnprintf. Or actually MSVC... */
3737 if ((size_t)prc >= len) {
3738 /* at least we have the proper size now... */
3739 len = (size_t)prc + 1;
3742 if ((size_t)prc < (len - 32))
3743 buf = erealloc(buf, (size_t)prc + 1);