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.
1199 #if !defined(SYS_WINNT) && defined(EINTR)
1203 if (seenlastfrag && offsets[0] == 0) {
1204 for (f = 1; f < numfrags; f++)
1205 if (offsets[f-1] + counts[f-1] !=
1208 if (f == numfrags) {
1209 *rsize = offsets[f-1] + counts[f-1];
1210 TRACE(1, ("%lu packets reassembled into response\n",
1215 } /* giant for (;;) collecting response packets */
1216 } /* getresponse() */
1220 * sendrequest - format and send a request packet
1231 struct ntp_control qpkt;
1238 * Check to make sure the data will fit in one packet
1240 if (qsize > CTL_MAX_DATA_LEN) {
1242 "***Internal error! qsize (%zu) too large\n",
1248 * Fill in the packet
1250 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1251 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1252 qpkt.sequence = htons(sequence);
1254 qpkt.associd = htons((u_short)associd);
1256 qpkt.count = htons((u_short)qsize);
1258 pktsize = CTL_HEADER_LEN;
1261 * If we have data, copy and pad it out to a 32-bit boundary.
1264 memcpy(&qpkt.u, qdata, (size_t)qsize);
1266 while (pktsize & (sizeof(u_int32) - 1)) {
1267 qpkt.u.data[qsize++] = 0;
1273 * If it isn't authenticated we can just send it. Otherwise
1274 * we're going to have to think about it a little.
1276 if (!auth && !always_auth) {
1277 return sendpkt(&qpkt, pktsize);
1281 * Pad out packet to a multiple of 8 octets to be sure
1282 * receiver can handle it.
1284 while (pktsize & 7) {
1285 qpkt.u.data[qsize++] = 0;
1290 * Get the keyid and the password if we don't have one.
1292 if (info_auth_keyid == 0) {
1293 key_id = getkeyid("Keyid: ");
1294 if (key_id == 0 || key_id > NTP_MAXKEY) {
1296 "Invalid key identifier\n");
1299 info_auth_keyid = key_id;
1301 if (!authistrusted(info_auth_keyid)) {
1302 pass = getpass_keytype(info_auth_keytype);
1303 if ('\0' == pass[0]) {
1304 fprintf(stderr, "Invalid password\n");
1307 authusekey(info_auth_keyid, info_auth_keytype,
1309 authtrust(info_auth_keyid, 1);
1313 * Do the encryption.
1315 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1317 fprintf(stderr, "Key not found\n");
1319 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1321 "%zu octet MAC, %zu expected with %zu octet digest\n",
1322 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1327 return sendpkt((char *)&qpkt, pktsize + maclen);
1332 * show_error_msg - display the error text for a mode 6 error response.
1341 fprintf(stderr, "server=%s ", currenthost);
1347 "***Server reports a bad format request packet\n");
1350 case CERR_PERMISSION:
1352 "***Server disallowed request (authentication?)\n");
1357 "***Server reports a bad opcode in request\n");
1362 "***Association ID %d unknown to server\n",
1366 case CERR_UNKNOWNVAR:
1368 "***A request variable unknown to the server\n");
1373 "***Server indicates a request variable was bad\n");
1378 "***Server returned an unspecified error\n");
1382 fprintf(stderr, "***Request timed out\n");
1385 case ERR_INCOMPLETE:
1387 "***Response from server was incomplete\n");
1392 "***Buffer size exceeded for returned data\n");
1397 "***Server returns unknown error code %d\n",
1403 * doquery - send a request and process the response, displaying
1404 * error messages for any error responses.
1418 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1419 rsize, rdata, FALSE);
1424 * doqueryex - send a request and process the response, optionally
1425 * displaying error messages for any error responses.
1444 * Check to make sure host is open
1447 fprintf(stderr, "***No host open, use `host' command\n");
1458 res = sendrequest(opcode, associd, auth, qsize, qdata);
1463 * Get the response. If we got a standard error, print a message
1465 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1468 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1469 if (res == ERR_INCOMPLETE) {
1471 * better bump the sequence so we don't
1472 * get confused about differing fragments.
1480 show_error_msg(res, associd);
1487 #ifndef BUILD_AS_LIB
1489 * getcmds - read commands from the standard input and execute them
1497 ntp_readline_init(interactive ? prompt : NULL);
1500 line = ntp_readline(&count);
1507 ntp_readline_uninit();
1509 #endif /* !BUILD_AS_LIB */
1512 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1514 * abortcmd - catch interrupts and abort the current command
1519 if (current_output == stdout)
1520 (void) fflush(stdout);
1522 (void) fflush(stderr);
1525 longjmp(interrupt_buf, 1);
1529 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1532 #ifndef BUILD_AS_LIB
1534 * docmd - decode the command line and execute a command
1541 char *tokens[1+MAXARGS+2];
1548 * Tokenize the command line. If nothing on it, return.
1550 tokenize(cmdline, tokens, &ntok);
1555 * Find the appropriate command description.
1557 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1559 (void) fprintf(stderr, "***Command `%s' unknown\n",
1562 } else if (i >= 2) {
1563 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1568 /* Warn about ignored extra args */
1569 for (i = MAXARGS + 1; i < ntok ; ++i) {
1570 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1574 * Save the keyword, then walk through the arguments, interpreting
1577 pcmd.keyword = tokens[0];
1579 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1580 if ((i+1) >= ntok) {
1581 if (!(xcmd->arg[i] & OPT)) {
1582 printusage(xcmd, stderr);
1587 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1589 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1595 if (i < ntok && *tokens[i] == '>') {
1598 if (*(tokens[i]+1) != '\0')
1599 fname = tokens[i]+1;
1600 else if ((i+1) < ntok)
1601 fname = tokens[i+1];
1603 (void) fprintf(stderr, "***No file for redirect\n");
1607 current_output = fopen(fname, "w");
1608 if (current_output == NULL) {
1609 (void) fprintf(stderr, "***Error opening %s: ", fname);
1613 i = 1; /* flag we need a close */
1615 current_output = stdout;
1616 i = 0; /* flag no close */
1619 if (interactive && setjmp(interrupt_buf)) {
1624 (xcmd->handler)(&pcmd, current_output);
1625 jump = 0; /* HMS: 961106: was after fclose() */
1626 if (i) (void) fclose(current_output);
1634 * tokenize - turn a command line into tokens
1636 * SK: Modified to allow a quoted string
1638 * HMS: If the first character of the first token is a ':' then (after
1639 * eating inter-token whitespace) the 2nd token is the rest of the line.
1649 register const char *cp;
1651 static char tspace[MAXLINE];
1655 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1658 /* Skip inter-token whitespace */
1659 while (ISSPACE(*cp))
1662 /* If we're at EOL we're done */
1666 /* If this is the 2nd token and the first token begins
1667 * with a ':', then just grab to EOL.
1670 if (*ntok == 1 && tokens[0][0] == ':') {
1672 if (sp - tspace >= MAXLINE)
1675 } while (!ISEOL(*cp));
1678 /* Check if this token begins with a double quote.
1679 * If yes, continue reading till the next double quote
1681 else if (*cp == '\"') {
1684 if (sp - tspace >= MAXLINE)
1687 } while ((*cp != '\"') && !ISEOL(*cp));
1688 /* HMS: a missing closing " should be an error */
1692 if (sp - tspace >= MAXLINE)
1695 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1696 /* HMS: Why check for a " in the previous line? */
1699 if (sp - tspace >= MAXLINE)
1708 "***Line `%s' is too big\n",
1715 * getarg - interpret an argument token
1726 switch (code & ~OPT) {
1732 if (!getnetnum(str, &argp->netnum, NULL, 0))
1737 if ('&' == str[0]) {
1738 if (!atouint(&str[1], &ul)) {
1740 "***Association index `%s' invalid/undecodable\n",
1744 if (0 == numassoc) {
1746 if (0 == numassoc) {
1748 "***No associations found, `%s' unknown\n",
1753 ul = min(ul, numassoc);
1754 argp->uval = assoc_cache[ul - 1].assid;
1757 if (!atouint(str, &argp->uval)) {
1758 fprintf(stderr, "***Illegal unsigned value %s\n",
1765 if (!atoint(str, &argp->ival)) {
1766 fprintf(stderr, "***Illegal integer value %s\n",
1773 if (!strcmp("-6", str)) {
1775 } else if (!strcmp("-4", str)) {
1778 fprintf(stderr, "***Version must be either 4 or 6\n");
1786 #endif /* !BUILD_AS_LIB */
1790 * findcmd - find a command in a command description table
1795 struct xcmd * clist1,
1796 struct xcmd * clist2,
1803 struct xcmd *nearmatch = NULL;
1810 else if (clist2 != 0)
1816 for (cl = clist; cl->keyword != 0; cl++) {
1817 /* do a first character check, for efficiency */
1818 if (*str != *(cl->keyword))
1820 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1822 * Could be extact match, could be approximate.
1823 * Is exact if the length of the keyword is the
1826 if (*((cl->keyword) + clen) == '\0') {
1836 * See if there is more to do. If so, go again. Sorry about the
1837 * goto, too much looking at BSD sources...
1839 if (clist == clist1 && clist2 != 0) {
1845 * If we got extactly 1 near match, use it, else return number
1857 * getnetnum - given a host name, return its net number
1858 * and (optional) full name
1868 struct addrinfo hints, *ai = NULL;
1871 hints.ai_flags = AI_CANONNAME;
1872 #ifdef AI_ADDRCONFIG
1873 hints.ai_flags |= AI_ADDRCONFIG;
1877 * decodenetnum only works with addresses, but handles syntax
1878 * that getaddrinfo doesn't: [2001::1]:1234
1880 if (decodenetnum(hname, num)) {
1881 if (fullhost != NULL)
1882 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1883 LENHOSTNAME, NULL, 0, 0);
1885 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1886 INSIST(sizeof(*num) >= ai->ai_addrlen);
1887 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1888 if (fullhost != NULL) {
1889 if (ai->ai_canonname != NULL)
1890 strlcpy(fullhost, ai->ai_canonname,
1893 getnameinfo(&num->sa, SOCKLEN(num),
1894 fullhost, LENHOSTNAME, NULL,
1900 fprintf(stderr, "***Can't find host %s\n", hname);
1907 * nntohost - convert network number to host name. This routine enforces
1908 * the showhostnames setting.
1915 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1920 * nntohost_col - convert network number to host name in fixed width.
1921 * This routine enforces the showhostnames setting.
1922 * When displaying hostnames longer than the width,
1923 * the first part of the hostname is displayed. When
1924 * displaying numeric addresses longer than the width,
1925 * Such as IPv6 addresses, the caller decides whether
1926 * the first or last of the numeric address is used.
1932 int preserve_lowaddrbits
1937 if (!showhostnames || SOCK_UNSPEC(addr)) {
1938 if (preserve_lowaddrbits)
1939 out = trunc_left(stoa(addr), width);
1941 out = trunc_right(stoa(addr), width);
1942 } else if (ISREFCLOCKADR(addr)) {
1943 out = refnumtoa(addr);
1945 out = trunc_right(socktohost(addr), width);
1952 * nntohostp() is the same as nntohost() plus a :port suffix
1962 if (!showhostnames || SOCK_UNSPEC(netnum))
1963 return sptoa(netnum);
1964 else if (ISREFCLOCKADR(netnum))
1965 return refnumtoa(netnum);
1967 hostn = socktohost(netnum);
1969 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1975 * rtdatetolfp - decode an RT-11 date into an l_fp
1985 struct calendar cal;
1991 * An RT-11 date looks like:
1993 * d[d]-Mth-y[y] hh:mm:ss
1995 * (No docs, but assume 4-digit years are also legal...)
1997 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
2000 if (!isdigit((int)*cp)) {
2003 * Catch special case
2011 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2012 if (isdigit((int)*cp)) {
2013 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2014 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2020 for (i = 0; i < 3; i++)
2024 for (i = 0; i < 12; i++)
2025 if (STREQ(buf, months[i]))
2029 cal.month = (u_char)(i + 1);
2034 if (!isdigit((int)*cp))
2036 cal.year = (u_short)(*cp++ - '0');
2037 if (isdigit((int)*cp)) {
2038 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2039 cal.year = (u_short)(*cp++ - '0');
2041 if (isdigit((int)*cp)) {
2042 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2043 cal.year = (u_short)(cal.year + *cp++ - '0');
2045 if (isdigit((int)*cp)) {
2046 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2047 cal.year = (u_short)(cal.year + *cp++ - '0');
2051 * Catch special case. If cal.year == 0 this is a zero timestamp.
2053 if (cal.year == 0) {
2058 if (*cp++ != ' ' || !isdigit((int)*cp))
2060 cal.hour = (u_char)(*cp++ - '0');
2061 if (isdigit((int)*cp)) {
2062 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2063 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2066 if (*cp++ != ':' || !isdigit((int)*cp))
2068 cal.minute = (u_char)(*cp++ - '0');
2069 if (isdigit((int)*cp)) {
2070 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2071 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2074 if (*cp++ != ':' || !isdigit((int)*cp))
2076 cal.second = (u_char)(*cp++ - '0');
2077 if (isdigit((int)*cp)) {
2078 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2079 cal.second = (u_char)(cal.second + *cp++ - '0');
2083 * For RT-11, 1972 seems to be the pivot year
2090 lfp->l_ui = caltontp(&cal);
2097 * decodets - decode a timestamp into an l_fp format number, with
2098 * consideration of fuzzball formats.
2111 * If it starts with a 0x, decode as hex.
2113 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2114 return hextolfp(str+2, lfp);
2117 * If it starts with a '"', try it as an RT-11 date.
2122 while ('"' != *cp && '\0' != *cp &&
2123 b < COUNTOF(buf) - 1)
2126 return rtdatetolfp(buf, lfp);
2130 * Might still be hex. Check out the first character. Talk
2133 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2134 return hextolfp(str, lfp);
2137 * Try it as a decimal. If this fails, try as an unquoted
2138 * RT-11 date. This code should go away eventually.
2140 if (atolfp(str, lfp))
2143 return rtdatetolfp(str, lfp);
2148 * decodetime - decode a time value. It should be in milliseconds
2156 return mstolfp(str, lfp);
2161 * decodeint - decode an integer
2170 if (*(str+1) == 'x' || *(str+1) == 'X')
2171 return hextoint(str+2, (u_long *)val);
2172 return octtoint(str, (u_long *)val);
2174 return atoint(str, val);
2179 * decodeuint - decode an unsigned integer
2188 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2189 return (hextoint(str + 2, val));
2190 return (octtoint(str, val));
2192 return (atouint(str, val));
2197 * decodearr - decode an array of time values
2206 register char *cp, *bp;
2215 while (isspace((int)*cp))
2221 while (!isspace((int)*cp) && *cp != '\0')
2225 if (!decodetime(buf, lfp))
2235 * Finally, the built in command handlers
2239 * help - tell about commands, or details of a particular command
2247 struct xcmd *xcp = NULL; /* quiet warning */
2249 const char *list[100];
2255 if (pcmd->nargs == 0) {
2257 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2258 if (*(xcp->keyword) != '?' &&
2259 words < COUNTOF(list))
2260 list[words++] = xcp->keyword;
2262 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2263 if (words < COUNTOF(list))
2264 list[words++] = xcp->keyword;
2266 qsort((void *)list, words, sizeof(list[0]), helpsort);
2268 for (word = 0; word < words; word++) {
2269 length = strlen(list[word]);
2270 col = max(col, length);
2273 cols = SCREENWIDTH / ++col;
2274 rows = (words + cols - 1) / cols;
2276 fprintf(fp, "ntpq commands:\n");
2278 for (row = 0; row < rows; row++) {
2279 for (word = row; word < words; word += rows)
2280 fprintf(fp, "%-*.*s", (int)col,
2281 (int)col - 1, list[word]);
2285 cmd = pcmd->argval[0].string;
2286 words = findcmd(cmd, builtins, opcmds, &xcp);
2289 "Command `%s' is unknown\n", cmd);
2291 } else if (words >= 2) {
2293 "Command `%s' is ambiguous\n", cmd);
2296 fprintf(fp, "function: %s\n", xcp->comment);
2297 printusage(xcp, fp);
2303 * helpsort - do hostname qsort comparisons
2311 const char * const * name1 = t1;
2312 const char * const * name2 = t2;
2314 return strcmp(*name1, *name2);
2319 * printusage - print usage information for a command
2329 /* XXX: Do we need to warn about extra args here too? */
2331 (void) fprintf(fp, "usage: %s", xcp->keyword);
2332 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2333 if (xcp->arg[i] & OPT)
2334 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2336 (void) fprintf(fp, " %s", xcp->desc[i]);
2338 (void) fprintf(fp, "\n");
2343 * timeout - set time out time
2353 if (pcmd->nargs == 0) {
2354 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2355 (void) fprintf(fp, "primary timeout %d ms\n", val);
2357 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2358 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2365 * auth_delay - set delay for auth requests
2376 if (pcmd->nargs == 0) {
2377 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2378 (void) fprintf(fp, "delay %lu ms\n", val);
2380 if (pcmd->argval[0].ival < 0) {
2382 val = (u_long)(-pcmd->argval[0].ival);
2385 val = (u_long)pcmd->argval[0].ival;
2388 delay_time.l_ui = val / 1000;
2390 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2399 * host - set the host we are dealing with.
2409 if (pcmd->nargs == 0) {
2411 (void) fprintf(fp, "current host is %s\n",
2414 (void) fprintf(fp, "no current host\n");
2419 ai_fam_templ = ai_fam_default;
2420 if (pcmd->nargs == 2) {
2421 if (!strcmp("-4", pcmd->argval[i].string))
2422 ai_fam_templ = AF_INET;
2423 else if (!strcmp("-6", pcmd->argval[i].string))
2424 ai_fam_templ = AF_INET6;
2429 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2430 fprintf(fp, "current host set to %s\n", currenthost);
2434 fprintf(fp, "current host remains %s\n",
2437 fprintf(fp, "still no current host\n");
2443 * poll - do one (or more) polls of the host via NTP
2452 (void) fprintf(fp, "poll not implemented yet\n");
2457 * showdrefid2str - return a string explanation of the value of drefid
2460 showdrefid2str(void)
2474 * drefid - display/change "display hash"
2482 if (pcmd->nargs == 0) {
2483 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2485 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2486 drefid = REFID_HASH;
2487 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2488 drefid = REFID_IPV4;
2490 (void) fprintf(fp, "What?\n");
2493 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2498 * keyid - get a keyid to use for authenticating requests
2506 if (pcmd->nargs == 0) {
2507 if (info_auth_keyid == 0)
2508 (void) fprintf(fp, "no keyid defined\n");
2510 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2512 /* allow zero so that keyid can be cleared. */
2513 if(pcmd->argval[0].uval > NTP_MAXKEY)
2514 (void) fprintf(fp, "Invalid key identifier\n");
2515 info_auth_keyid = pcmd->argval[0].uval;
2520 * keytype - get type of key to use for authenticating requests
2528 const char * digest_name;
2533 fprintf(fp, "keytype is %s with %lu octet digests\n",
2534 keytype_name(info_auth_keytype),
2535 (u_long)info_auth_hashlen);
2539 digest_name = pcmd->argval[0].string;
2541 key_type = keytype_from_text(digest_name, &digest_len);
2544 fprintf(fp, "keytype is not valid. "
2546 "Type \"help keytype\" for the available digest types.\n");
2548 "Only \"md5\" is available.\n");
2553 info_auth_keytype = key_type;
2554 info_auth_hashlen = digest_len;
2559 * passwd - get an authentication key
2570 if (info_auth_keyid == 0) {
2571 info_auth_keyid = getkeyid("Keyid: ");
2572 if (info_auth_keyid == 0) {
2573 (void)fprintf(fp, "Keyid must be defined\n");
2577 if (pcmd->nargs >= 1)
2578 pass = pcmd->argval[0].string;
2580 pass = getpass_keytype(info_auth_keytype);
2581 if ('\0' == pass[0]) {
2582 fprintf(fp, "Password unchanged\n");
2586 authusekey(info_auth_keyid, info_auth_keytype,
2587 (const u_char *)pass);
2588 authtrust(info_auth_keyid, 1);
2593 * hostnames - set the showhostnames flag
2601 if (pcmd->nargs == 0) {
2603 (void) fprintf(fp, "hostnames being shown\n");
2605 (void) fprintf(fp, "hostnames not being shown\n");
2607 if (STREQ(pcmd->argval[0].string, "yes"))
2609 else if (STREQ(pcmd->argval[0].string, "no"))
2612 (void)fprintf(stderr, "What?\n");
2619 * setdebug - set/change debugging level
2627 if (pcmd->nargs == 0) {
2628 (void) fprintf(fp, "debug level is %d\n", debug);
2630 } else if (STREQ(pcmd->argval[0].string, "no")) {
2632 } else if (STREQ(pcmd->argval[0].string, "more")) {
2634 } else if (STREQ(pcmd->argval[0].string, "less")) {
2637 (void) fprintf(fp, "What?\n");
2640 (void) fprintf(fp, "debug level set to %d\n", debug);
2645 * quit - stop this nonsense
2655 closesocket(sockfd); /* cleanliness next to godliness */
2661 * version - print the current version number
2671 (void) fprintf(fp, "%s\n", Version);
2677 * raw - set raw mode output
2687 (void) fprintf(fp, "Output set to raw\n");
2692 * cooked - set cooked mode output
2702 (void) fprintf(fp, "Output set to cooked\n");
2708 * authenticate - always authenticate requests to this host
2716 if (pcmd->nargs == 0) {
2719 "authenticated requests being sent\n");
2722 "unauthenticated requests being sent\n");
2724 if (STREQ(pcmd->argval[0].string, "yes")) {
2726 } else if (STREQ(pcmd->argval[0].string, "no")) {
2729 (void)fprintf(stderr, "What?\n");
2735 * ntpversion - choose the NTP version to use
2743 if (pcmd->nargs == 0) {
2745 "NTP version being claimed is %d\n", pktversion);
2747 if (pcmd->argval[0].uval < NTP_OLDVERSION
2748 || pcmd->argval[0].uval > NTP_VERSION) {
2749 (void) fprintf(stderr, "versions %d to %d, please\n",
2750 NTP_OLDVERSION, NTP_VERSION);
2752 pktversion = (u_char) pcmd->argval[0].uval;
2758 static void __attribute__((__format__(__printf__, 1, 0)))
2759 vwarning(const char *fmt, va_list ap)
2762 (void) fprintf(stderr, "%s: ", progname);
2763 vfprintf(stderr, fmt, ap);
2764 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2768 * warning - print a warning message
2770 static void __attribute__((__format__(__printf__, 1, 2)))
2784 * error - print a message and exit
2786 static void __attribute__((__format__(__printf__, 1, 2)))
2799 * getkeyid - prompt the user for a keyid to use
2803 const char *keyprompt
2813 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2815 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2816 #endif /* SYS_WINNT */
2819 setbuf(fi, (char *)NULL);
2820 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2821 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2822 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2824 pbuf[i++] = (char)c;
2829 return (u_long) atoi(pbuf);
2834 * atoascii - printable-ize possibly ascii data using the character
2835 * transformations cat -v uses.
2845 const u_char * pchIn;
2846 const u_char * pchInLimit;
2850 pchIn = (const u_char *)in;
2851 pchInLimit = pchIn + in_octets;
2852 pchOut = (u_char *)out;
2854 if (NULL == pchIn) {
2862 if (0 == --out_octets) { \
2869 for ( ; pchIn < pchInLimit; pchIn++) {
2880 ONEOUT((u_char)(c + '@'));
2881 } else if (0x7f == c) {
2894 * makeascii - print possibly ascii data using the character
2895 * transformations that cat -v uses.
2904 const u_char *data_u_char;
2908 data_u_char = (const u_char *)data;
2910 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2921 } else if (0x7f == c) {
2931 * asciize - same thing as makeascii except add a newline
2940 makeascii(length, data, fp);
2946 * truncate string to fit clipping excess at end.
2947 * "too long" -> "too l"
2948 * Used for hostnames.
2961 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2963 memcpy(out, src, width);
2974 * truncate string to fit by preserving right side and using '_' to hint
2975 * "too long" -> "_long"
2976 * Used for local IPv6 addresses, where low bits differentiate.
2989 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2992 memcpy(&out[1], &src[sl + 1 - width], width);
3002 * Some circular buffer space
3007 char circ_buf[NUMCB][CBLEN];
3011 * nextvar - find the next variable in the buffer
3026 static char name[MAXVARLEN];
3027 static char value[MAXVALLEN];
3030 cpend = cp + *datalen;
3033 * Space past commas and white space
3035 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
3041 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
3042 * over any white space and terminate it.
3044 srclen = strcspn(cp, ",=\r\n");
3045 srclen = min(srclen, (size_t)(cpend - cp));
3047 while (len > 0 && isspace((unsigned char)cp[len - 1]))
3049 if (len >= sizeof(name))
3052 memcpy(name, cp, len);
3058 * Check if we hit the end of the buffer or a ','. If so we are done.
3060 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
3064 *datalen = size2int_sat(cpend - cp);
3070 * So far, so good. Copy out the value
3072 cp++; /* past '=' */
3073 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
3079 } while (np < cpend && '"' != *np);
3080 if (np < cpend && '"' == *np)
3083 while (np < cpend && ',' != *np && '\r' != *np)
3087 if (np > cpend || len >= sizeof(value) ||
3088 (np < cpend && ',' != *np && '\r' != *np))
3090 memcpy(value, cp, len);
3092 * Trim off any trailing whitespace
3094 while (len > 0 && isspace((unsigned char)value[len - 1]))
3099 * Return this. All done.
3101 if (np < cpend && ',' == *np)
3104 *datalen = size2int_sat(cpend - np);
3111 varfmt(const char * varname)
3115 for (n = 0; n < COUNTOF(cookedvars); n++)
3116 if (!strcmp(varname, cookedvars[n].varname))
3117 return cookedvars[n].fmt;
3124 * printvars - print variables returned in response packet
3137 rawprint(sttype, length, data, status, quiet, fp);
3139 cookedprint(sttype, length, data, status, quiet, fp);
3144 * rawprint - do a printout of the data in raw mode
3160 * Essentially print the data as is. We reformat unprintables, though.
3163 cpend = data + length;
3166 (void) fprintf(fp, "status=0x%04x,\n", status);
3168 while (cp < cpend) {
3171 * If this is a \r and the next character is a
3172 * \n, supress this, else pretty print it. Otherwise
3173 * just output the character.
3175 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3176 makeascii(1, cp, fp);
3177 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3180 makeascii(1, cp, fp);
3187 * Global data used by the cooked output routines
3189 int out_chars; /* number of characters output */
3190 int out_linecount; /* number of characters output on this line */
3194 * startoutput - get ready to do cooked output
3205 * output - output a variable=value combination
3216 /* strlen of "name=value" */
3217 len = size2int_sat(strlen(name) + 1 + strlen(value));
3219 if (out_chars != 0) {
3221 if ((out_linecount + len + 2) > MAXOUTLINE) {
3234 out_linecount += len;
3239 * endoutput - terminate a block of cooked output
3252 * outputarr - output an array of values
3270 * Hack to align delay and offset values
3272 for (i = (int)strlen(name); i < 11; i++)
3275 for (i = narr; i > 0; i--) {
3278 cp = lfptoms(lfp, 2);
3293 output(fp, name, buf);
3301 register char *cp, *s;
3304 register const char *sep;
3307 s = cp = circ_buf[nextcb];
3308 if (++nextcb >= NUMCB)
3310 cb = sizeof(circ_buf[0]);
3312 snprintf(cp, cb, "%02lx", val);
3316 strlcat(cp, " ok", cb);
3324 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3326 snprintf(cp, cb, "%s%s", sep,
3342 * cookedprint - output variables in cooked mode
3365 char bn[2 * MAXVARLEN];
3366 char bv[2 * MAXVALLEN];
3368 UNUSED_ARG(datatype);
3371 fprintf(fp, "status=%04x %s,\n", status,
3372 statustoa(datatype, status));
3375 while (nextvar(&length, &data, &name, &value)) {
3385 if (!decodets(value, &lfp))
3388 output(fp, name, prettydate(&lfp));
3391 case HA: /* fallthru */
3393 if (!decodenetnum(value, &hval)) {
3395 } else if (fmt == HA){
3396 output(fp, name, nntohost(&hval));
3398 output(fp, name, stoa(&hval));
3403 if (decodenetnum(value, &hval)) {
3404 if (ISREFCLOCKADR(&hval))
3408 output(fp, name, stoa(&hval));
3409 } else if (strlen(value) <= 4) {
3410 output(fp, name, value);
3417 if (!decodeuint(value, &uval) || uval > 3) {
3427 output(fp, name, b);
3432 if (!decodeuint(value, &uval)) {
3435 snprintf(b, sizeof(b), "%03lo", uval);
3436 output(fp, name, b);
3441 if (!decodearr(value, &narr, lfparr))
3444 outputarr(fp, name, narr, lfparr);
3448 if (!decodeuint(value, &uval))
3451 output(fp, name, tstflags(uval));
3455 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3461 if (output_raw != 0) {
3462 /* TALOS-CAN-0063: avoid buffer overrun */
3463 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3464 if (output_raw != '*') {
3465 atoascii(value, MAXVALLEN,
3466 bv, sizeof(bv) - 1);
3468 bv[len] = output_raw;
3471 atoascii(value, MAXVALLEN,
3482 * sortassoc - sort associations in the cache into ascending order
3488 qsort(assoc_cache, (size_t)numassoc,
3489 sizeof(assoc_cache[0]), &assoccmp);
3494 * assoccmp - compare two associations
3502 const struct association *ass1 = t1;
3503 const struct association *ass2 = t2;
3505 if (ass1->assid < ass2->assid)
3507 if (ass1->assid > ass2->assid)
3514 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3516 * The strategy is to add an assumed 4k page size at a time, leaving
3517 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3520 grow_assoc_cache(void)
3522 static size_t prior_sz;
3525 new_sz = prior_sz + 4 * 1024;
3526 if (0 == prior_sz) {
3527 new_sz -= 4 * sizeof(void *);
3529 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3531 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3536 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3538 * By default, autoopts loses the relative order of -c and -p options
3539 * on the command line. This routine replaces the default handler for
3540 * those routines and builds a list of commands to execute preserving
3544 ntpq_custom_opt_handler(
3549 switch (pOptDesc->optValue) {
3553 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3554 pOptDesc->optValue, pOptDesc->optValue);
3558 ADDCMD(pOptDesc->pzLastArg);
3567 * Obtain list of digest names
3571 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3577 #define K_PER_LINE 8
3578 #define K_NL_PFX_STR "\n "
3579 #define K_DELIM_STR ", "
3580 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3583 const char *name, *cp, **seen;
3584 struct hstate *hstate = arg;
3587 u_char digest[EVP_MAX_MD_SIZE];
3590 return; /* Ignore aliases */
3592 name = EVP_MD_name(m);
3594 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3596 for( cp = name; *cp; cp++ ) {
3600 len = (cp - name) + 1;
3602 /* There are duplicates. Discard if name has been seen. */
3604 for (seen = hstate->seen; *seen; seen++)
3605 if (!strcmp(*seen, name))
3607 n = (seen - hstate->seen) + 2;
3608 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3609 hstate->seen[n-2] = name;
3610 hstate->seen[n-1] = NULL;
3612 /* Discard MACs that NTP won't accept.
3613 * Keep this consistent with keytype_from_text() in ssl_init.c.
3616 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3617 EVP_DigestFinal(&ctx, digest, &digest_len);
3618 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3621 if (hstate->list != NULL)
3622 len += strlen(hstate->list);
3623 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3625 if (hstate->list == NULL) {
3626 hstate->list = (char *)emalloc(len);
3627 hstate->list[0] = '\0';
3629 hstate->list = (char *)erealloc(hstate->list, len);
3631 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3632 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3634 if (hstate->idx >= K_PER_LINE)
3642 static char *list_digest_names(void)
3647 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3648 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3650 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3653 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3657 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3658 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3661 list = (char *)emalloc(sizeof("md5"));
3662 strcpy(list, "md5");
3668 #define CTRLC_STACK_MAX 4
3669 static volatile size_t ctrlc_stack_len = 0;
3670 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3675 push_ctrl_c_handler(
3679 size_t size = ctrlc_stack_len;
3680 if (func && (size < CTRLC_STACK_MAX)) {
3681 ctrlc_stack[size] = func;
3682 ctrlc_stack_len = size + 1;
3693 size_t size = ctrlc_stack_len;
3696 if (func == NULL || func == ctrlc_stack[size]) {
3697 ctrlc_stack_len = size;
3707 size_t size = ctrlc_stack_len;
3709 if ((*ctrlc_stack[--size])())
3723 char * buf = emalloc(len);
3726 /* Note: we expect the memory allocation to fail long before the
3727 * increment in buffer size actually overflows.
3729 buf = (buf) ? erealloc(buf, len) : emalloc(len);
3732 prc = vsnprintf(buf, len, fmt, va);
3736 /* might be very old vsnprintf. Or actually MSVC... */
3740 if ((size_t)prc >= len) {
3741 /* at least we have the proper size now... */
3742 len = (size_t)prc + 1;
3745 if ((size_t)prc < (len - 32))
3746 buf = erealloc(buf, (size_t)prc + 1);