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 */
780 const char * rowstart;
788 rowlen = min(16, len);
789 for (idx = 0; idx < rowlen; idx++) {
791 printf("%02x ", uch);
793 for ( ; idx < 16 ; idx++)
796 for (idx = 0; idx < rowlen; idx++) {
798 printf("%c", (isprint(uch))
808 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
810 * sendpkt - send a packet to the remote host
819 printf("Sending %zu octets\n", xdatalen);
821 if (send(sockfd, xdata, xdatalen, 0) == -1) {
822 warning("write to %s failed", currenthost);
827 printf("Request packet:\n");
828 dump_hex_printable(xdata, xdatalen);
834 * getresponse - get a (series of) response packet(s) and return the data
846 struct ntp_control rpkt;
847 struct sock_timeval tvo;
848 u_short offsets[MAXFRAGS+1];
849 u_short counts[MAXFRAGS+1];
860 /* absolute timeout checks. Not 'time_t' by intention! */
861 uint32_t tobase; /* base value for timeout */
862 uint32_t tospan; /* timeout span (max delay) */
863 uint32_t todiff; /* current delay */
866 * This is pretty tricky. We may get between 1 and MAXFRAG packets
867 * back in response to the request. We peel the data out of
868 * each packet and collect it in one long block. When the last
869 * packet in the sequence is received we'll know how much data we
870 * should have had. Note we use one long time out, should reconsider.
875 *rdata = (char *)pktdata;
880 tobase = (uint32_t)time(NULL);
885 * Loop until we have an error or a complete response. Nearly all
886 * code paths to loop again use continue.
894 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
896 FD_SET(sockfd, &fds);
897 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
899 #if !defined(SYS_WINNT) && defined(EINTR)
900 /* Windows does not know about EINTR (until very
901 * recently) and the handling of console events
902 * is *very* different from POSIX/UNIX signal
905 * Under non-windows targets we map EINTR as
906 * 'last packet was received' and try to exit
907 * the receive sequence.
909 if (errno == EINTR) {
914 warning("select fails");
919 * Check if this is already too late. Trash the data and
920 * fake a timeout if this is so.
922 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
923 if ((n > 0) && (todiff > tospan)) {
924 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
925 n = 0; /* faked timeout return from 'select()'*/
930 * Timed out. Return what we have
935 "%s: timed out, nothing received\n",
941 "%s: timed out with incomplete data\n",
945 "ERR_INCOMPLETE: Received fragments:\n");
946 for (f = 0; f < numfrags; f++)
948 "%2u: %5d %5d\t%3d octets\n",
949 (u_int)f, offsets[f],
954 "last fragment %sreceived\n",
959 return ERR_INCOMPLETE;
962 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
969 printf("Response packet:\n");
970 dump_hex_printable(&rpkt, n);
974 * Check for format errors. Bug proofing.
976 if (n < (int)CTL_HEADER_LEN) {
978 printf("Short (%d byte) packet received\n", n);
981 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
982 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
984 printf("Packet received with version %d\n",
985 PKT_VERSION(rpkt.li_vn_mode));
988 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
990 printf("Packet received with mode %d\n",
991 PKT_MODE(rpkt.li_vn_mode));
994 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
996 printf("Received request packet, wanted response\n");
1001 * Check opcode and sequence number for a match.
1002 * Could be old data getting to us.
1004 if (ntohs(rpkt.sequence) != sequence) {
1006 printf("Received sequnce number %d, wanted %d\n",
1007 ntohs(rpkt.sequence), sequence);
1010 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1013 "Received opcode %d, wanted %d (sequence number okay)\n",
1014 CTL_OP(rpkt.r_m_e_op), opcode);
1019 * Check the error code. If non-zero, return it.
1021 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1022 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1023 if (CTL_ISMORE(rpkt.r_m_e_op))
1024 TRACE(1, ("Error code %d received on not-final packet\n",
1026 if (errcode == CERR_UNSPEC)
1032 * Check the association ID to make sure it matches what
1035 if (ntohs(rpkt.associd) != associd) {
1036 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1037 ntohs(rpkt.associd), associd));
1039 * Hack for silly fuzzballs which, at the time of writing,
1040 * return an assID of sys.peer when queried for system variables.
1048 * Collect offset and count. Make sure they make sense.
1050 offset = ntohs(rpkt.offset);
1051 count = ntohs(rpkt.count);
1054 * validate received payload size is padded to next 32-bit
1055 * boundary and no smaller than claimed by rpkt.count
1058 TRACE(1, ("Response packet not padded, size = %d\n",
1063 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1065 if (n < shouldbesize) {
1066 printf("Response packet claims %u octets payload, above %ld received\n",
1067 count, (long)(n - CTL_HEADER_LEN));
1068 return ERR_INCOMPLETE;
1071 if (debug >= 3 && shouldbesize > n) {
1077 * Usually we ignore authentication, but for debugging purposes
1080 /* round to 8 octet boundary */
1081 shouldbesize = (shouldbesize + 7) & ~7;
1083 maclen = n - shouldbesize;
1084 if (maclen >= (int)MIN_MAC_LEN) {
1086 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1087 n, shouldbesize, maclen);
1088 lpkt = (u_int32 *)&rpkt;
1089 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1090 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1091 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1092 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1093 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1094 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1095 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1096 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1097 printf("Authenticated with keyid %lu\n", (u_long)key);
1098 if (key != 0 && key != info_auth_keyid) {
1099 printf("We don't know that key\n");
1101 if (authdecrypt(key, (u_int32 *)&rpkt,
1102 n - maclen, maclen)) {
1103 printf("Auth okay!\n");
1105 printf("Auth failed!\n");
1111 TRACE(2, ("Got packet, size = %d\n", n));
1112 if (count > (n - CTL_HEADER_LEN)) {
1113 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1114 count, (long)n - CTL_HEADER_LEN));
1117 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1118 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1121 if (offset + count > sizeof(pktdata)) {
1122 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1126 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1127 TRACE(1, ("Received second last fragment packet\n"));
1132 * So far, so good. Record this fragment, making sure it doesn't
1135 TRACE(2, ("Packet okay\n"));
1137 if (numfrags > (MAXFRAGS - 1)) {
1138 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1144 * Find the position for the fragment relative to any
1145 * previously received.
1148 f < numfrags && offsets[f] < offset;
1153 if (f < numfrags && offset == offsets[f]) {
1154 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1155 count, offset, counts[f], offsets[f]));
1159 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1160 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1161 offset, counts[f-1], offsets[f-1]));
1165 if (f < numfrags && (offset + count) > offsets[f]) {
1166 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1167 count, offset, offsets[f]));
1171 for (ff = numfrags; ff > f; ff--) {
1172 offsets[ff] = offsets[ff-1];
1173 counts[ff] = counts[ff-1];
1175 offsets[f] = offset;
1180 * Got that stuffed in right. Figure out if this was the last.
1181 * Record status info out of the last packet.
1183 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1186 *rstatus = ntohs(rpkt.status);
1190 * Copy the data into the data buffer, and bump the
1191 * timout base in case we need more.
1193 memcpy((char *)pktdata + offset, &rpkt.u, count);
1194 tobase = (uint32_t)time(NULL);
1197 * If we've seen the last fragment, look for holes in the sequence.
1198 * If there aren't any, we're done.
1200 #if !defined(SYS_WINNT) && defined(EINTR)
1204 if (seenlastfrag && offsets[0] == 0) {
1205 for (f = 1; f < numfrags; f++)
1206 if (offsets[f-1] + counts[f-1] !=
1209 if (f == numfrags) {
1210 *rsize = offsets[f-1] + counts[f-1];
1211 TRACE(1, ("%lu packets reassembled into response\n",
1216 } /* giant for (;;) collecting response packets */
1217 } /* getresponse() */
1221 * sendrequest - format and send a request packet
1232 struct ntp_control qpkt;
1239 * Check to make sure the data will fit in one packet
1241 if (qsize > CTL_MAX_DATA_LEN) {
1243 "***Internal error! qsize (%zu) too large\n",
1249 * Fill in the packet
1251 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1252 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1253 qpkt.sequence = htons(sequence);
1255 qpkt.associd = htons((u_short)associd);
1257 qpkt.count = htons((u_short)qsize);
1259 pktsize = CTL_HEADER_LEN;
1262 * If we have data, copy and pad it out to a 32-bit boundary.
1265 memcpy(&qpkt.u, qdata, (size_t)qsize);
1267 while (pktsize & (sizeof(u_int32) - 1)) {
1268 qpkt.u.data[qsize++] = 0;
1274 * If it isn't authenticated we can just send it. Otherwise
1275 * we're going to have to think about it a little.
1277 if (!auth && !always_auth) {
1278 return sendpkt(&qpkt, pktsize);
1282 * Pad out packet to a multiple of 8 octets to be sure
1283 * receiver can handle it.
1285 while (pktsize & 7) {
1286 qpkt.u.data[qsize++] = 0;
1291 * Get the keyid and the password if we don't have one.
1293 if (info_auth_keyid == 0) {
1294 key_id = getkeyid("Keyid: ");
1295 if (key_id == 0 || key_id > NTP_MAXKEY) {
1297 "Invalid key identifier\n");
1300 info_auth_keyid = key_id;
1302 if (!authistrusted(info_auth_keyid)) {
1303 pass = getpass_keytype(info_auth_keytype);
1304 if ('\0' == pass[0]) {
1305 fprintf(stderr, "Invalid password\n");
1308 authusekey(info_auth_keyid, info_auth_keytype,
1310 authtrust(info_auth_keyid, 1);
1314 * Do the encryption.
1316 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1318 fprintf(stderr, "Key not found\n");
1320 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1322 "%zu octet MAC, %zu expected with %zu octet digest\n",
1323 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1328 return sendpkt((char *)&qpkt, pktsize + maclen);
1333 * show_error_msg - display the error text for a mode 6 error response.
1342 fprintf(stderr, "server=%s ", currenthost);
1348 "***Server reports a bad format request packet\n");
1351 case CERR_PERMISSION:
1353 "***Server disallowed request (authentication?)\n");
1358 "***Server reports a bad opcode in request\n");
1363 "***Association ID %d unknown to server\n",
1367 case CERR_UNKNOWNVAR:
1369 "***A request variable unknown to the server\n");
1374 "***Server indicates a request variable was bad\n");
1379 "***Server returned an unspecified error\n");
1383 fprintf(stderr, "***Request timed out\n");
1386 case ERR_INCOMPLETE:
1388 "***Response from server was incomplete\n");
1393 "***Buffer size exceeded for returned data\n");
1398 "***Server returns unknown error code %d\n",
1404 * doquery - send a request and process the response, displaying
1405 * error messages for any error responses.
1419 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1420 rsize, rdata, FALSE);
1425 * doqueryex - send a request and process the response, optionally
1426 * displaying error messages for any error responses.
1445 * Check to make sure host is open
1448 fprintf(stderr, "***No host open, use `host' command\n");
1459 res = sendrequest(opcode, associd, auth, qsize, qdata);
1464 * Get the response. If we got a standard error, print a message
1466 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1469 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1470 if (res == ERR_INCOMPLETE) {
1472 * better bump the sequence so we don't
1473 * get confused about differing fragments.
1481 show_error_msg(res, associd);
1488 #ifndef BUILD_AS_LIB
1490 * getcmds - read commands from the standard input and execute them
1498 ntp_readline_init(interactive ? prompt : NULL);
1501 line = ntp_readline(&count);
1508 ntp_readline_uninit();
1510 #endif /* !BUILD_AS_LIB */
1513 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1515 * abortcmd - catch interrupts and abort the current command
1520 if (current_output == stdout)
1521 (void) fflush(stdout);
1523 (void) fflush(stderr);
1526 longjmp(interrupt_buf, 1);
1530 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1533 #ifndef BUILD_AS_LIB
1535 * docmd - decode the command line and execute a command
1542 char *tokens[1+MAXARGS+2];
1549 * Tokenize the command line. If nothing on it, return.
1551 tokenize(cmdline, tokens, &ntok);
1556 * Find the appropriate command description.
1558 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1560 (void) fprintf(stderr, "***Command `%s' unknown\n",
1563 } else if (i >= 2) {
1564 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1569 /* Warn about ignored extra args */
1570 for (i = MAXARGS + 1; i < ntok ; ++i) {
1571 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1575 * Save the keyword, then walk through the arguments, interpreting
1578 pcmd.keyword = tokens[0];
1580 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1581 if ((i+1) >= ntok) {
1582 if (!(xcmd->arg[i] & OPT)) {
1583 printusage(xcmd, stderr);
1588 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1590 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1596 if (i < ntok && *tokens[i] == '>') {
1599 if (*(tokens[i]+1) != '\0')
1600 fname = tokens[i]+1;
1601 else if ((i+1) < ntok)
1602 fname = tokens[i+1];
1604 (void) fprintf(stderr, "***No file for redirect\n");
1608 current_output = fopen(fname, "w");
1609 if (current_output == NULL) {
1610 (void) fprintf(stderr, "***Error opening %s: ", fname);
1614 i = 1; /* flag we need a close */
1616 current_output = stdout;
1617 i = 0; /* flag no close */
1620 if (interactive && setjmp(interrupt_buf)) {
1625 (xcmd->handler)(&pcmd, current_output);
1626 jump = 0; /* HMS: 961106: was after fclose() */
1627 if (i) (void) fclose(current_output);
1635 * tokenize - turn a command line into tokens
1637 * SK: Modified to allow a quoted string
1639 * HMS: If the first character of the first token is a ':' then (after
1640 * eating inter-token whitespace) the 2nd token is the rest of the line.
1650 register const char *cp;
1652 static char tspace[MAXLINE];
1656 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1659 /* Skip inter-token whitespace */
1660 while (ISSPACE(*cp))
1663 /* If we're at EOL we're done */
1667 /* If this is the 2nd token and the first token begins
1668 * with a ':', then just grab to EOL.
1671 if (*ntok == 1 && tokens[0][0] == ':') {
1673 if (sp - tspace >= MAXLINE)
1676 } while (!ISEOL(*cp));
1679 /* Check if this token begins with a double quote.
1680 * If yes, continue reading till the next double quote
1682 else if (*cp == '\"') {
1685 if (sp - tspace >= MAXLINE)
1688 } while ((*cp != '\"') && !ISEOL(*cp));
1689 /* HMS: a missing closing " should be an error */
1693 if (sp - tspace >= MAXLINE)
1696 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1697 /* HMS: Why check for a " in the previous line? */
1700 if (sp - tspace >= MAXLINE)
1709 "***Line `%s' is too big\n",
1716 * getarg - interpret an argument token
1727 switch (code & ~OPT) {
1733 if (!getnetnum(str, &argp->netnum, NULL, 0))
1738 if ('&' == str[0]) {
1739 if (!atouint(&str[1], &ul)) {
1741 "***Association index `%s' invalid/undecodable\n",
1745 if (0 == numassoc) {
1747 if (0 == numassoc) {
1749 "***No associations found, `%s' unknown\n",
1754 ul = min(ul, numassoc);
1755 argp->uval = assoc_cache[ul - 1].assid;
1758 if (!atouint(str, &argp->uval)) {
1759 fprintf(stderr, "***Illegal unsigned value %s\n",
1766 if (!atoint(str, &argp->ival)) {
1767 fprintf(stderr, "***Illegal integer value %s\n",
1774 if (!strcmp("-6", str)) {
1776 } else if (!strcmp("-4", str)) {
1779 fprintf(stderr, "***Version must be either 4 or 6\n");
1787 #endif /* !BUILD_AS_LIB */
1791 * findcmd - find a command in a command description table
1796 struct xcmd * clist1,
1797 struct xcmd * clist2,
1804 struct xcmd *nearmatch = NULL;
1811 else if (clist2 != 0)
1817 for (cl = clist; cl->keyword != 0; cl++) {
1818 /* do a first character check, for efficiency */
1819 if (*str != *(cl->keyword))
1821 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1823 * Could be extact match, could be approximate.
1824 * Is exact if the length of the keyword is the
1827 if (*((cl->keyword) + clen) == '\0') {
1837 * See if there is more to do. If so, go again. Sorry about the
1838 * goto, too much looking at BSD sources...
1840 if (clist == clist1 && clist2 != 0) {
1846 * If we got extactly 1 near match, use it, else return number
1858 * getnetnum - given a host name, return its net number
1859 * and (optional) full name
1869 struct addrinfo hints, *ai = NULL;
1872 hints.ai_flags = AI_CANONNAME;
1873 #ifdef AI_ADDRCONFIG
1874 hints.ai_flags |= AI_ADDRCONFIG;
1878 * decodenetnum only works with addresses, but handles syntax
1879 * that getaddrinfo doesn't: [2001::1]:1234
1881 if (decodenetnum(hname, num)) {
1882 if (fullhost != NULL)
1883 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1884 LENHOSTNAME, NULL, 0, 0);
1886 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1887 INSIST(sizeof(*num) >= ai->ai_addrlen);
1888 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1889 if (fullhost != NULL) {
1890 if (ai->ai_canonname != NULL)
1891 strlcpy(fullhost, ai->ai_canonname,
1894 getnameinfo(&num->sa, SOCKLEN(num),
1895 fullhost, LENHOSTNAME, NULL,
1901 fprintf(stderr, "***Can't find host %s\n", hname);
1908 * nntohost - convert network number to host name. This routine enforces
1909 * the showhostnames setting.
1916 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1921 * nntohost_col - convert network number to host name in fixed width.
1922 * This routine enforces the showhostnames setting.
1923 * When displaying hostnames longer than the width,
1924 * the first part of the hostname is displayed. When
1925 * displaying numeric addresses longer than the width,
1926 * Such as IPv6 addresses, the caller decides whether
1927 * the first or last of the numeric address is used.
1933 int preserve_lowaddrbits
1938 if (!showhostnames || SOCK_UNSPEC(addr)) {
1939 if (preserve_lowaddrbits)
1940 out = trunc_left(stoa(addr), width);
1942 out = trunc_right(stoa(addr), width);
1943 } else if (ISREFCLOCKADR(addr)) {
1944 out = refnumtoa(addr);
1946 out = trunc_right(socktohost(addr), width);
1953 * nntohostp() is the same as nntohost() plus a :port suffix
1963 if (!showhostnames || SOCK_UNSPEC(netnum))
1964 return sptoa(netnum);
1965 else if (ISREFCLOCKADR(netnum))
1966 return refnumtoa(netnum);
1968 hostn = socktohost(netnum);
1970 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1976 * rtdatetolfp - decode an RT-11 date into an l_fp
1986 struct calendar cal;
1992 * An RT-11 date looks like:
1994 * d[d]-Mth-y[y] hh:mm:ss
1996 * (No docs, but assume 4-digit years are also legal...)
1998 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
2001 if (!isdigit((int)*cp)) {
2004 * Catch special case
2012 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2013 if (isdigit((int)*cp)) {
2014 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2015 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2021 for (i = 0; i < 3; i++)
2025 for (i = 0; i < 12; i++)
2026 if (STREQ(buf, months[i]))
2030 cal.month = (u_char)(i + 1);
2035 if (!isdigit((int)*cp))
2037 cal.year = (u_short)(*cp++ - '0');
2038 if (isdigit((int)*cp)) {
2039 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2040 cal.year = (u_short)(*cp++ - '0');
2042 if (isdigit((int)*cp)) {
2043 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2044 cal.year = (u_short)(cal.year + *cp++ - '0');
2046 if (isdigit((int)*cp)) {
2047 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2048 cal.year = (u_short)(cal.year + *cp++ - '0');
2052 * Catch special case. If cal.year == 0 this is a zero timestamp.
2054 if (cal.year == 0) {
2059 if (*cp++ != ' ' || !isdigit((int)*cp))
2061 cal.hour = (u_char)(*cp++ - '0');
2062 if (isdigit((int)*cp)) {
2063 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2064 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2067 if (*cp++ != ':' || !isdigit((int)*cp))
2069 cal.minute = (u_char)(*cp++ - '0');
2070 if (isdigit((int)*cp)) {
2071 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2072 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2075 if (*cp++ != ':' || !isdigit((int)*cp))
2077 cal.second = (u_char)(*cp++ - '0');
2078 if (isdigit((int)*cp)) {
2079 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2080 cal.second = (u_char)(cal.second + *cp++ - '0');
2084 * For RT-11, 1972 seems to be the pivot year
2091 lfp->l_ui = caltontp(&cal);
2098 * decodets - decode a timestamp into an l_fp format number, with
2099 * consideration of fuzzball formats.
2112 * If it starts with a 0x, decode as hex.
2114 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2115 return hextolfp(str+2, lfp);
2118 * If it starts with a '"', try it as an RT-11 date.
2123 while ('"' != *cp && '\0' != *cp &&
2124 b < COUNTOF(buf) - 1)
2127 return rtdatetolfp(buf, lfp);
2131 * Might still be hex. Check out the first character. Talk
2134 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2135 return hextolfp(str, lfp);
2138 * Try it as a decimal. If this fails, try as an unquoted
2139 * RT-11 date. This code should go away eventually.
2141 if (atolfp(str, lfp))
2144 return rtdatetolfp(str, lfp);
2149 * decodetime - decode a time value. It should be in milliseconds
2157 return mstolfp(str, lfp);
2162 * decodeint - decode an integer
2171 if (*(str+1) == 'x' || *(str+1) == 'X')
2172 return hextoint(str+2, (u_long *)val);
2173 return octtoint(str, (u_long *)val);
2175 return atoint(str, val);
2180 * decodeuint - decode an unsigned integer
2189 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2190 return (hextoint(str + 2, val));
2191 return (octtoint(str, val));
2193 return (atouint(str, val));
2198 * decodearr - decode an array of time values
2207 register char *cp, *bp;
2216 while (isspace((int)*cp))
2222 while (!isspace((int)*cp) && *cp != '\0')
2226 if (!decodetime(buf, lfp))
2236 * Finally, the built in command handlers
2240 * help - tell about commands, or details of a particular command
2248 struct xcmd *xcp = NULL; /* quiet warning */
2250 const char *list[100];
2256 if (pcmd->nargs == 0) {
2258 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2259 if (*(xcp->keyword) != '?' &&
2260 words < COUNTOF(list))
2261 list[words++] = xcp->keyword;
2263 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2264 if (words < COUNTOF(list))
2265 list[words++] = xcp->keyword;
2267 qsort((void *)list, words, sizeof(list[0]), helpsort);
2269 for (word = 0; word < words; word++) {
2270 length = strlen(list[word]);
2271 col = max(col, length);
2274 cols = SCREENWIDTH / ++col;
2275 rows = (words + cols - 1) / cols;
2277 fprintf(fp, "ntpq commands:\n");
2279 for (row = 0; row < rows; row++) {
2280 for (word = row; word < words; word += rows)
2281 fprintf(fp, "%-*.*s", (int)col,
2282 (int)col - 1, list[word]);
2286 cmd = pcmd->argval[0].string;
2287 words = findcmd(cmd, builtins, opcmds, &xcp);
2290 "Command `%s' is unknown\n", cmd);
2292 } else if (words >= 2) {
2294 "Command `%s' is ambiguous\n", cmd);
2297 fprintf(fp, "function: %s\n", xcp->comment);
2298 printusage(xcp, fp);
2304 * helpsort - do hostname qsort comparisons
2312 const char * const * name1 = t1;
2313 const char * const * name2 = t2;
2315 return strcmp(*name1, *name2);
2320 * printusage - print usage information for a command
2330 /* XXX: Do we need to warn about extra args here too? */
2332 (void) fprintf(fp, "usage: %s", xcp->keyword);
2333 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2334 if (xcp->arg[i] & OPT)
2335 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2337 (void) fprintf(fp, " %s", xcp->desc[i]);
2339 (void) fprintf(fp, "\n");
2344 * timeout - set time out time
2354 if (pcmd->nargs == 0) {
2355 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2356 (void) fprintf(fp, "primary timeout %d ms\n", val);
2358 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2359 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2366 * auth_delay - set delay for auth requests
2377 if (pcmd->nargs == 0) {
2378 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2379 (void) fprintf(fp, "delay %lu ms\n", val);
2381 if (pcmd->argval[0].ival < 0) {
2383 val = (u_long)(-pcmd->argval[0].ival);
2386 val = (u_long)pcmd->argval[0].ival;
2389 delay_time.l_ui = val / 1000;
2391 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2400 * host - set the host we are dealing with.
2410 if (pcmd->nargs == 0) {
2412 (void) fprintf(fp, "current host is %s\n",
2415 (void) fprintf(fp, "no current host\n");
2420 ai_fam_templ = ai_fam_default;
2421 if (pcmd->nargs == 2) {
2422 if (!strcmp("-4", pcmd->argval[i].string))
2423 ai_fam_templ = AF_INET;
2424 else if (!strcmp("-6", pcmd->argval[i].string))
2425 ai_fam_templ = AF_INET6;
2430 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2431 fprintf(fp, "current host set to %s\n", currenthost);
2435 fprintf(fp, "current host remains %s\n",
2438 fprintf(fp, "still no current host\n");
2444 * poll - do one (or more) polls of the host via NTP
2453 (void) fprintf(fp, "poll not implemented yet\n");
2458 * showdrefid2str - return a string explanation of the value of drefid
2461 showdrefid2str(void)
2475 * drefid - display/change "display hash"
2483 if (pcmd->nargs == 0) {
2484 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2486 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2487 drefid = REFID_HASH;
2488 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2489 drefid = REFID_IPV4;
2491 (void) fprintf(fp, "What?\n");
2494 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2499 * keyid - get a keyid to use for authenticating requests
2507 if (pcmd->nargs == 0) {
2508 if (info_auth_keyid == 0)
2509 (void) fprintf(fp, "no keyid defined\n");
2511 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2513 /* allow zero so that keyid can be cleared. */
2514 if(pcmd->argval[0].uval > NTP_MAXKEY)
2515 (void) fprintf(fp, "Invalid key identifier\n");
2516 info_auth_keyid = pcmd->argval[0].uval;
2521 * keytype - get type of key to use for authenticating requests
2529 const char * digest_name;
2534 fprintf(fp, "keytype is %s with %lu octet digests\n",
2535 keytype_name(info_auth_keytype),
2536 (u_long)info_auth_hashlen);
2540 digest_name = pcmd->argval[0].string;
2542 key_type = keytype_from_text(digest_name, &digest_len);
2545 fprintf(fp, "keytype is not valid. "
2547 "Type \"help keytype\" for the available digest types.\n");
2549 "Only \"md5\" is available.\n");
2554 info_auth_keytype = key_type;
2555 info_auth_hashlen = digest_len;
2560 * passwd - get an authentication key
2571 if (info_auth_keyid == 0) {
2572 info_auth_keyid = getkeyid("Keyid: ");
2573 if (info_auth_keyid == 0) {
2574 (void)fprintf(fp, "Keyid must be defined\n");
2578 if (pcmd->nargs >= 1)
2579 pass = pcmd->argval[0].string;
2581 pass = getpass_keytype(info_auth_keytype);
2582 if ('\0' == pass[0]) {
2583 fprintf(fp, "Password unchanged\n");
2587 authusekey(info_auth_keyid, info_auth_keytype,
2588 (const u_char *)pass);
2589 authtrust(info_auth_keyid, 1);
2594 * hostnames - set the showhostnames flag
2602 if (pcmd->nargs == 0) {
2604 (void) fprintf(fp, "hostnames being shown\n");
2606 (void) fprintf(fp, "hostnames not being shown\n");
2608 if (STREQ(pcmd->argval[0].string, "yes"))
2610 else if (STREQ(pcmd->argval[0].string, "no"))
2613 (void)fprintf(stderr, "What?\n");
2620 * setdebug - set/change debugging level
2628 if (pcmd->nargs == 0) {
2629 (void) fprintf(fp, "debug level is %d\n", debug);
2631 } else if (STREQ(pcmd->argval[0].string, "no")) {
2633 } else if (STREQ(pcmd->argval[0].string, "more")) {
2635 } else if (STREQ(pcmd->argval[0].string, "less")) {
2638 (void) fprintf(fp, "What?\n");
2641 (void) fprintf(fp, "debug level set to %d\n", debug);
2646 * quit - stop this nonsense
2656 closesocket(sockfd); /* cleanliness next to godliness */
2662 * version - print the current version number
2672 (void) fprintf(fp, "%s\n", Version);
2678 * raw - set raw mode output
2688 (void) fprintf(fp, "Output set to raw\n");
2693 * cooked - set cooked mode output
2703 (void) fprintf(fp, "Output set to cooked\n");
2709 * authenticate - always authenticate requests to this host
2717 if (pcmd->nargs == 0) {
2720 "authenticated requests being sent\n");
2723 "unauthenticated requests being sent\n");
2725 if (STREQ(pcmd->argval[0].string, "yes")) {
2727 } else if (STREQ(pcmd->argval[0].string, "no")) {
2730 (void)fprintf(stderr, "What?\n");
2736 * ntpversion - choose the NTP version to use
2744 if (pcmd->nargs == 0) {
2746 "NTP version being claimed is %d\n", pktversion);
2748 if (pcmd->argval[0].uval < NTP_OLDVERSION
2749 || pcmd->argval[0].uval > NTP_VERSION) {
2750 (void) fprintf(stderr, "versions %d to %d, please\n",
2751 NTP_OLDVERSION, NTP_VERSION);
2753 pktversion = (u_char) pcmd->argval[0].uval;
2759 static void __attribute__((__format__(__printf__, 1, 0)))
2760 vwarning(const char *fmt, va_list ap)
2763 (void) fprintf(stderr, "%s: ", progname);
2764 vfprintf(stderr, fmt, ap);
2765 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2769 * warning - print a warning message
2771 static void __attribute__((__format__(__printf__, 1, 2)))
2785 * error - print a message and exit
2787 static void __attribute__((__format__(__printf__, 1, 2)))
2800 * getkeyid - prompt the user for a keyid to use
2804 const char *keyprompt
2814 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2816 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2817 #endif /* SYS_WINNT */
2820 setbuf(fi, (char *)NULL);
2821 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2822 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2823 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2825 pbuf[i++] = (char)c;
2830 return (u_long) atoi(pbuf);
2835 * atoascii - printable-ize possibly ascii data using the character
2836 * transformations cat -v uses.
2846 const u_char * pchIn;
2847 const u_char * pchInLimit;
2851 pchIn = (const u_char *)in;
2852 pchInLimit = pchIn + in_octets;
2853 pchOut = (u_char *)out;
2855 if (NULL == pchIn) {
2863 if (0 == --out_octets) { \
2870 for ( ; pchIn < pchInLimit; pchIn++) {
2881 ONEOUT((u_char)(c + '@'));
2882 } else if (0x7f == c) {
2895 * makeascii - print possibly ascii data using the character
2896 * transformations that cat -v uses.
2905 const u_char *data_u_char;
2909 data_u_char = (const u_char *)data;
2911 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2922 } else if (0x7f == c) {
2932 * asciize - same thing as makeascii except add a newline
2941 makeascii(length, data, fp);
2947 * truncate string to fit clipping excess at end.
2948 * "too long" -> "too l"
2949 * Used for hostnames.
2962 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2964 memcpy(out, src, width);
2975 * truncate string to fit by preserving right side and using '_' to hint
2976 * "too long" -> "_long"
2977 * Used for local IPv6 addresses, where low bits differentiate.
2990 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2993 memcpy(&out[1], &src[sl + 1 - width], width);
3003 * Some circular buffer space
3008 char circ_buf[NUMCB][CBLEN];
3012 * nextvar - find the next variable in the buffer
3027 static char name[MAXVARLEN];
3028 static char value[MAXVALLEN];
3031 cpend = cp + *datalen;
3034 * Space past commas and white space
3036 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
3042 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
3043 * over any white space and terminate it.
3045 srclen = strcspn(cp, ",=\r\n");
3046 srclen = min(srclen, (size_t)(cpend - cp));
3048 while (len > 0 && isspace((unsigned char)cp[len - 1]))
3050 if (len >= sizeof(name))
3053 memcpy(name, cp, len);
3059 * Check if we hit the end of the buffer or a ','. If so we are done.
3061 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
3065 *datalen = size2int_sat(cpend - cp);
3071 * So far, so good. Copy out the value
3073 cp++; /* past '=' */
3074 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
3080 } while (np < cpend && '"' != *np);
3081 if (np < cpend && '"' == *np)
3084 while (np < cpend && ',' != *np && '\r' != *np)
3088 if (np > cpend || len >= sizeof(value) ||
3089 (np < cpend && ',' != *np && '\r' != *np))
3091 memcpy(value, cp, len);
3093 * Trim off any trailing whitespace
3095 while (len > 0 && isspace((unsigned char)value[len - 1]))
3100 * Return this. All done.
3102 if (np < cpend && ',' == *np)
3105 *datalen = size2int_sat(cpend - np);
3112 varfmt(const char * varname)
3116 for (n = 0; n < COUNTOF(cookedvars); n++)
3117 if (!strcmp(varname, cookedvars[n].varname))
3118 return cookedvars[n].fmt;
3125 * printvars - print variables returned in response packet
3138 rawprint(sttype, length, data, status, quiet, fp);
3140 cookedprint(sttype, length, data, status, quiet, fp);
3145 * rawprint - do a printout of the data in raw mode
3161 * Essentially print the data as is. We reformat unprintables, though.
3164 cpend = data + length;
3167 (void) fprintf(fp, "status=0x%04x,\n", status);
3169 while (cp < cpend) {
3172 * If this is a \r and the next character is a
3173 * \n, supress this, else pretty print it. Otherwise
3174 * just output the character.
3176 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3177 makeascii(1, cp, fp);
3178 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3181 makeascii(1, cp, fp);
3188 * Global data used by the cooked output routines
3190 int out_chars; /* number of characters output */
3191 int out_linecount; /* number of characters output on this line */
3195 * startoutput - get ready to do cooked output
3206 * output - output a variable=value combination
3217 /* strlen of "name=value" */
3218 len = size2int_sat(strlen(name) + 1 + strlen(value));
3220 if (out_chars != 0) {
3222 if ((out_linecount + len + 2) > MAXOUTLINE) {
3235 out_linecount += len;
3240 * endoutput - terminate a block of cooked output
3253 * outputarr - output an array of values
3271 * Hack to align delay and offset values
3273 for (i = (int)strlen(name); i < 11; i++)
3276 for (i = narr; i > 0; i--) {
3279 cp = lfptoms(lfp, 2);
3294 output(fp, name, buf);
3302 register char *cp, *s;
3305 register const char *sep;
3308 s = cp = circ_buf[nextcb];
3309 if (++nextcb >= NUMCB)
3311 cb = sizeof(circ_buf[0]);
3313 snprintf(cp, cb, "%02lx", val);
3317 strlcat(cp, " ok", cb);
3325 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3327 snprintf(cp, cb, "%s%s", sep,
3343 * cookedprint - output variables in cooked mode
3366 char bn[2 * MAXVARLEN];
3367 char bv[2 * MAXVALLEN];
3369 UNUSED_ARG(datatype);
3372 fprintf(fp, "status=%04x %s,\n", status,
3373 statustoa(datatype, status));
3376 while (nextvar(&length, &data, &name, &value)) {
3386 if (!decodets(value, &lfp))
3389 output(fp, name, prettydate(&lfp));
3392 case HA: /* fallthru */
3394 if (!decodenetnum(value, &hval)) {
3396 } else if (fmt == HA){
3397 output(fp, name, nntohost(&hval));
3399 output(fp, name, stoa(&hval));
3404 if (decodenetnum(value, &hval)) {
3405 if (ISREFCLOCKADR(&hval))
3409 output(fp, name, stoa(&hval));
3410 } else if (strlen(value) <= 4) {
3411 output(fp, name, value);
3418 if (!decodeuint(value, &uval) || uval > 3) {
3428 output(fp, name, b);
3433 if (!decodeuint(value, &uval)) {
3436 snprintf(b, sizeof(b), "%03lo", uval);
3437 output(fp, name, b);
3442 if (!decodearr(value, &narr, lfparr))
3445 outputarr(fp, name, narr, lfparr);
3449 if (!decodeuint(value, &uval))
3452 output(fp, name, tstflags(uval));
3456 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3462 if (output_raw != 0) {
3463 /* TALOS-CAN-0063: avoid buffer overrun */
3464 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3465 if (output_raw != '*') {
3466 atoascii(value, MAXVALLEN,
3467 bv, sizeof(bv) - 1);
3469 bv[len] = output_raw;
3472 atoascii(value, MAXVALLEN,
3483 * sortassoc - sort associations in the cache into ascending order
3489 qsort(assoc_cache, (size_t)numassoc,
3490 sizeof(assoc_cache[0]), &assoccmp);
3495 * assoccmp - compare two associations
3503 const struct association *ass1 = t1;
3504 const struct association *ass2 = t2;
3506 if (ass1->assid < ass2->assid)
3508 if (ass1->assid > ass2->assid)
3515 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3517 * The strategy is to add an assumed 4k page size at a time, leaving
3518 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3521 grow_assoc_cache(void)
3523 static size_t prior_sz;
3526 new_sz = prior_sz + 4 * 1024;
3527 if (0 == prior_sz) {
3528 new_sz -= 4 * sizeof(void *);
3530 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3532 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3537 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3539 * By default, autoopts loses the relative order of -c and -p options
3540 * on the command line. This routine replaces the default handler for
3541 * those routines and builds a list of commands to execute preserving
3545 ntpq_custom_opt_handler(
3550 switch (pOptDesc->optValue) {
3554 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3555 pOptDesc->optValue, pOptDesc->optValue);
3559 ADDCMD(pOptDesc->pzLastArg);
3568 * Obtain list of digest names
3572 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3578 #define K_PER_LINE 8
3579 #define K_NL_PFX_STR "\n "
3580 #define K_DELIM_STR ", "
3581 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3584 const char *name, *cp, **seen;
3585 struct hstate *hstate = arg;
3588 u_char digest[EVP_MAX_MD_SIZE];
3591 return; /* Ignore aliases */
3593 name = EVP_MD_name(m);
3595 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3597 for( cp = name; *cp; cp++ ) {
3601 len = (cp - name) + 1;
3603 /* There are duplicates. Discard if name has been seen. */
3605 for (seen = hstate->seen; *seen; seen++)
3606 if (!strcmp(*seen, name))
3608 n = (seen - hstate->seen) + 2;
3609 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3610 hstate->seen[n-2] = name;
3611 hstate->seen[n-1] = NULL;
3613 /* Discard MACs that NTP won't accept.
3614 * Keep this consistent with keytype_from_text() in ssl_init.c.
3617 ctx = EVP_MD_CTX_new();
3618 EVP_DigestInit(ctx, EVP_get_digestbyname(name));
3619 EVP_DigestFinal(ctx, digest, &digest_len);
3620 EVP_MD_CTX_free(ctx);
3621 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3624 if (hstate->list != NULL)
3625 len += strlen(hstate->list);
3626 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3628 if (hstate->list == NULL) {
3629 hstate->list = (char *)emalloc(len);
3630 hstate->list[0] = '\0';
3632 hstate->list = (char *)erealloc(hstate->list, len);
3634 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3635 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3637 if (hstate->idx >= K_PER_LINE)
3645 static char *list_digest_names(void)
3650 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3651 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3653 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3656 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3660 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3661 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3664 list = (char *)emalloc(sizeof("md5"));
3665 strcpy(list, "md5");
3671 #define CTRLC_STACK_MAX 4
3672 static volatile size_t ctrlc_stack_len = 0;
3673 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3678 push_ctrl_c_handler(
3682 size_t size = ctrlc_stack_len;
3683 if (func && (size < CTRLC_STACK_MAX)) {
3684 ctrlc_stack[size] = func;
3685 ctrlc_stack_len = size + 1;
3696 size_t size = ctrlc_stack_len;
3699 if (func == NULL || func == ctrlc_stack[size]) {
3700 ctrlc_stack_len = size;
3710 size_t size = ctrlc_stack_len;
3712 if ((*ctrlc_stack[--size])())
3726 char * buf = emalloc(len);
3729 /* Note: we expect the memory allocation to fail long before the
3730 * increment in buffer size actually overflows.
3732 buf = (buf) ? erealloc(buf, len) : emalloc(len);
3735 prc = vsnprintf(buf, len, fmt, va);
3739 /* might be very old vsnprintf. Or actually MSVC... */
3743 if ((size_t)prc >= len) {
3744 /* at least we have the proper size now... */
3745 len = (size_t)prc + 1;
3748 if ((size_t)prc < (len - 32))
3749 buf = erealloc(buf, (size_t)prc + 1);