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"
37 #include "libssl_compat.h"
39 #include <ssl_applink.c>
41 #include "ntp_libopts.h"
44 #ifdef SYS_VXWORKS /* vxWorks needs mode flag -casey*/
45 # define open(name, flags) open(name, flags, 0777)
46 # define SERVER_PORT_NUM 123
49 /* we use COMMAND as an autogen keyword */
55 * Because we potentially understand a lot of commands we will run
56 * interactive if connected to a terminal.
58 int interactive = 0; /* set to 1 when we should prompt */
59 const char *prompt = "ntpq> "; /* prompt to ask him about */
62 * use old readvars behavior? --old-rv processing in ntpq resets
63 * this value based on the presence or absence of --old-rv. It is
64 * initialized to 1 here to maintain backward compatibility with
65 * libntpq clients such as ntpsnmpd, which are free to reset it as
71 * How should we display the refid?
72 * REFID_HASH, REFID_IPV4
79 s_char sys_precision; /* local clock precision (log2 s) */
82 * Keyid used for authenticated requests. Obtained on the fly.
84 u_long info_auth_keyid = 0;
86 static int info_auth_keytype = NID_md5; /* MD5 */
87 static size_t info_auth_hashlen = 16; /* MD5 */
88 u_long current_time; /* needed by authkeys; not used */
91 * Flag which indicates we should always send authenticated requests
96 * Flag which indicates raw mode output.
101 * Packet version number we use
103 u_char pktversion = NTP_OLDVERSION + 1;
106 * Don't jump if no set jmp.
108 volatile int jump = 0;
114 #define HA 1 /* host address */
115 #define NA 2 /* network address */
116 #define LP 3 /* leap (print in binary) */
117 #define RF 4 /* refid (sometimes string, sometimes not) */
118 #define AR 5 /* array of times */
119 #define FX 6 /* test flags */
120 #define TS 7 /* l_fp timestamp in hex */
121 #define OC 8 /* integer, print in octal */
122 #define EOV 255 /* end of table */
125 * For the most part ntpq simply displays what ntpd provides in the
126 * mostly plain-text mode 6 responses. A few variable names are by
127 * default "cooked" to provide more human-friendly output.
129 const var_format cookedvars[] = {
140 { "peeradr", HA }, /* compat with others */
143 { "filtoffset", AR },
145 { "filterror", AR }, /* compat with others */
153 static const char *tstflagnames[] = {
154 "pkt_dup", /* TEST1 */
155 "pkt_bogus", /* TEST2 */
156 "pkt_unsync", /* TEST3 */
157 "pkt_denied", /* TEST4 */
158 "pkt_auth", /* TEST5 */
159 "pkt_stratum", /* TEST6 */
160 "pkt_header", /* TEST7 */
161 "pkt_autokey", /* TEST8 */
162 "pkt_crypto", /* TEST9 */
163 "peer_stratum", /* TEST10 */
164 "peer_dist", /* TEST11 */
165 "peer_loop", /* TEST12 */
166 "peer_unreach" /* TEST13 */
170 int ntpqmain (int, char **);
172 * Built in command handler declarations
174 static int openhost (const char *, int);
175 static void dump_hex_printable(const void *, size_t);
176 static int sendpkt (void *, size_t);
177 static int getresponse (int, int, u_short *, size_t *, const char **, int);
178 static int sendrequest (int, associd_t, int, size_t, const char *);
179 static char * tstflags (u_long);
181 static void getcmds (void);
183 static int abortcmd (void);
184 #endif /* SYS_WINNT */
185 static void docmd (const char *);
186 static void tokenize (const char *, char **, int *);
187 static int getarg (const char *, int, arg_v *);
188 #endif /* BUILD_AS_LIB */
189 static int findcmd (const char *, struct xcmd *,
190 struct xcmd *, struct xcmd **);
191 static int rtdatetolfp (char *, l_fp *);
192 static int decodearr (char *, int *, l_fp *);
193 static void help (struct parse *, FILE *);
194 static int helpsort (const void *, const void *);
195 static void printusage (struct xcmd *, FILE *);
196 static void timeout (struct parse *, FILE *);
197 static void auth_delay (struct parse *, FILE *);
198 static void host (struct parse *, FILE *);
199 static void ntp_poll (struct parse *, FILE *);
200 static void keyid (struct parse *, FILE *);
201 static void keytype (struct parse *, FILE *);
202 static void passwd (struct parse *, FILE *);
203 static void hostnames (struct parse *, FILE *);
204 static void setdebug (struct parse *, FILE *);
205 static void quit (struct parse *, FILE *);
206 static void showdrefid (struct parse *, FILE *);
207 static void version (struct parse *, FILE *);
208 static void raw (struct parse *, FILE *);
209 static void cooked (struct parse *, FILE *);
210 static void authenticate (struct parse *, FILE *);
211 static void ntpversion (struct parse *, FILE *);
212 static void warning (const char *, ...)
213 __attribute__((__format__(__printf__, 1, 2)));
214 static void error (const char *, ...)
215 __attribute__((__format__(__printf__, 1, 2)));
216 static u_long getkeyid (const char *);
217 static void atoascii (const char *, size_t, char *, size_t);
218 static void cookedprint (int, size_t, const char *, int, int, FILE *);
219 static void rawprint (int, size_t, const char *, int, int, FILE *);
220 static void startoutput (void);
221 static void output (FILE *, const char *, const char *);
222 static void endoutput (FILE *);
223 static void outputarr (FILE *, char *, int, l_fp *);
224 static int assoccmp (const void *, const void *);
225 static void on_ctrlc (void);
226 u_short varfmt (const char *);
227 static int my_easprintf (char**, const char *, ...) NTP_PRINTF(2, 3);
228 void ntpq_custom_opt_handler (tOptions *, tOptDesc *);
231 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
232 static void list_md_fn(const EVP_MD *m, const char *from,
233 const char *to, void *arg );
236 static char *list_digest_names(void);
239 * Built-in commands we understand
241 struct xcmd builtins[] = {
242 { "?", help, { OPT|NTP_STR, NO, NO, NO },
243 { "command", "", "", "" },
244 "tell the use and syntax of commands" },
245 { "help", help, { OPT|NTP_STR, NO, NO, NO },
246 { "command", "", "", "" },
247 "tell the use and syntax of commands" },
248 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
249 { "msec", "", "", "" },
250 "set the primary receive time out" },
251 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
252 { "msec", "", "", "" },
253 "set the delay added to encryption time stamps" },
254 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
255 { "-4|-6", "hostname", "", "" },
256 "specify the host whose NTP server we talk to" },
257 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
258 { "n", "verbose", "", "" },
259 "poll an NTP server in client mode `n' times" },
260 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
262 "specify a password to use for authenticated requests"},
263 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
264 { "yes|no", "", "", "" },
265 "specify whether hostnames or net numbers are printed"},
266 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
267 { "no|more|less", "", "", "" },
268 "set/change debugging level" },
269 { "quit", quit, { NO, NO, NO, NO },
272 { "exit", quit, { NO, NO, NO, NO },
275 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
276 { "key#", "", "", "" },
277 "set keyid to use for authenticated requests" },
278 { "drefid", showdrefid, { OPT|NTP_STR, NO, NO, NO },
279 { "hash|ipv4", "", "", "" },
280 "display refid's as IPv4 or hash" },
281 { "version", version, { NO, NO, NO, NO },
283 "print version number" },
284 { "raw", raw, { NO, NO, NO, NO },
286 "do raw mode variable output" },
287 { "cooked", cooked, { NO, NO, NO, NO },
289 "do cooked mode variable output" },
290 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
291 { "yes|no", "", "", "" },
292 "always authenticate requests to this server" },
293 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
294 { "version number", "", "", "" },
295 "set the NTP version number to use for requests" },
296 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
297 { "key type %s", "", "", "" },
299 { 0, 0, { NO, NO, NO, NO },
300 { "", "", "", "" }, "" }
305 * Default values we use.
307 #define DEFHOST "localhost" /* default host name */
308 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
309 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
311 * Requests are automatically retried once, so total timeout with no
312 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
313 * extreme, a request eliciting 32 packets of responses each for some
314 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
315 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
316 * 93 seconds to fail each of two times, or 186 seconds.
317 * Some commands involve a series of requests, such as "peers" and
318 * "mrulist", so the cumulative timeouts are even longer for those.
320 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
321 #define LENHOSTNAME 256 /* host name is 256 characters long */
322 #define MAXCMDS 100 /* maximum commands on cmd line */
323 #define MAXHOSTS 200 /* maximum hosts on cmd line */
324 #define MAXLINE 512 /* maximum line length */
325 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
326 #define MAXVARLEN 256 /* maximum length of a variable name */
327 #define MAXVALLEN 2048 /* maximum length of a variable value */
328 #define MAXOUTLINE 72 /* maximum length of an output line */
329 #define SCREENWIDTH 76 /* nominal screen width in columns */
332 * Some variables used and manipulated locally
334 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
335 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
336 l_fp delay_time; /* delay time */
337 char currenthost[LENHOSTNAME]; /* current host name */
338 int currenthostisnum; /* is prior text from IP? */
339 struct sockaddr_in hostaddr; /* host address */
340 int showhostnames = 1; /* show host names by default */
341 int wideremote = 0; /* show wide remote names? */
343 int ai_fam_templ; /* address family */
344 int ai_fam_default; /* default address family */
345 SOCKET sockfd; /* fd socket is opened on */
346 int havehost = 0; /* set to 1 when host open */
348 struct servent *server_entry = NULL; /* server entry for ntp */
352 * Sequence number used for requests. It is incremented before
358 * Holds data returned from queries. Declare buffer long to be sure of
361 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
362 long pktdata[DATASIZE/sizeof(long)];
365 * assoc_cache[] is a dynamic array which allows references to
366 * associations using &1 ... &N for n associations, avoiding manual
367 * lookup of the current association IDs for a given ntpd. It also
368 * caches the status word for each association, retrieved incidentally.
370 struct association * assoc_cache;
371 u_int assoc_cache_slots;/* count of allocated array entries */
372 u_int numassoc; /* number of cached associations */
375 * For commands typed on the command line (with the -c option)
378 const char *ccmds[MAXCMDS];
379 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
382 * When multiple hosts are specified.
387 chost chosts[MAXHOSTS];
388 #define ADDHOST(cp) \
390 if (numhosts < MAXHOSTS) { \
391 chosts[numhosts].name = (cp); \
392 chosts[numhosts].fam = ai_fam_templ; \
398 * Macro definitions we use
400 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
401 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
402 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
405 * Jump buffer for longjumping back to the command level
407 jmp_buf interrupt_buf;
410 * Points at file being currently printed into
412 FILE *current_output;
415 * Command table imported from ntpdc_ops.c
417 extern struct xcmd opcmds[];
419 char const *progname;
421 #ifdef NO_MAIN_ALLOWED
423 CALL(ntpq,"ntpq",ntpqmain);
425 void clear_globals(void)
427 extern int ntp_optind;
428 showhostnames = 0; /* don'tshow host names by default */
430 server_entry = NULL; /* server entry for ntp */
431 havehost = 0; /* set to 1 when host open */
432 numassoc = 0; /* number of cached associations */
436 #endif /* !BUILD_AS_LIB */
437 #endif /* NO_MAIN_ALLOWED */
440 * main - parse arguments and handle options
442 #ifndef NO_MAIN_ALLOWED
449 return ntpqmain(argc, argv);
466 taskPrioritySet(taskIdSelf(), 100 );
470 delay_time.l_uf = DEFDELAY;
472 init_lib(); /* sets up ipv4_works, ipv6_works */
476 /* Check to see if we have IPv6. Otherwise default to IPv4 */
478 ai_fam_default = AF_INET;
480 /* Fixup keytype's help based on available digest names */
486 list = list_digest_names();
487 for (icmd = 0; icmd < sizeof(builtins)/sizeof(builtins[0]); icmd++) {
488 if (strcmp("keytype", builtins[icmd].keyword) == 0)
493 /* This should only "trip" if "keytype" is removed from builtins */
494 INSIST(icmd < sizeof(builtins)/sizeof(builtins[0]));
497 builtins[icmd].desc[0] = "digest-name";
499 "set key type to use for authenticated requests, one of:%s",
502 builtins[icmd].desc[0] = "md5";
504 "set key type to use for authenticated requests (%s)",
507 builtins[icmd].comment = msg;
514 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
520 * Process options other than -c and -p, which are specially
521 * handled by ntpq_custom_opt_handler().
524 debug = OPT_VALUE_SET_DEBUG_LEVEL;
527 ai_fam_templ = AF_INET;
528 else if (HAVE_OPT(IPV6))
529 ai_fam_templ = AF_INET6;
531 ai_fam_templ = ai_fam_default;
533 if (HAVE_OPT(INTERACTIVE))
536 if (HAVE_OPT(NUMERIC))
542 old_rv = HAVE_OPT(OLD_RV);
544 drefid = OPT_VALUE_REFID;
549 for (ihost = 0; ihost < (u_int)argc; ihost++) {
550 if ('-' == *argv[ihost]) {
552 // If I really cared I'd also check:
553 // 0 == argv[ihost][2]
555 // and there are other cases as well...
557 if ('4' == argv[ihost][1]) {
558 ai_fam_templ = AF_INET;
560 } else if ('6' == argv[ihost][1]) {
561 ai_fam_templ = AF_INET6;
564 // XXX Throw a usage error
567 ADDHOST(argv[ihost]);
571 if (numcmds == 0 && interactive == 0
572 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
576 set_ctrl_c_hook(on_ctrlc);
577 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
579 push_ctrl_c_handler(abortcmd);
580 #endif /* SYS_WINNT */
583 (void) openhost(chosts[0].name, chosts[0].fam);
586 for (ihost = 0; ihost < numhosts; ihost++) {
587 if (openhost(chosts[ihost].name, chosts[ihost].fam))
588 for (icmd = 0; icmd < numcmds; icmd++)
594 #endif /* SYS_WINNT */
597 #endif /* !BUILD_AS_LIB */
600 * openhost - open a socket to a host
608 const char svc[] = "ntp";
609 char temphost[LENHOSTNAME];
611 struct addrinfo hints, *ai;
614 register const char *cp;
615 char name[LENHOSTNAME];
618 * We need to get by the [] if they were entered
625 for (i = 0; *cp && *cp != ']'; cp++, i++)
636 * First try to resolve it as an ip address and if that fails,
637 * do a fullblown (dns) lookup. That way we only use the dns
638 * when it is needed and work around some implementations that
639 * will return an "IPv4-mapped IPv6 address" address if you
640 * give it an IPv4 address to lookup.
643 hints.ai_family = fam;
644 hints.ai_protocol = IPPROTO_UDP;
645 hints.ai_socktype = SOCK_DGRAM;
646 hints.ai_flags = Z_AI_NUMERICHOST;
649 a_info = getaddrinfo(hname, svc, &hints, &ai);
650 if (a_info == EAI_NONAME
652 || a_info == EAI_NODATA
655 hints.ai_flags = AI_CANONNAME;
657 hints.ai_flags |= AI_ADDRCONFIG;
659 a_info = getaddrinfo(hname, svc, &hints, &ai);
662 /* Some older implementations don't like AI_ADDRCONFIG. */
663 if (a_info == EAI_BADFLAGS) {
664 hints.ai_flags &= ~AI_ADDRCONFIG;
665 a_info = getaddrinfo(hname, svc, &hints, &ai);
669 fprintf(stderr, "%s\n", gai_strerror(a_info));
675 octets = min(sizeof(addr), ai->ai_addrlen);
676 memcpy(&addr, ai->ai_addr, octets);
678 if (ai->ai_canonname == NULL) {
679 strlcpy(temphost, stoa(&addr), sizeof(temphost));
680 currenthostisnum = TRUE;
682 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
683 currenthostisnum = FALSE;
687 printf("Opening host %s (%s)\n",
689 (ai->ai_family == AF_INET)
691 : (ai->ai_family == AF_INET6)
698 printf("Closing old host %s\n", currenthost);
702 strlcpy(currenthost, temphost, sizeof(currenthost));
704 /* port maps to the same location in both families */
705 s_port = NSRCPORT(&addr);
707 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
708 if (ai->ai_family == AF_INET)
709 *(struct sockaddr_in *)&hostaddr=
710 *((struct sockaddr_in *)ai->ai_addr);
712 *(struct sockaddr_in6 *)&hostaddr=
713 *((struct sockaddr_in6 *)ai->ai_addr);
714 #endif /* SYS_VXWORKS */
718 int optionValue = SO_SYNCHRONOUS_NONALERT;
721 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
722 (char *)&optionValue, sizeof(optionValue));
725 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
731 #endif /* SYS_WINNT */
733 sockfd = socket(ai->ai_family, ai->ai_socktype,
735 if (sockfd == INVALID_SOCKET) {
742 #ifdef NEED_RCVBUF_SLOP
744 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
745 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
746 &rbufsize, sizeof(int)) == -1)
754 (connect(sockfd, (struct sockaddr *)&hostaddr,
755 sizeof(hostaddr)) == -1)
757 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
758 ai->ai_addrlen) == -1)
759 #endif /* SYS_VXWORKS */
779 /* every line shows at most 16 bytes, so we need a buffer of
780 * 4 * 16 (2 xdigits, 1 char, one sep for xdigits)
781 * + 2 * 1 (block separators)
786 static const char s_xdig[16] = "0123456789ABCDEF";
790 const u_char * cdata = data;
794 memset(lbuf, ' ', sizeof(lbuf));
796 pptr = lbuf + 3*16 + 2;
798 rowlen = (len > 16) ? 16 : (int)len;
804 *xptr++ = s_xdig[ch >> 4 ];
805 *xptr++ = s_xdig[ch & 0x0F];
806 if (++xptr == lbuf + 3*8)
809 *pptr++ = isprint(ch) ? (char)ch : '.';
819 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
821 * sendpkt - send a packet to the remote host
830 printf("Sending %zu octets\n", xdatalen);
832 if (send(sockfd, xdata, xdatalen, 0) == -1) {
833 warning("write to %s failed", currenthost);
838 printf("Request packet:\n");
839 dump_hex_printable(xdata, xdatalen);
845 * getresponse - get a (series of) response packet(s) and return the data
857 struct ntp_control rpkt;
858 struct sock_timeval tvo;
859 u_short offsets[MAXFRAGS+1];
860 u_short counts[MAXFRAGS+1];
871 /* absolute timeout checks. Not 'time_t' by intention! */
872 uint32_t tobase; /* base value for timeout */
873 uint32_t tospan; /* timeout span (max delay) */
874 uint32_t todiff; /* current delay */
876 memset(offsets, 0, sizeof(offsets));
877 memset(counts , 0, sizeof(counts ));
880 * This is pretty tricky. We may get between 1 and MAXFRAG packets
881 * back in response to the request. We peel the data out of
882 * each packet and collect it in one long block. When the last
883 * packet in the sequence is received we'll know how much data we
884 * should have had. Note we use one long time out, should reconsider.
889 *rdata = (char *)pktdata;
894 tobase = (uint32_t)time(NULL);
899 * Loop until we have an error or a complete response. Nearly all
900 * code paths to loop again use continue.
908 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
910 FD_SET(sockfd, &fds);
911 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
913 #if !defined(SYS_WINNT) && defined(EINTR)
914 /* Windows does not know about EINTR (until very
915 * recently) and the handling of console events
916 * is *very* different from POSIX/UNIX signal
919 * Under non-windows targets we map EINTR as
920 * 'last packet was received' and try to exit
921 * the receive sequence.
923 if (errno == EINTR) {
928 warning("select fails");
933 * Check if this is already too late. Trash the data and
934 * fake a timeout if this is so.
936 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
937 if ((n > 0) && (todiff > tospan)) {
938 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
939 n -= n; /* faked timeout return from 'select()',
940 * execute RMW cycle on 'n'
946 * Timed out. Return what we have
951 "%s: timed out, nothing received\n",
957 "%s: timed out with incomplete data\n",
961 "ERR_INCOMPLETE: Received fragments:\n");
962 for (f = 0; f < numfrags; f++)
964 "%2u: %5d %5d\t%3d octets\n",
965 (u_int)f, offsets[f],
970 "last fragment %sreceived\n",
975 return ERR_INCOMPLETE;
978 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
985 printf("Response packet:\n");
986 dump_hex_printable(&rpkt, n);
990 * Check for format errors. Bug proofing.
992 if (n < (int)CTL_HEADER_LEN) {
994 printf("Short (%d byte) packet received\n", n);
997 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
998 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
1000 printf("Packet received with version %d\n",
1001 PKT_VERSION(rpkt.li_vn_mode));
1004 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
1006 printf("Packet received with mode %d\n",
1007 PKT_MODE(rpkt.li_vn_mode));
1010 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
1012 printf("Received request packet, wanted response\n");
1017 * Check opcode and sequence number for a match.
1018 * Could be old data getting to us.
1020 if (ntohs(rpkt.sequence) != sequence) {
1022 printf("Received sequnce number %d, wanted %d\n",
1023 ntohs(rpkt.sequence), sequence);
1026 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1029 "Received opcode %d, wanted %d (sequence number okay)\n",
1030 CTL_OP(rpkt.r_m_e_op), opcode);
1035 * Check the error code. If non-zero, return it.
1037 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1038 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1039 if (CTL_ISMORE(rpkt.r_m_e_op))
1040 TRACE(1, ("Error code %d received on not-final packet\n",
1042 if (errcode == CERR_UNSPEC)
1048 * Check the association ID to make sure it matches what
1051 if (ntohs(rpkt.associd) != associd) {
1052 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1053 ntohs(rpkt.associd), associd));
1055 * Hack for silly fuzzballs which, at the time of writing,
1056 * return an assID of sys.peer when queried for system variables.
1064 * Collect offset and count. Make sure they make sense.
1066 offset = ntohs(rpkt.offset);
1067 count = ntohs(rpkt.count);
1070 * validate received payload size is padded to next 32-bit
1071 * boundary and no smaller than claimed by rpkt.count
1074 TRACE(1, ("Response packet not padded, size = %d\n",
1079 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1081 if (n < shouldbesize) {
1082 printf("Response packet claims %u octets payload, above %ld received\n",
1083 count, (long)(n - CTL_HEADER_LEN));
1084 return ERR_INCOMPLETE;
1087 if (debug >= 3 && shouldbesize > n) {
1093 * Usually we ignore authentication, but for debugging purposes
1096 /* round to 8 octet boundary */
1097 shouldbesize = (shouldbesize + 7) & ~7;
1099 maclen = n - shouldbesize;
1100 if (maclen >= (int)MIN_MAC_LEN) {
1102 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1103 n, shouldbesize, maclen);
1104 lpkt = (u_int32 *)&rpkt;
1105 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1106 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1107 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1108 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1109 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1110 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1111 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1112 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1113 printf("Authenticated with keyid %lu\n", (u_long)key);
1114 if (key != 0 && key != info_auth_keyid) {
1115 printf("We don't know that key\n");
1117 if (authdecrypt(key, (u_int32 *)&rpkt,
1118 n - maclen, maclen)) {
1119 printf("Auth okay!\n");
1121 printf("Auth failed!\n");
1127 TRACE(2, ("Got packet, size = %d\n", n));
1128 if (count > (n - CTL_HEADER_LEN)) {
1129 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1130 count, (long)n - CTL_HEADER_LEN));
1133 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1134 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1137 if (offset + count > sizeof(pktdata)) {
1138 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1142 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1143 TRACE(1, ("Received second last fragment packet\n"));
1148 * So far, so good. Record this fragment, making sure it doesn't
1151 TRACE(2, ("Packet okay\n"));
1153 if (numfrags > (MAXFRAGS - 1)) {
1154 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1160 * Find the position for the fragment relative to any
1161 * previously received.
1164 f < numfrags && offsets[f] < offset;
1169 if (f < numfrags && offset == offsets[f]) {
1170 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1171 count, offset, counts[f], offsets[f]));
1175 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1176 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1177 offset, counts[f-1], offsets[f-1]));
1181 if (f < numfrags && (offset + count) > offsets[f]) {
1182 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1183 count, offset, offsets[f]));
1187 for (ff = numfrags; ff > f; ff--) {
1188 offsets[ff] = offsets[ff-1];
1189 counts[ff] = counts[ff-1];
1191 offsets[f] = offset;
1196 * Got that stuffed in right. Figure out if this was the last.
1197 * Record status info out of the last packet.
1199 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1202 *rstatus = ntohs(rpkt.status);
1206 * Copy the data into the data buffer, and bump the
1207 * timout base in case we need more.
1209 memcpy((char *)pktdata + offset, &rpkt.u, count);
1210 tobase = (uint32_t)time(NULL);
1213 * If we've seen the last fragment, look for holes in the sequence.
1214 * If there aren't any, we're done.
1216 #if !defined(SYS_WINNT) && defined(EINTR)
1220 if (seenlastfrag && offsets[0] == 0) {
1221 for (f = 1; f < numfrags; f++)
1222 if (offsets[f-1] + counts[f-1] !=
1225 if (f == numfrags) {
1226 *rsize = offsets[f-1] + counts[f-1];
1227 TRACE(1, ("%lu packets reassembled into response\n",
1232 } /* giant for (;;) collecting response packets */
1233 } /* getresponse() */
1237 * sendrequest - format and send a request packet
1248 struct ntp_control qpkt;
1255 * Check to make sure the data will fit in one packet
1257 if (qsize > CTL_MAX_DATA_LEN) {
1259 "***Internal error! qsize (%zu) too large\n",
1265 * Fill in the packet
1267 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1268 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1269 qpkt.sequence = htons(sequence);
1271 qpkt.associd = htons((u_short)associd);
1273 qpkt.count = htons((u_short)qsize);
1275 pktsize = CTL_HEADER_LEN;
1278 * If we have data, copy and pad it out to a 32-bit boundary.
1281 memcpy(&qpkt.u, qdata, (size_t)qsize);
1283 while (pktsize & (sizeof(u_int32) - 1)) {
1284 qpkt.u.data[qsize++] = 0;
1290 * If it isn't authenticated we can just send it. Otherwise
1291 * we're going to have to think about it a little.
1293 if (!auth && !always_auth) {
1294 return sendpkt(&qpkt, pktsize);
1298 * Pad out packet to a multiple of 8 octets to be sure
1299 * receiver can handle it.
1301 while (pktsize & 7) {
1302 qpkt.u.data[qsize++] = 0;
1307 * Get the keyid and the password if we don't have one.
1309 if (info_auth_keyid == 0) {
1310 key_id = getkeyid("Keyid: ");
1311 if (key_id == 0 || key_id > NTP_MAXKEY) {
1313 "Invalid key identifier\n");
1316 info_auth_keyid = key_id;
1318 if (!authistrusted(info_auth_keyid)) {
1319 pass = getpass_keytype(info_auth_keytype);
1320 if ('\0' == pass[0]) {
1321 fprintf(stderr, "Invalid password\n");
1324 authusekey(info_auth_keyid, info_auth_keytype,
1326 authtrust(info_auth_keyid, 1);
1330 * Do the encryption.
1332 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1334 fprintf(stderr, "Key not found\n");
1336 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1338 "%zu octet MAC, %zu expected with %zu octet digest\n",
1339 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1344 return sendpkt((char *)&qpkt, pktsize + maclen);
1349 * show_error_msg - display the error text for a mode 6 error response.
1358 fprintf(stderr, "server=%s ", currenthost);
1364 "***Server reports a bad format request packet\n");
1367 case CERR_PERMISSION:
1369 "***Server disallowed request (authentication?)\n");
1374 "***Server reports a bad opcode in request\n");
1379 "***Association ID %d unknown to server\n",
1383 case CERR_UNKNOWNVAR:
1385 "***A request variable unknown to the server\n");
1390 "***Server indicates a request variable was bad\n");
1395 "***Server returned an unspecified error\n");
1399 fprintf(stderr, "***Request timed out\n");
1402 case ERR_INCOMPLETE:
1404 "***Response from server was incomplete\n");
1409 "***Buffer size exceeded for returned data\n");
1414 "***Server returns unknown error code %d\n",
1420 * doquery - send a request and process the response, displaying
1421 * error messages for any error responses.
1435 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1436 rsize, rdata, FALSE);
1441 * doqueryex - send a request and process the response, optionally
1442 * displaying error messages for any error responses.
1461 * Check to make sure host is open
1464 fprintf(stderr, "***No host open, use `host' command\n");
1475 res = sendrequest(opcode, associd, auth, qsize, qdata);
1480 * Get the response. If we got a standard error, print a message
1482 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1485 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1486 if (res == ERR_INCOMPLETE) {
1488 * better bump the sequence so we don't
1489 * get confused about differing fragments.
1497 show_error_msg(res, associd);
1504 #ifndef BUILD_AS_LIB
1506 * getcmds - read commands from the standard input and execute them
1514 ntp_readline_init(interactive ? prompt : NULL);
1517 line = ntp_readline(&count);
1524 ntp_readline_uninit();
1526 #endif /* !BUILD_AS_LIB */
1529 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1531 * abortcmd - catch interrupts and abort the current command
1536 if (current_output == stdout)
1537 (void) fflush(stdout);
1539 (void) fflush(stderr);
1542 longjmp(interrupt_buf, 1);
1546 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1549 #ifndef BUILD_AS_LIB
1551 * docmd - decode the command line and execute a command
1558 char *tokens[1+MAXARGS+2];
1565 * Tokenize the command line. If nothing on it, return.
1567 tokenize(cmdline, tokens, &ntok);
1572 * Find the appropriate command description.
1574 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1576 (void) fprintf(stderr, "***Command `%s' unknown\n",
1579 } else if (i >= 2) {
1580 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1585 /* Warn about ignored extra args */
1586 for (i = MAXARGS + 1; i < ntok ; ++i) {
1587 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1591 * Save the keyword, then walk through the arguments, interpreting
1594 pcmd.keyword = tokens[0];
1596 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1597 if ((i+1) >= ntok) {
1598 if (!(xcmd->arg[i] & OPT)) {
1599 printusage(xcmd, stderr);
1604 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1606 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1612 if (i < ntok && *tokens[i] == '>') {
1615 if (*(tokens[i]+1) != '\0')
1616 fname = tokens[i]+1;
1617 else if ((i+1) < ntok)
1618 fname = tokens[i+1];
1620 (void) fprintf(stderr, "***No file for redirect\n");
1624 current_output = fopen(fname, "w");
1625 if (current_output == NULL) {
1626 (void) fprintf(stderr, "***Error opening %s: ", fname);
1630 i = 1; /* flag we need a close */
1632 current_output = stdout;
1633 i = 0; /* flag no close */
1636 if (interactive && setjmp(interrupt_buf)) {
1641 (xcmd->handler)(&pcmd, current_output);
1642 jump = 0; /* HMS: 961106: was after fclose() */
1643 if (i) (void) fclose(current_output);
1651 * tokenize - turn a command line into tokens
1653 * SK: Modified to allow a quoted string
1655 * HMS: If the first character of the first token is a ':' then (after
1656 * eating inter-token whitespace) the 2nd token is the rest of the line.
1666 register const char *cp;
1668 static char tspace[MAXLINE];
1672 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1675 /* Skip inter-token whitespace */
1676 while (ISSPACE(*cp))
1679 /* If we're at EOL we're done */
1683 /* If this is the 2nd token and the first token begins
1684 * with a ':', then just grab to EOL.
1687 if (*ntok == 1 && tokens[0][0] == ':') {
1689 if (sp - tspace >= MAXLINE)
1692 } while (!ISEOL(*cp));
1695 /* Check if this token begins with a double quote.
1696 * If yes, continue reading till the next double quote
1698 else if (*cp == '\"') {
1701 if (sp - tspace >= MAXLINE)
1704 } while ((*cp != '\"') && !ISEOL(*cp));
1705 /* HMS: a missing closing " should be an error */
1709 if (sp - tspace >= MAXLINE)
1712 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1713 /* HMS: Why check for a " in the previous line? */
1716 if (sp - tspace >= MAXLINE)
1725 "***Line `%s' is too big\n",
1732 * getarg - interpret an argument token
1743 switch (code & ~OPT) {
1749 if (!getnetnum(str, &argp->netnum, NULL, 0))
1754 if ('&' == str[0]) {
1755 if (!atouint(&str[1], &ul)) {
1757 "***Association index `%s' invalid/undecodable\n",
1761 if (0 == numassoc) {
1763 if (0 == numassoc) {
1765 "***No associations found, `%s' unknown\n",
1770 ul = min(ul, numassoc);
1771 argp->uval = assoc_cache[ul - 1].assid;
1774 if (!atouint(str, &argp->uval)) {
1775 fprintf(stderr, "***Illegal unsigned value %s\n",
1782 if (!atoint(str, &argp->ival)) {
1783 fprintf(stderr, "***Illegal integer value %s\n",
1790 if (!strcmp("-6", str)) {
1792 } else if (!strcmp("-4", str)) {
1795 fprintf(stderr, "***Version must be either 4 or 6\n");
1803 #endif /* !BUILD_AS_LIB */
1807 * findcmd - find a command in a command description table
1812 struct xcmd * clist1,
1813 struct xcmd * clist2,
1820 struct xcmd *nearmatch = NULL;
1827 else if (clist2 != 0)
1833 for (cl = clist; cl->keyword != 0; cl++) {
1834 /* do a first character check, for efficiency */
1835 if (*str != *(cl->keyword))
1837 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1839 * Could be extact match, could be approximate.
1840 * Is exact if the length of the keyword is the
1843 if (*((cl->keyword) + clen) == '\0') {
1853 * See if there is more to do. If so, go again. Sorry about the
1854 * goto, too much looking at BSD sources...
1856 if (clist == clist1 && clist2 != 0) {
1862 * If we got extactly 1 near match, use it, else return number
1874 * getnetnum - given a host name, return its net number
1875 * and (optional) full name
1885 struct addrinfo hints, *ai = NULL;
1888 hints.ai_flags = AI_CANONNAME;
1889 #ifdef AI_ADDRCONFIG
1890 hints.ai_flags |= AI_ADDRCONFIG;
1894 * decodenetnum only works with addresses, but handles syntax
1895 * that getaddrinfo doesn't: [2001::1]:1234
1897 if (decodenetnum(hname, num)) {
1898 if (fullhost != NULL)
1899 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1900 LENHOSTNAME, NULL, 0, 0);
1902 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1903 INSIST(sizeof(*num) >= ai->ai_addrlen);
1904 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1905 if (fullhost != NULL) {
1906 if (ai->ai_canonname != NULL)
1907 strlcpy(fullhost, ai->ai_canonname,
1910 getnameinfo(&num->sa, SOCKLEN(num),
1911 fullhost, LENHOSTNAME, NULL,
1917 fprintf(stderr, "***Can't find host %s\n", hname);
1924 * nntohost - convert network number to host name. This routine enforces
1925 * the showhostnames setting.
1932 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1937 * nntohost_col - convert network number to host name in fixed width.
1938 * This routine enforces the showhostnames setting.
1939 * When displaying hostnames longer than the width,
1940 * the first part of the hostname is displayed. When
1941 * displaying numeric addresses longer than the width,
1942 * Such as IPv6 addresses, the caller decides whether
1943 * the first or last of the numeric address is used.
1949 int preserve_lowaddrbits
1954 if (!showhostnames || SOCK_UNSPEC(addr)) {
1955 if (preserve_lowaddrbits)
1956 out = trunc_left(stoa(addr), width);
1958 out = trunc_right(stoa(addr), width);
1959 } else if (ISREFCLOCKADR(addr)) {
1960 out = refnumtoa(addr);
1962 out = trunc_right(socktohost(addr), width);
1969 * nntohostp() is the same as nntohost() plus a :port suffix
1979 if (!showhostnames || SOCK_UNSPEC(netnum))
1980 return sptoa(netnum);
1981 else if (ISREFCLOCKADR(netnum))
1982 return refnumtoa(netnum);
1984 hostn = socktohost(netnum);
1986 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1992 * rtdatetolfp - decode an RT-11 date into an l_fp
2002 struct calendar cal;
2008 * An RT-11 date looks like:
2010 * d[d]-Mth-y[y] hh:mm:ss
2012 * (No docs, but assume 4-digit years are also legal...)
2014 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
2017 if (!isdigit((int)*cp)) {
2020 * Catch special case
2028 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2029 if (isdigit((int)*cp)) {
2030 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2031 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2037 for (i = 0; i < 3; i++)
2041 for (i = 0; i < 12; i++)
2042 if (STREQ(buf, months[i]))
2046 cal.month = (u_char)(i + 1);
2051 if (!isdigit((int)*cp))
2053 cal.year = (u_short)(*cp++ - '0');
2054 if (isdigit((int)*cp)) {
2055 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2056 cal.year = (u_short)(*cp++ - '0');
2058 if (isdigit((int)*cp)) {
2059 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2060 cal.year = (u_short)(cal.year + *cp++ - '0');
2062 if (isdigit((int)*cp)) {
2063 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2064 cal.year = (u_short)(cal.year + *cp++ - '0');
2068 * Catch special case. If cal.year == 0 this is a zero timestamp.
2070 if (cal.year == 0) {
2075 if (*cp++ != ' ' || !isdigit((int)*cp))
2077 cal.hour = (u_char)(*cp++ - '0');
2078 if (isdigit((int)*cp)) {
2079 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2080 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2083 if (*cp++ != ':' || !isdigit((int)*cp))
2085 cal.minute = (u_char)(*cp++ - '0');
2086 if (isdigit((int)*cp)) {
2087 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2088 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2091 if (*cp++ != ':' || !isdigit((int)*cp))
2093 cal.second = (u_char)(*cp++ - '0');
2094 if (isdigit((int)*cp)) {
2095 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2096 cal.second = (u_char)(cal.second + *cp++ - '0');
2100 * For RT-11, 1972 seems to be the pivot year
2107 lfp->l_ui = caltontp(&cal);
2114 * decodets - decode a timestamp into an l_fp format number, with
2115 * consideration of fuzzball formats.
2128 * If it starts with a 0x, decode as hex.
2130 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2131 return hextolfp(str+2, lfp);
2134 * If it starts with a '"', try it as an RT-11 date.
2139 while ('"' != *cp && '\0' != *cp &&
2140 b < COUNTOF(buf) - 1)
2143 return rtdatetolfp(buf, lfp);
2147 * Might still be hex. Check out the first character. Talk
2150 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2151 return hextolfp(str, lfp);
2154 * Try it as a decimal. If this fails, try as an unquoted
2155 * RT-11 date. This code should go away eventually.
2157 if (atolfp(str, lfp))
2160 return rtdatetolfp(str, lfp);
2165 * decodetime - decode a time value. It should be in milliseconds
2173 return mstolfp(str, lfp);
2178 * decodeint - decode an integer
2187 if (*(str+1) == 'x' || *(str+1) == 'X')
2188 return hextoint(str+2, (u_long *)val);
2189 return octtoint(str, (u_long *)val);
2191 return atoint(str, val);
2196 * decodeuint - decode an unsigned integer
2205 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2206 return (hextoint(str + 2, val));
2207 return (octtoint(str, val));
2209 return (atouint(str, val));
2214 * decodearr - decode an array of time values
2223 register char *cp, *bp;
2232 while (isspace((int)*cp))
2238 while (!isspace((int)*cp) && *cp != '\0')
2242 if (!decodetime(buf, lfp))
2252 * Finally, the built in command handlers
2256 * help - tell about commands, or details of a particular command
2264 struct xcmd *xcp = NULL; /* quiet warning */
2266 const char *list[100];
2272 if (pcmd->nargs == 0) {
2274 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2275 if (*(xcp->keyword) != '?' &&
2276 words < COUNTOF(list))
2277 list[words++] = xcp->keyword;
2279 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2280 if (words < COUNTOF(list))
2281 list[words++] = xcp->keyword;
2283 qsort((void *)list, words, sizeof(list[0]), helpsort);
2285 for (word = 0; word < words; word++) {
2286 length = strlen(list[word]);
2287 col = max(col, length);
2290 cols = SCREENWIDTH / ++col;
2291 rows = (words + cols - 1) / cols;
2293 fprintf(fp, "ntpq commands:\n");
2295 for (row = 0; row < rows; row++) {
2296 for (word = row; word < words; word += rows)
2297 fprintf(fp, "%-*.*s", (int)col,
2298 (int)col - 1, list[word]);
2302 cmd = pcmd->argval[0].string;
2303 words = findcmd(cmd, builtins, opcmds, &xcp);
2306 "Command `%s' is unknown\n", cmd);
2308 } else if (words >= 2) {
2310 "Command `%s' is ambiguous\n", cmd);
2313 fprintf(fp, "function: %s\n", xcp->comment);
2314 printusage(xcp, fp);
2320 * helpsort - do hostname qsort comparisons
2328 const char * const * name1 = t1;
2329 const char * const * name2 = t2;
2331 return strcmp(*name1, *name2);
2336 * printusage - print usage information for a command
2346 /* XXX: Do we need to warn about extra args here too? */
2348 (void) fprintf(fp, "usage: %s", xcp->keyword);
2349 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2350 if (xcp->arg[i] & OPT)
2351 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2353 (void) fprintf(fp, " %s", xcp->desc[i]);
2355 (void) fprintf(fp, "\n");
2360 * timeout - set time out time
2370 if (pcmd->nargs == 0) {
2371 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2372 (void) fprintf(fp, "primary timeout %d ms\n", val);
2374 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2375 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2382 * auth_delay - set delay for auth requests
2393 if (pcmd->nargs == 0) {
2394 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2395 (void) fprintf(fp, "delay %lu ms\n", val);
2397 if (pcmd->argval[0].ival < 0) {
2399 val = (u_long)(-pcmd->argval[0].ival);
2402 val = (u_long)pcmd->argval[0].ival;
2405 delay_time.l_ui = val / 1000;
2407 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2416 * host - set the host we are dealing with.
2426 if (pcmd->nargs == 0) {
2428 (void) fprintf(fp, "current host is %s\n",
2431 (void) fprintf(fp, "no current host\n");
2436 ai_fam_templ = ai_fam_default;
2437 if (pcmd->nargs == 2) {
2438 if (!strcmp("-4", pcmd->argval[i].string))
2439 ai_fam_templ = AF_INET;
2440 else if (!strcmp("-6", pcmd->argval[i].string))
2441 ai_fam_templ = AF_INET6;
2446 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2447 fprintf(fp, "current host set to %s\n", currenthost);
2451 fprintf(fp, "current host remains %s\n",
2454 fprintf(fp, "still no current host\n");
2460 * poll - do one (or more) polls of the host via NTP
2469 (void) fprintf(fp, "poll not implemented yet\n");
2474 * showdrefid2str - return a string explanation of the value of drefid
2477 showdrefid2str(void)
2491 * drefid - display/change "display hash"
2499 if (pcmd->nargs == 0) {
2500 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2502 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2503 drefid = REFID_HASH;
2504 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2505 drefid = REFID_IPV4;
2507 (void) fprintf(fp, "What?\n");
2510 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2515 * keyid - get a keyid to use for authenticating requests
2523 if (pcmd->nargs == 0) {
2524 if (info_auth_keyid == 0)
2525 (void) fprintf(fp, "no keyid defined\n");
2527 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2529 /* allow zero so that keyid can be cleared. */
2530 if(pcmd->argval[0].uval > NTP_MAXKEY)
2531 (void) fprintf(fp, "Invalid key identifier\n");
2532 info_auth_keyid = pcmd->argval[0].uval;
2537 * keytype - get type of key to use for authenticating requests
2545 const char * digest_name;
2550 fprintf(fp, "keytype is %s with %lu octet digests\n",
2551 keytype_name(info_auth_keytype),
2552 (u_long)info_auth_hashlen);
2556 digest_name = pcmd->argval[0].string;
2558 key_type = keytype_from_text(digest_name, &digest_len);
2561 fprintf(fp, "keytype is not valid. "
2563 "Type \"help keytype\" for the available digest types.\n");
2565 "Only \"md5\" is available.\n");
2570 info_auth_keytype = key_type;
2571 info_auth_hashlen = digest_len;
2576 * passwd - get an authentication key
2587 if (info_auth_keyid == 0) {
2588 info_auth_keyid = getkeyid("Keyid: ");
2589 if (info_auth_keyid == 0) {
2590 (void)fprintf(fp, "Keyid must be defined\n");
2594 if (pcmd->nargs >= 1)
2595 pass = pcmd->argval[0].string;
2597 pass = getpass_keytype(info_auth_keytype);
2598 if ('\0' == pass[0]) {
2599 fprintf(fp, "Password unchanged\n");
2603 authusekey(info_auth_keyid, info_auth_keytype,
2604 (const u_char *)pass);
2605 authtrust(info_auth_keyid, 1);
2610 * hostnames - set the showhostnames flag
2618 if (pcmd->nargs == 0) {
2620 (void) fprintf(fp, "hostnames being shown\n");
2622 (void) fprintf(fp, "hostnames not being shown\n");
2624 if (STREQ(pcmd->argval[0].string, "yes"))
2626 else if (STREQ(pcmd->argval[0].string, "no"))
2629 (void)fprintf(stderr, "What?\n");
2636 * setdebug - set/change debugging level
2644 if (pcmd->nargs == 0) {
2645 (void) fprintf(fp, "debug level is %d\n", debug);
2647 } else if (STREQ(pcmd->argval[0].string, "no")) {
2649 } else if (STREQ(pcmd->argval[0].string, "more")) {
2651 } else if (STREQ(pcmd->argval[0].string, "less")) {
2654 (void) fprintf(fp, "What?\n");
2657 (void) fprintf(fp, "debug level set to %d\n", debug);
2662 * quit - stop this nonsense
2672 closesocket(sockfd); /* cleanliness next to godliness */
2678 * version - print the current version number
2688 (void) fprintf(fp, "%s\n", Version);
2694 * raw - set raw mode output
2704 (void) fprintf(fp, "Output set to raw\n");
2709 * cooked - set cooked mode output
2719 (void) fprintf(fp, "Output set to cooked\n");
2725 * authenticate - always authenticate requests to this host
2733 if (pcmd->nargs == 0) {
2736 "authenticated requests being sent\n");
2739 "unauthenticated requests being sent\n");
2741 if (STREQ(pcmd->argval[0].string, "yes")) {
2743 } else if (STREQ(pcmd->argval[0].string, "no")) {
2746 (void)fprintf(stderr, "What?\n");
2752 * ntpversion - choose the NTP version to use
2760 if (pcmd->nargs == 0) {
2762 "NTP version being claimed is %d\n", pktversion);
2764 if (pcmd->argval[0].uval < NTP_OLDVERSION
2765 || pcmd->argval[0].uval > NTP_VERSION) {
2766 (void) fprintf(stderr, "versions %d to %d, please\n",
2767 NTP_OLDVERSION, NTP_VERSION);
2769 pktversion = (u_char) pcmd->argval[0].uval;
2775 static void __attribute__((__format__(__printf__, 1, 0)))
2776 vwarning(const char *fmt, va_list ap)
2779 (void) fprintf(stderr, "%s: ", progname);
2780 vfprintf(stderr, fmt, ap);
2781 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2785 * warning - print a warning message
2787 static void __attribute__((__format__(__printf__, 1, 2)))
2801 * error - print a message and exit
2803 static void __attribute__((__format__(__printf__, 1, 2)))
2816 * getkeyid - prompt the user for a keyid to use
2820 const char *keyprompt
2830 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2832 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2833 #endif /* SYS_WINNT */
2836 setbuf(fi, (char *)NULL);
2837 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2838 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2839 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2841 pbuf[i++] = (char)c;
2846 return (u_long) atoi(pbuf);
2851 * atoascii - printable-ize possibly ascii data using the character
2852 * transformations cat -v uses.
2862 const u_char * pchIn;
2863 const u_char * pchInLimit;
2867 pchIn = (const u_char *)in;
2868 pchInLimit = pchIn + in_octets;
2869 pchOut = (u_char *)out;
2871 if (NULL == pchIn) {
2879 if (0 == --out_octets) { \
2886 for ( ; pchIn < pchInLimit; pchIn++) {
2897 ONEOUT((u_char)(c + '@'));
2898 } else if (0x7f == c) {
2911 * makeascii - print possibly ascii data using the character
2912 * transformations that cat -v uses.
2921 const u_char *data_u_char;
2925 data_u_char = (const u_char *)data;
2927 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2938 } else if (0x7f == c) {
2948 * asciize - same thing as makeascii except add a newline
2957 makeascii(length, data, fp);
2963 * truncate string to fit clipping excess at end.
2964 * "too long" -> "too l"
2965 * Used for hostnames.
2978 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2980 memcpy(out, src, width);
2991 * truncate string to fit by preserving right side and using '_' to hint
2992 * "too long" -> "_long"
2993 * Used for local IPv6 addresses, where low bits differentiate.
3006 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
3009 memcpy(&out[1], &src[sl + 1 - width], width);
3019 * Some circular buffer space
3024 char circ_buf[NUMCB][CBLEN];
3028 * nextvar - find the next variable in the buffer
3043 static char name[MAXVARLEN];
3044 static char value[MAXVALLEN];
3047 cpend = cp + *datalen;
3050 * Space past commas and white space
3052 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
3058 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
3059 * over any white space and terminate it.
3061 srclen = strcspn(cp, ",=\r\n");
3062 srclen = min(srclen, (size_t)(cpend - cp));
3064 while (len > 0 && isspace((unsigned char)cp[len - 1]))
3066 if (len >= sizeof(name))
3069 memcpy(name, cp, len);
3075 * Check if we hit the end of the buffer or a ','. If so we are done.
3077 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
3081 *datalen = size2int_sat(cpend - cp);
3087 * So far, so good. Copy out the value
3089 cp++; /* past '=' */
3090 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
3096 } while (np < cpend && '"' != *np);
3097 if (np < cpend && '"' == *np)
3100 while (np < cpend && ',' != *np && '\r' != *np)
3104 if (np > cpend || len >= sizeof(value) ||
3105 (np < cpend && ',' != *np && '\r' != *np))
3107 memcpy(value, cp, len);
3109 * Trim off any trailing whitespace
3111 while (len > 0 && isspace((unsigned char)value[len - 1]))
3116 * Return this. All done.
3118 if (np < cpend && ',' == *np)
3121 *datalen = size2int_sat(cpend - np);
3128 varfmt(const char * varname)
3132 for (n = 0; n < COUNTOF(cookedvars); n++)
3133 if (!strcmp(varname, cookedvars[n].varname))
3134 return cookedvars[n].fmt;
3141 * printvars - print variables returned in response packet
3154 rawprint(sttype, length, data, status, quiet, fp);
3156 cookedprint(sttype, length, data, status, quiet, fp);
3161 * rawprint - do a printout of the data in raw mode
3177 * Essentially print the data as is. We reformat unprintables, though.
3180 cpend = data + length;
3183 (void) fprintf(fp, "status=0x%04x,\n", status);
3185 while (cp < cpend) {
3188 * If this is a \r and the next character is a
3189 * \n, supress this, else pretty print it. Otherwise
3190 * just output the character.
3192 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3193 makeascii(1, cp, fp);
3194 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3197 makeascii(1, cp, fp);
3204 * Global data used by the cooked output routines
3206 int out_chars; /* number of characters output */
3207 int out_linecount; /* number of characters output on this line */
3211 * startoutput - get ready to do cooked output
3222 * output - output a variable=value combination
3233 /* strlen of "name=value" */
3234 len = size2int_sat(strlen(name) + 1 + strlen(value));
3236 if (out_chars != 0) {
3238 if ((out_linecount + len + 2) > MAXOUTLINE) {
3251 out_linecount += len;
3256 * endoutput - terminate a block of cooked output
3269 * outputarr - output an array of values
3287 * Hack to align delay and offset values
3289 for (i = (int)strlen(name); i < 11; i++)
3292 for (i = narr; i > 0; i--) {
3295 cp = lfptoms(lfp, 2);
3310 output(fp, name, buf);
3318 register char *cp, *s;
3321 register const char *sep;
3324 s = cp = circ_buf[nextcb];
3325 if (++nextcb >= NUMCB)
3327 cb = sizeof(circ_buf[0]);
3329 snprintf(cp, cb, "%02lx", val);
3333 strlcat(cp, " ok", cb);
3341 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3343 snprintf(cp, cb, "%s%s", sep,
3359 * cookedprint - output variables in cooked mode
3382 char bn[2 * MAXVARLEN];
3383 char bv[2 * MAXVALLEN];
3385 UNUSED_ARG(datatype);
3388 fprintf(fp, "status=%04x %s,\n", status,
3389 statustoa(datatype, status));
3392 while (nextvar(&length, &data, &name, &value)) {
3402 if (!decodets(value, &lfp))
3405 output(fp, name, prettydate(&lfp));
3408 case HA: /* fallthru */
3410 if (!decodenetnum(value, &hval)) {
3412 } else if (fmt == HA){
3413 output(fp, name, nntohost(&hval));
3415 output(fp, name, stoa(&hval));
3420 if (decodenetnum(value, &hval)) {
3421 if (ISREFCLOCKADR(&hval))
3425 output(fp, name, stoa(&hval));
3426 } else if (strlen(value) <= 4) {
3427 output(fp, name, value);
3434 if (!decodeuint(value, &uval) || uval > 3) {
3444 output(fp, name, b);
3449 if (!decodeuint(value, &uval)) {
3452 snprintf(b, sizeof(b), "%03lo", uval);
3453 output(fp, name, b);
3458 if (!decodearr(value, &narr, lfparr))
3461 outputarr(fp, name, narr, lfparr);
3465 if (!decodeuint(value, &uval))
3468 output(fp, name, tstflags(uval));
3472 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3478 if (output_raw != 0) {
3479 /* TALOS-CAN-0063: avoid buffer overrun */
3480 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3481 if (output_raw != '*') {
3482 atoascii(value, MAXVALLEN,
3483 bv, sizeof(bv) - 1);
3485 bv[len] = output_raw;
3488 atoascii(value, MAXVALLEN,
3499 * sortassoc - sort associations in the cache into ascending order
3505 qsort(assoc_cache, (size_t)numassoc,
3506 sizeof(assoc_cache[0]), &assoccmp);
3511 * assoccmp - compare two associations
3519 const struct association *ass1 = t1;
3520 const struct association *ass2 = t2;
3522 if (ass1->assid < ass2->assid)
3524 if (ass1->assid > ass2->assid)
3531 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3533 * The strategy is to add an assumed 4k page size at a time, leaving
3534 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3537 grow_assoc_cache(void)
3539 static size_t prior_sz;
3542 new_sz = prior_sz + 4 * 1024;
3543 if (0 == prior_sz) {
3544 new_sz -= 4 * sizeof(void *);
3546 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3548 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3553 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3555 * By default, autoopts loses the relative order of -c and -p options
3556 * on the command line. This routine replaces the default handler for
3557 * those routines and builds a list of commands to execute preserving
3561 ntpq_custom_opt_handler(
3566 switch (pOptDesc->optValue) {
3570 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3571 pOptDesc->optValue, pOptDesc->optValue);
3575 ADDCMD(pOptDesc->pzLastArg);
3584 * Obtain list of digest names
3588 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3594 #define K_PER_LINE 8
3595 #define K_NL_PFX_STR "\n "
3596 #define K_DELIM_STR ", "
3597 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3600 const char *name, *cp, **seen;
3601 struct hstate *hstate = arg;
3604 u_char digest[EVP_MAX_MD_SIZE];
3607 return; /* Ignore aliases */
3609 name = EVP_MD_name(m);
3611 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3613 for( cp = name; *cp; cp++ ) {
3614 if( islower((unsigned char)*cp) )
3617 len = (cp - name) + 1;
3619 /* There are duplicates. Discard if name has been seen. */
3621 for (seen = hstate->seen; *seen; seen++)
3622 if (!strcmp(*seen, name))
3624 n = (seen - hstate->seen) + 2;
3625 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3626 hstate->seen[n-2] = name;
3627 hstate->seen[n-1] = NULL;
3629 /* Discard MACs that NTP won't accept.
3630 * Keep this consistent with keytype_from_text() in ssl_init.c.
3633 ctx = EVP_MD_CTX_new();
3634 EVP_DigestInit(ctx, EVP_get_digestbyname(name));
3635 EVP_DigestFinal(ctx, digest, &digest_len);
3636 EVP_MD_CTX_free(ctx);
3637 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3640 if (hstate->list != NULL)
3641 len += strlen(hstate->list);
3642 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3644 if (hstate->list == NULL) {
3645 hstate->list = (char *)emalloc(len);
3646 hstate->list[0] = '\0';
3648 hstate->list = (char *)erealloc(hstate->list, len);
3650 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3651 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3653 if (hstate->idx >= K_PER_LINE)
3661 static char *list_digest_names(void)
3666 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3667 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3669 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3672 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3676 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3677 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3680 list = (char *)emalloc(sizeof("md5"));
3681 strcpy(list, "md5");
3687 #define CTRLC_STACK_MAX 4
3688 static volatile size_t ctrlc_stack_len = 0;
3689 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3694 push_ctrl_c_handler(
3698 size_t size = ctrlc_stack_len;
3699 if (func && (size < CTRLC_STACK_MAX)) {
3700 ctrlc_stack[size] = func;
3701 ctrlc_stack_len = size + 1;
3712 size_t size = ctrlc_stack_len;
3715 if (func == NULL || func == ctrlc_stack[size]) {
3716 ctrlc_stack_len = size;
3726 size_t size = ctrlc_stack_len;
3728 if ((*ctrlc_stack[--size])())
3742 char * buf = emalloc(len);
3745 /* Note: we expect the memory allocation to fail long before the
3746 * increment in buffer size actually overflows.
3748 buf = (buf) ? erealloc(buf, len) : emalloc(len);
3751 prc = vsnprintf(buf, len, fmt, va);
3755 /* might be very old vsnprintf. Or actually MSVC... */
3759 if ((size_t)prc >= len) {
3760 /* at least we have the proper size now... */
3761 len = (size_t)prc + 1;
3764 if ((size_t)prc < (len - 32))
3765 buf = erealloc(buf, (size_t)prc + 1);