2 * ntpq - query an NTP server using mode 6 commands
21 #include <isc/result.h>
24 #include "ntp_assert.h"
25 #include "ntp_stdlib.h"
26 #include "ntp_unixtime.h"
27 #include "ntp_calendar.h"
28 #include "ntp_select.h"
29 #include "ntp_assert.h"
30 #include "lib_strbuf.h"
31 #include "ntp_lineedit.h"
32 #include "ntp_debug.h"
34 #include "openssl/evp.h"
35 #include "openssl/objects.h"
36 #include "openssl/err.h"
38 #include <ssl_applink.c>
40 #include "ntp_libopts.h"
41 #include "ntpq-opts.h"
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
74 s_char sys_precision; /* local clock precision (log2 s) */
77 * Keyid used for authenticated requests. Obtained on the fly.
79 u_long info_auth_keyid = 0;
81 static int info_auth_keytype = NID_md5; /* MD5 */
82 static size_t info_auth_hashlen = 16; /* MD5 */
83 u_long current_time; /* needed by authkeys; not used */
86 * Flag which indicates we should always send authenticated requests
91 * Flag which indicates raw mode output.
96 * Packet version number we use
98 u_char pktversion = NTP_OLDVERSION + 1;
101 * Don't jump if no set jmp.
103 volatile int jump = 0;
109 #define HA 1 /* host address */
110 #define NA 2 /* network address */
111 #define LP 3 /* leap (print in binary) */
112 #define RF 4 /* refid (sometimes string, sometimes not) */
113 #define AR 5 /* array of times */
114 #define FX 6 /* test flags */
115 #define TS 7 /* l_fp timestamp in hex */
116 #define OC 8 /* integer, print in octal */
117 #define EOV 255 /* end of table */
120 * For the most part ntpq simply displays what ntpd provides in the
121 * mostly plain-text mode 6 responses. A few variable names are by
122 * default "cooked" to provide more human-friendly output.
124 const var_format cookedvars[] = {
135 { "peeradr", HA }, /* compat with others */
138 { "filtoffset", AR },
140 { "filterror", AR }, /* compat with others */
148 static const char *tstflagnames[] = {
149 "pkt_dup", /* TEST1 */
150 "pkt_bogus", /* TEST2 */
151 "pkt_unsync", /* TEST3 */
152 "pkt_denied", /* TEST4 */
153 "pkt_auth", /* TEST5 */
154 "pkt_stratum", /* TEST6 */
155 "pkt_header", /* TEST7 */
156 "pkt_autokey", /* TEST8 */
157 "pkt_crypto", /* TEST9 */
158 "peer_stratum", /* TEST10 */
159 "peer_dist", /* TEST11 */
160 "peer_loop", /* TEST12 */
161 "peer_unreach" /* TEST13 */
165 int ntpqmain (int, char **);
167 * Built in command handler declarations
169 static int openhost (const char *, int);
170 static void dump_hex_printable(const void *, size_t);
171 static int sendpkt (void *, size_t);
172 static int getresponse (int, int, u_short *, size_t *, const char **, int);
173 static int sendrequest (int, associd_t, int, size_t, const char *);
174 static char * tstflags (u_long);
176 static void getcmds (void);
178 static int abortcmd (void);
179 #endif /* SYS_WINNT */
180 static void docmd (const char *);
181 static void tokenize (const char *, char **, int *);
182 static int getarg (const char *, int, arg_v *);
183 #endif /* BUILD_AS_LIB */
184 static int findcmd (const char *, struct xcmd *,
185 struct xcmd *, struct xcmd **);
186 static int rtdatetolfp (char *, l_fp *);
187 static int decodearr (char *, int *, l_fp *);
188 static void help (struct parse *, FILE *);
189 static int helpsort (const void *, const void *);
190 static void printusage (struct xcmd *, FILE *);
191 static void timeout (struct parse *, FILE *);
192 static void auth_delay (struct parse *, FILE *);
193 static void host (struct parse *, FILE *);
194 static void ntp_poll (struct parse *, FILE *);
195 static void keyid (struct parse *, FILE *);
196 static void keytype (struct parse *, FILE *);
197 static void passwd (struct parse *, FILE *);
198 static void hostnames (struct parse *, FILE *);
199 static void setdebug (struct parse *, FILE *);
200 static void quit (struct parse *, FILE *);
201 static void version (struct parse *, FILE *);
202 static void raw (struct parse *, FILE *);
203 static void cooked (struct parse *, FILE *);
204 static void authenticate (struct parse *, FILE *);
205 static void ntpversion (struct parse *, FILE *);
206 static void warning (const char *, ...)
207 __attribute__((__format__(__printf__, 1, 2)));
208 static void error (const char *, ...)
209 __attribute__((__format__(__printf__, 1, 2)));
210 static u_long getkeyid (const char *);
211 static void atoascii (const char *, size_t, char *, size_t);
212 static void cookedprint (int, size_t, const char *, int, int, FILE *);
213 static void rawprint (int, size_t, const char *, int, int, FILE *);
214 static void startoutput (void);
215 static void output (FILE *, const char *, const char *);
216 static void endoutput (FILE *);
217 static void outputarr (FILE *, char *, int, l_fp *);
218 static int assoccmp (const void *, const void *);
219 static void on_ctrlc (void);
220 u_short varfmt (const char *);
221 static int my_easprintf (char**, const char *, ...) NTP_PRINTF(2, 3);
222 void ntpq_custom_opt_handler (tOptions *, tOptDesc *);
225 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
226 static void list_md_fn(const EVP_MD *m, const char *from,
227 const char *to, void *arg );
230 static char *list_digest_names(void);
233 * Built-in commands we understand
235 struct xcmd builtins[] = {
236 { "?", help, { OPT|NTP_STR, NO, NO, NO },
237 { "command", "", "", "" },
238 "tell the use and syntax of commands" },
239 { "help", help, { OPT|NTP_STR, NO, NO, NO },
240 { "command", "", "", "" },
241 "tell the use and syntax of commands" },
242 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
243 { "msec", "", "", "" },
244 "set the primary receive time out" },
245 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
246 { "msec", "", "", "" },
247 "set the delay added to encryption time stamps" },
248 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
249 { "-4|-6", "hostname", "", "" },
250 "specify the host whose NTP server we talk to" },
251 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
252 { "n", "verbose", "", "" },
253 "poll an NTP server in client mode `n' times" },
254 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
256 "specify a password to use for authenticated requests"},
257 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
258 { "yes|no", "", "", "" },
259 "specify whether hostnames or net numbers are printed"},
260 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
261 { "no|more|less", "", "", "" },
262 "set/change debugging level" },
263 { "quit", quit, { NO, NO, NO, NO },
266 { "exit", quit, { NO, NO, NO, NO },
269 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
270 { "key#", "", "", "" },
271 "set keyid to use for authenticated requests" },
272 { "version", version, { NO, NO, NO, NO },
274 "print version number" },
275 { "raw", raw, { NO, NO, NO, NO },
277 "do raw mode variable output" },
278 { "cooked", cooked, { NO, NO, NO, NO },
280 "do cooked mode variable output" },
281 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
282 { "yes|no", "", "", "" },
283 "always authenticate requests to this server" },
284 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
285 { "version number", "", "", "" },
286 "set the NTP version number to use for requests" },
287 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
288 { "key type %s", "", "", "" },
290 { 0, 0, { NO, NO, NO, NO },
291 { "", "", "", "" }, "" }
296 * Default values we use.
298 #define DEFHOST "localhost" /* default host name */
299 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
300 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
302 * Requests are automatically retried once, so total timeout with no
303 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
304 * extreme, a request eliciting 32 packets of responses each for some
305 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
306 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
307 * 93 seconds to fail each of two times, or 186 seconds.
308 * Some commands involve a series of requests, such as "peers" and
309 * "mrulist", so the cumulative timeouts are even longer for those.
311 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
312 #define LENHOSTNAME 256 /* host name is 256 characters long */
313 #define MAXCMDS 100 /* maximum commands on cmd line */
314 #define MAXHOSTS 200 /* maximum hosts on cmd line */
315 #define MAXLINE 512 /* maximum line length */
316 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
317 #define MAXVARLEN 256 /* maximum length of a variable name */
318 #define MAXVALLEN 2048 /* maximum length of a variable value */
319 #define MAXOUTLINE 72 /* maximum length of an output line */
320 #define SCREENWIDTH 76 /* nominal screen width in columns */
323 * Some variables used and manipulated locally
325 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
326 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
327 l_fp delay_time; /* delay time */
328 char currenthost[LENHOSTNAME]; /* current host name */
329 int currenthostisnum; /* is prior text from IP? */
330 struct sockaddr_in hostaddr; /* host address */
331 int showhostnames = 1; /* show host names by default */
332 int wideremote = 0; /* show wide remote names? */
334 int ai_fam_templ; /* address family */
335 int ai_fam_default; /* default address family */
336 SOCKET sockfd; /* fd socket is opened on */
337 int havehost = 0; /* set to 1 when host open */
339 struct servent *server_entry = NULL; /* server entry for ntp */
343 * Sequence number used for requests. It is incremented before
349 * Holds data returned from queries. Declare buffer long to be sure of
352 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
353 long pktdata[DATASIZE/sizeof(long)];
356 * assoc_cache[] is a dynamic array which allows references to
357 * associations using &1 ... &N for n associations, avoiding manual
358 * lookup of the current association IDs for a given ntpd. It also
359 * caches the status word for each association, retrieved incidentally.
361 struct association * assoc_cache;
362 u_int assoc_cache_slots;/* count of allocated array entries */
363 u_int numassoc; /* number of cached associations */
366 * For commands typed on the command line (with the -c option)
369 const char *ccmds[MAXCMDS];
370 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
373 * When multiple hosts are specified.
378 chost chosts[MAXHOSTS];
379 #define ADDHOST(cp) \
381 if (numhosts < MAXHOSTS) { \
382 chosts[numhosts].name = (cp); \
383 chosts[numhosts].fam = ai_fam_templ; \
389 * Macro definitions we use
391 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
392 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
393 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
396 * Jump buffer for longjumping back to the command level
398 jmp_buf interrupt_buf;
401 * Points at file being currently printed into
403 FILE *current_output;
406 * Command table imported from ntpdc_ops.c
408 extern struct xcmd opcmds[];
410 char const *progname;
412 #ifdef NO_MAIN_ALLOWED
414 CALL(ntpq,"ntpq",ntpqmain);
416 void clear_globals(void)
418 extern int ntp_optind;
419 showhostnames = 0; /* don'tshow host names by default */
421 server_entry = NULL; /* server entry for ntp */
422 havehost = 0; /* set to 1 when host open */
423 numassoc = 0; /* number of cached associations */
427 #endif /* !BUILD_AS_LIB */
428 #endif /* NO_MAIN_ALLOWED */
431 * main - parse arguments and handle options
433 #ifndef NO_MAIN_ALLOWED
440 return ntpqmain(argc, argv);
457 taskPrioritySet(taskIdSelf(), 100 );
461 delay_time.l_uf = DEFDELAY;
463 init_lib(); /* sets up ipv4_works, ipv6_works */
467 /* Check to see if we have IPv6. Otherwise default to IPv4 */
469 ai_fam_default = AF_INET;
471 /* Fixup keytype's help based on available digest names */
477 list = list_digest_names();
478 for (icmd = 0; icmd < sizeof(builtins)/sizeof(builtins[0]); icmd++) {
479 if (strcmp("keytype", builtins[icmd].keyword) == 0)
484 /* This should only "trip" if "keytype" is removed from builtins */
485 INSIST(icmd < sizeof(builtins)/sizeof(builtins[0]));
488 builtins[icmd].desc[0] = "digest-name";
490 "set key type to use for authenticated requests, one of:%s",
493 builtins[icmd].desc[0] = "md5";
495 "set key type to use for authenticated requests (%s)",
498 builtins[icmd].comment = msg;
505 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
511 * Process options other than -c and -p, which are specially
512 * handled by ntpq_custom_opt_handler().
515 debug = OPT_VALUE_SET_DEBUG_LEVEL;
518 ai_fam_templ = AF_INET;
519 else if (HAVE_OPT(IPV6))
520 ai_fam_templ = AF_INET6;
522 ai_fam_templ = ai_fam_default;
524 if (HAVE_OPT(INTERACTIVE))
527 if (HAVE_OPT(NUMERIC))
533 old_rv = HAVE_OPT(OLD_RV);
538 for (ihost = 0; ihost < (u_int)argc; ihost++) {
539 if ('-' == *argv[ihost]) {
541 // If I really cared I'd also check:
542 // 0 == argv[ihost][2]
544 // and there are other cases as well...
546 if ('4' == argv[ihost][1]) {
547 ai_fam_templ = AF_INET;
549 } else if ('6' == argv[ihost][1]) {
550 ai_fam_templ = AF_INET6;
553 // XXX Throw a usage error
556 ADDHOST(argv[ihost]);
560 if (numcmds == 0 && interactive == 0
561 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
565 set_ctrl_c_hook(on_ctrlc);
566 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
568 push_ctrl_c_handler(abortcmd);
569 #endif /* SYS_WINNT */
572 (void) openhost(chosts[0].name, chosts[0].fam);
575 for (ihost = 0; ihost < numhosts; ihost++) {
576 if (openhost(chosts[ihost].name, chosts[ihost].fam))
577 for (icmd = 0; icmd < numcmds; icmd++)
583 #endif /* SYS_WINNT */
586 #endif /* !BUILD_AS_LIB */
589 * openhost - open a socket to a host
597 const char svc[] = "ntp";
598 char temphost[LENHOSTNAME];
600 struct addrinfo hints, *ai;
603 register const char *cp;
604 char name[LENHOSTNAME];
607 * We need to get by the [] if they were entered
614 for (i = 0; *cp && *cp != ']'; cp++, i++)
625 * First try to resolve it as an ip address and if that fails,
626 * do a fullblown (dns) lookup. That way we only use the dns
627 * when it is needed and work around some implementations that
628 * will return an "IPv4-mapped IPv6 address" address if you
629 * give it an IPv4 address to lookup.
632 hints.ai_family = fam;
633 hints.ai_protocol = IPPROTO_UDP;
634 hints.ai_socktype = SOCK_DGRAM;
635 hints.ai_flags = Z_AI_NUMERICHOST;
638 a_info = getaddrinfo(hname, svc, &hints, &ai);
639 if (a_info == EAI_NONAME
641 || a_info == EAI_NODATA
644 hints.ai_flags = AI_CANONNAME;
646 hints.ai_flags |= AI_ADDRCONFIG;
648 a_info = getaddrinfo(hname, svc, &hints, &ai);
651 /* Some older implementations don't like AI_ADDRCONFIG. */
652 if (a_info == EAI_BADFLAGS) {
653 hints.ai_flags &= ~AI_ADDRCONFIG;
654 a_info = getaddrinfo(hname, svc, &hints, &ai);
658 fprintf(stderr, "%s\n", gai_strerror(a_info));
664 octets = min(sizeof(addr), ai->ai_addrlen);
665 memcpy(&addr, ai->ai_addr, octets);
667 if (ai->ai_canonname == NULL) {
668 strlcpy(temphost, stoa(&addr), sizeof(temphost));
669 currenthostisnum = TRUE;
671 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
672 currenthostisnum = FALSE;
676 printf("Opening host %s (%s)\n",
678 (ai->ai_family == AF_INET)
680 : (ai->ai_family == AF_INET6)
687 printf("Closing old host %s\n", currenthost);
691 strlcpy(currenthost, temphost, sizeof(currenthost));
693 /* port maps to the same location in both families */
694 s_port = NSRCPORT(&addr);
696 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
697 if (ai->ai_family == AF_INET)
698 *(struct sockaddr_in *)&hostaddr=
699 *((struct sockaddr_in *)ai->ai_addr);
701 *(struct sockaddr_in6 *)&hostaddr=
702 *((struct sockaddr_in6 *)ai->ai_addr);
703 #endif /* SYS_VXWORKS */
707 int optionValue = SO_SYNCHRONOUS_NONALERT;
710 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
711 (char *)&optionValue, sizeof(optionValue));
714 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
720 #endif /* SYS_WINNT */
722 sockfd = socket(ai->ai_family, ai->ai_socktype,
724 if (sockfd == INVALID_SOCKET) {
731 #ifdef NEED_RCVBUF_SLOP
733 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
734 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
735 &rbufsize, sizeof(int)) == -1)
743 (connect(sockfd, (struct sockaddr *)&hostaddr,
744 sizeof(hostaddr)) == -1)
746 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
747 ai->ai_addrlen) == -1)
748 #endif /* SYS_VXWORKS */
769 const char * rowstart;
777 rowlen = min(16, len);
778 for (idx = 0; idx < rowlen; idx++) {
780 printf("%02x ", uch);
782 for ( ; idx < 16 ; idx++)
785 for (idx = 0; idx < rowlen; idx++) {
787 printf("%c", (isprint(uch))
797 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
799 * sendpkt - send a packet to the remote host
808 printf("Sending %zu octets\n", xdatalen);
810 if (send(sockfd, xdata, xdatalen, 0) == -1) {
811 warning("write to %s failed", currenthost);
816 printf("Request packet:\n");
817 dump_hex_printable(xdata, xdatalen);
823 * getresponse - get a (series of) response packet(s) and return the data
835 struct ntp_control rpkt;
836 struct sock_timeval tvo;
837 u_short offsets[MAXFRAGS+1];
838 u_short counts[MAXFRAGS+1];
849 /* absolute timeout checks. Not 'time_t' by intention! */
850 uint32_t tobase; /* base value for timeout */
851 uint32_t tospan; /* timeout span (max delay) */
852 uint32_t todiff; /* current delay */
855 * This is pretty tricky. We may get between 1 and MAXFRAG packets
856 * back in response to the request. We peel the data out of
857 * each packet and collect it in one long block. When the last
858 * packet in the sequence is received we'll know how much data we
859 * should have had. Note we use one long time out, should reconsider.
864 *rdata = (char *)pktdata;
869 tobase = (uint32_t)time(NULL);
874 * Loop until we have an error or a complete response. Nearly all
875 * code paths to loop again use continue.
883 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
885 FD_SET(sockfd, &fds);
886 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
888 #if !defined(SYS_WINNT) && defined(EINTR)
889 /* Windows does not know about EINTR (until very
890 * recently) and the handling of console events
891 * is *very* different from POSIX/UNIX signal
894 * Under non-windows targets we map EINTR as
895 * 'last packet was received' and try to exit
896 * the receive sequence.
898 if (errno == EINTR) {
903 warning("select fails");
908 * Check if this is already too late. Trash the data and
909 * fake a timeout if this is so.
911 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
912 if ((n > 0) && (todiff > tospan)) {
913 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
914 n = 0; /* faked timeout return from 'select()'*/
919 * Timed out. Return what we have
924 "%s: timed out, nothing received\n",
930 "%s: timed out with incomplete data\n",
934 "ERR_INCOMPLETE: Received fragments:\n");
935 for (f = 0; f < numfrags; f++)
937 "%2u: %5d %5d\t%3d octets\n",
938 (u_int)f, offsets[f],
943 "last fragment %sreceived\n",
948 return ERR_INCOMPLETE;
951 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
958 printf("Response packet:\n");
959 dump_hex_printable(&rpkt, n);
963 * Check for format errors. Bug proofing.
965 if (n < (int)CTL_HEADER_LEN) {
967 printf("Short (%d byte) packet received\n", n);
970 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
971 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
973 printf("Packet received with version %d\n",
974 PKT_VERSION(rpkt.li_vn_mode));
977 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
979 printf("Packet received with mode %d\n",
980 PKT_MODE(rpkt.li_vn_mode));
983 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
985 printf("Received request packet, wanted response\n");
990 * Check opcode and sequence number for a match.
991 * Could be old data getting to us.
993 if (ntohs(rpkt.sequence) != sequence) {
995 printf("Received sequnce number %d, wanted %d\n",
996 ntohs(rpkt.sequence), sequence);
999 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1002 "Received opcode %d, wanted %d (sequence number okay)\n",
1003 CTL_OP(rpkt.r_m_e_op), opcode);
1008 * Check the error code. If non-zero, return it.
1010 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1011 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1012 if (CTL_ISMORE(rpkt.r_m_e_op))
1013 TRACE(1, ("Error code %d received on not-final packet\n",
1015 if (errcode == CERR_UNSPEC)
1021 * Check the association ID to make sure it matches what
1024 if (ntohs(rpkt.associd) != associd) {
1025 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1026 ntohs(rpkt.associd), associd));
1028 * Hack for silly fuzzballs which, at the time of writing,
1029 * return an assID of sys.peer when queried for system variables.
1037 * Collect offset and count. Make sure they make sense.
1039 offset = ntohs(rpkt.offset);
1040 count = ntohs(rpkt.count);
1043 * validate received payload size is padded to next 32-bit
1044 * boundary and no smaller than claimed by rpkt.count
1047 TRACE(1, ("Response packet not padded, size = %d\n",
1052 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1054 if (n < shouldbesize) {
1055 printf("Response packet claims %u octets payload, above %ld received\n",
1056 count, (long)n - CTL_HEADER_LEN);
1057 return ERR_INCOMPLETE;
1060 if (debug >= 3 && shouldbesize > n) {
1066 * Usually we ignore authentication, but for debugging purposes
1069 /* round to 8 octet boundary */
1070 shouldbesize = (shouldbesize + 7) & ~7;
1072 maclen = n - shouldbesize;
1073 if (maclen >= (int)MIN_MAC_LEN) {
1075 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1076 n, shouldbesize, maclen);
1077 lpkt = (u_int32 *)&rpkt;
1078 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1079 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1080 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1081 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1082 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1083 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1084 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1085 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1086 printf("Authenticated with keyid %lu\n", (u_long)key);
1087 if (key != 0 && key != info_auth_keyid) {
1088 printf("We don't know that key\n");
1090 if (authdecrypt(key, (u_int32 *)&rpkt,
1091 n - maclen, maclen)) {
1092 printf("Auth okay!\n");
1094 printf("Auth failed!\n");
1100 TRACE(2, ("Got packet, size = %d\n", n));
1101 if (count > (n - CTL_HEADER_LEN)) {
1102 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1103 count, (long)n - CTL_HEADER_LEN));
1106 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1107 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1110 if (offset + count > sizeof(pktdata)) {
1111 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1115 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1116 TRACE(1, ("Received second last fragment packet\n"));
1121 * So far, so good. Record this fragment, making sure it doesn't
1124 TRACE(2, ("Packet okay\n"));
1126 if (numfrags > (MAXFRAGS - 1)) {
1127 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1133 * Find the position for the fragment relative to any
1134 * previously received.
1137 f < numfrags && offsets[f] < offset;
1142 if (f < numfrags && offset == offsets[f]) {
1143 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1144 count, offset, counts[f], offsets[f]));
1148 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1149 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1150 offset, counts[f-1], offsets[f-1]));
1154 if (f < numfrags && (offset + count) > offsets[f]) {
1155 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1156 count, offset, offsets[f]));
1160 for (ff = numfrags; ff > f; ff--) {
1161 offsets[ff] = offsets[ff-1];
1162 counts[ff] = counts[ff-1];
1164 offsets[f] = offset;
1169 * Got that stuffed in right. Figure out if this was the last.
1170 * Record status info out of the last packet.
1172 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1175 *rstatus = ntohs(rpkt.status);
1179 * Copy the data into the data buffer, and bump the
1180 * timout base in case we need more.
1182 memcpy((char *)pktdata + offset, &rpkt.u, count);
1183 tobase = (uint32_t)time(NULL);
1186 * If we've seen the last fragment, look for holes in the sequence.
1187 * If there aren't any, we're done.
1190 if (seenlastfrag && offsets[0] == 0) {
1191 for (f = 1; f < numfrags; f++)
1192 if (offsets[f-1] + counts[f-1] !=
1195 if (f == numfrags) {
1196 *rsize = offsets[f-1] + counts[f-1];
1197 TRACE(1, ("%lu packets reassembled into response\n",
1202 } /* giant for (;;) collecting response packets */
1203 } /* getresponse() */
1207 * sendrequest - format and send a request packet
1218 struct ntp_control qpkt;
1225 * Check to make sure the data will fit in one packet
1227 if (qsize > CTL_MAX_DATA_LEN) {
1229 "***Internal error! qsize (%zu) too large\n",
1235 * Fill in the packet
1237 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1238 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1239 qpkt.sequence = htons(sequence);
1241 qpkt.associd = htons((u_short)associd);
1243 qpkt.count = htons((u_short)qsize);
1245 pktsize = CTL_HEADER_LEN;
1248 * If we have data, copy and pad it out to a 32-bit boundary.
1251 memcpy(&qpkt.u, qdata, (size_t)qsize);
1253 while (pktsize & (sizeof(u_int32) - 1)) {
1254 qpkt.u.data[qsize++] = 0;
1260 * If it isn't authenticated we can just send it. Otherwise
1261 * we're going to have to think about it a little.
1263 if (!auth && !always_auth) {
1264 return sendpkt(&qpkt, pktsize);
1268 * Pad out packet to a multiple of 8 octets to be sure
1269 * receiver can handle it.
1271 while (pktsize & 7) {
1272 qpkt.u.data[qsize++] = 0;
1277 * Get the keyid and the password if we don't have one.
1279 if (info_auth_keyid == 0) {
1280 key_id = getkeyid("Keyid: ");
1281 if (key_id == 0 || key_id > NTP_MAXKEY) {
1283 "Invalid key identifier\n");
1286 info_auth_keyid = key_id;
1288 if (!authistrusted(info_auth_keyid)) {
1289 pass = getpass_keytype(info_auth_keytype);
1290 if ('\0' == pass[0]) {
1291 fprintf(stderr, "Invalid password\n");
1294 authusekey(info_auth_keyid, info_auth_keytype,
1296 authtrust(info_auth_keyid, 1);
1300 * Do the encryption.
1302 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1304 fprintf(stderr, "Key not found\n");
1306 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1308 "%zu octet MAC, %zu expected with %zu octet digest\n",
1309 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1314 return sendpkt((char *)&qpkt, pktsize + maclen);
1319 * show_error_msg - display the error text for a mode 6 error response.
1328 fprintf(stderr, "server=%s ", currenthost);
1334 "***Server reports a bad format request packet\n");
1337 case CERR_PERMISSION:
1339 "***Server disallowed request (authentication?)\n");
1344 "***Server reports a bad opcode in request\n");
1349 "***Association ID %d unknown to server\n",
1353 case CERR_UNKNOWNVAR:
1355 "***A request variable unknown to the server\n");
1360 "***Server indicates a request variable was bad\n");
1365 "***Server returned an unspecified error\n");
1369 fprintf(stderr, "***Request timed out\n");
1372 case ERR_INCOMPLETE:
1374 "***Response from server was incomplete\n");
1379 "***Buffer size exceeded for returned data\n");
1384 "***Server returns unknown error code %d\n",
1390 * doquery - send a request and process the response, displaying
1391 * error messages for any error responses.
1405 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1406 rsize, rdata, FALSE);
1411 * doqueryex - send a request and process the response, optionally
1412 * displaying error messages for any error responses.
1431 * Check to make sure host is open
1434 fprintf(stderr, "***No host open, use `host' command\n");
1445 res = sendrequest(opcode, associd, auth, qsize, qdata);
1450 * Get the response. If we got a standard error, print a message
1452 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1455 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1456 if (res == ERR_INCOMPLETE) {
1458 * better bump the sequence so we don't
1459 * get confused about differing fragments.
1467 show_error_msg(res, associd);
1474 #ifndef BUILD_AS_LIB
1476 * getcmds - read commands from the standard input and execute them
1484 ntp_readline_init(interactive ? prompt : NULL);
1487 line = ntp_readline(&count);
1494 ntp_readline_uninit();
1496 #endif /* !BUILD_AS_LIB */
1499 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1501 * abortcmd - catch interrupts and abort the current command
1506 if (current_output == stdout)
1507 (void) fflush(stdout);
1509 (void) fflush(stderr);
1512 longjmp(interrupt_buf, 1);
1516 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1519 #ifndef BUILD_AS_LIB
1521 * docmd - decode the command line and execute a command
1528 char *tokens[1+MAXARGS+2];
1535 * Tokenize the command line. If nothing on it, return.
1537 tokenize(cmdline, tokens, &ntok);
1542 * Find the appropriate command description.
1544 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1546 (void) fprintf(stderr, "***Command `%s' unknown\n",
1549 } else if (i >= 2) {
1550 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1555 /* Warn about ignored extra args */
1556 for (i = MAXARGS + 1; i < ntok ; ++i) {
1557 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1561 * Save the keyword, then walk through the arguments, interpreting
1564 pcmd.keyword = tokens[0];
1566 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1567 if ((i+1) >= ntok) {
1568 if (!(xcmd->arg[i] & OPT)) {
1569 printusage(xcmd, stderr);
1574 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1576 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1582 if (i < ntok && *tokens[i] == '>') {
1585 if (*(tokens[i]+1) != '\0')
1586 fname = tokens[i]+1;
1587 else if ((i+1) < ntok)
1588 fname = tokens[i+1];
1590 (void) fprintf(stderr, "***No file for redirect\n");
1594 current_output = fopen(fname, "w");
1595 if (current_output == NULL) {
1596 (void) fprintf(stderr, "***Error opening %s: ", fname);
1600 i = 1; /* flag we need a close */
1602 current_output = stdout;
1603 i = 0; /* flag no close */
1606 if (interactive && setjmp(interrupt_buf)) {
1611 (xcmd->handler)(&pcmd, current_output);
1612 jump = 0; /* HMS: 961106: was after fclose() */
1613 if (i) (void) fclose(current_output);
1621 * tokenize - turn a command line into tokens
1623 * SK: Modified to allow a quoted string
1625 * HMS: If the first character of the first token is a ':' then (after
1626 * eating inter-token whitespace) the 2nd token is the rest of the line.
1636 register const char *cp;
1638 static char tspace[MAXLINE];
1642 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1645 /* Skip inter-token whitespace */
1646 while (ISSPACE(*cp))
1649 /* If we're at EOL we're done */
1653 /* If this is the 2nd token and the first token begins
1654 * with a ':', then just grab to EOL.
1657 if (*ntok == 1 && tokens[0][0] == ':') {
1659 if (sp - tspace >= MAXLINE)
1662 } while (!ISEOL(*cp));
1665 /* Check if this token begins with a double quote.
1666 * If yes, continue reading till the next double quote
1668 else if (*cp == '\"') {
1671 if (sp - tspace >= MAXLINE)
1674 } while ((*cp != '\"') && !ISEOL(*cp));
1675 /* HMS: a missing closing " should be an error */
1679 if (sp - tspace >= MAXLINE)
1682 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1683 /* HMS: Why check for a " in the previous line? */
1686 if (sp - tspace >= MAXLINE)
1695 "***Line `%s' is too big\n",
1702 * getarg - interpret an argument token
1713 switch (code & ~OPT) {
1719 if (!getnetnum(str, &argp->netnum, NULL, 0))
1724 if ('&' == str[0]) {
1725 if (!atouint(&str[1], &ul)) {
1727 "***Association index `%s' invalid/undecodable\n",
1731 if (0 == numassoc) {
1733 if (0 == numassoc) {
1735 "***No associations found, `%s' unknown\n",
1740 ul = min(ul, numassoc);
1741 argp->uval = assoc_cache[ul - 1].assid;
1744 if (!atouint(str, &argp->uval)) {
1745 fprintf(stderr, "***Illegal unsigned value %s\n",
1752 if (!atoint(str, &argp->ival)) {
1753 fprintf(stderr, "***Illegal integer value %s\n",
1760 if (!strcmp("-6", str)) {
1762 } else if (!strcmp("-4", str)) {
1765 fprintf(stderr, "***Version must be either 4 or 6\n");
1773 #endif /* !BUILD_AS_LIB */
1777 * findcmd - find a command in a command description table
1782 struct xcmd * clist1,
1783 struct xcmd * clist2,
1790 struct xcmd *nearmatch = NULL;
1797 else if (clist2 != 0)
1803 for (cl = clist; cl->keyword != 0; cl++) {
1804 /* do a first character check, for efficiency */
1805 if (*str != *(cl->keyword))
1807 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1809 * Could be extact match, could be approximate.
1810 * Is exact if the length of the keyword is the
1813 if (*((cl->keyword) + clen) == '\0') {
1823 * See if there is more to do. If so, go again. Sorry about the
1824 * goto, too much looking at BSD sources...
1826 if (clist == clist1 && clist2 != 0) {
1832 * If we got extactly 1 near match, use it, else return number
1844 * getnetnum - given a host name, return its net number
1845 * and (optional) full name
1855 struct addrinfo hints, *ai = NULL;
1858 hints.ai_flags = AI_CANONNAME;
1859 #ifdef AI_ADDRCONFIG
1860 hints.ai_flags |= AI_ADDRCONFIG;
1864 * decodenetnum only works with addresses, but handles syntax
1865 * that getaddrinfo doesn't: [2001::1]:1234
1867 if (decodenetnum(hname, num)) {
1868 if (fullhost != NULL)
1869 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1870 LENHOSTNAME, NULL, 0, 0);
1872 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1873 INSIST(sizeof(*num) >= ai->ai_addrlen);
1874 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1875 if (fullhost != NULL) {
1876 if (ai->ai_canonname != NULL)
1877 strlcpy(fullhost, ai->ai_canonname,
1880 getnameinfo(&num->sa, SOCKLEN(num),
1881 fullhost, LENHOSTNAME, NULL,
1887 fprintf(stderr, "***Can't find host %s\n", hname);
1894 * nntohost - convert network number to host name. This routine enforces
1895 * the showhostnames setting.
1902 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1907 * nntohost_col - convert network number to host name in fixed width.
1908 * This routine enforces the showhostnames setting.
1909 * When displaying hostnames longer than the width,
1910 * the first part of the hostname is displayed. When
1911 * displaying numeric addresses longer than the width,
1912 * Such as IPv6 addresses, the caller decides whether
1913 * the first or last of the numeric address is used.
1919 int preserve_lowaddrbits
1924 if (!showhostnames || SOCK_UNSPEC(addr)) {
1925 if (preserve_lowaddrbits)
1926 out = trunc_left(stoa(addr), width);
1928 out = trunc_right(stoa(addr), width);
1929 } else if (ISREFCLOCKADR(addr)) {
1930 out = refnumtoa(addr);
1932 out = trunc_right(socktohost(addr), width);
1939 * nntohostp() is the same as nntohost() plus a :port suffix
1949 if (!showhostnames || SOCK_UNSPEC(netnum))
1950 return sptoa(netnum);
1951 else if (ISREFCLOCKADR(netnum))
1952 return refnumtoa(netnum);
1954 hostn = socktohost(netnum);
1956 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1962 * rtdatetolfp - decode an RT-11 date into an l_fp
1972 struct calendar cal;
1978 * An RT-11 date looks like:
1980 * d[d]-Mth-y[y] hh:mm:ss
1982 * (No docs, but assume 4-digit years are also legal...)
1984 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
1987 if (!isdigit((int)*cp)) {
1990 * Catch special case
1998 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
1999 if (isdigit((int)*cp)) {
2000 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2001 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2007 for (i = 0; i < 3; i++)
2011 for (i = 0; i < 12; i++)
2012 if (STREQ(buf, months[i]))
2016 cal.month = (u_char)(i + 1);
2021 if (!isdigit((int)*cp))
2023 cal.year = (u_short)(*cp++ - '0');
2024 if (isdigit((int)*cp)) {
2025 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2026 cal.year = (u_short)(*cp++ - '0');
2028 if (isdigit((int)*cp)) {
2029 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2030 cal.year = (u_short)(cal.year + *cp++ - '0');
2032 if (isdigit((int)*cp)) {
2033 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2034 cal.year = (u_short)(cal.year + *cp++ - '0');
2038 * Catch special case. If cal.year == 0 this is a zero timestamp.
2040 if (cal.year == 0) {
2045 if (*cp++ != ' ' || !isdigit((int)*cp))
2047 cal.hour = (u_char)(*cp++ - '0');
2048 if (isdigit((int)*cp)) {
2049 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2050 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2053 if (*cp++ != ':' || !isdigit((int)*cp))
2055 cal.minute = (u_char)(*cp++ - '0');
2056 if (isdigit((int)*cp)) {
2057 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2058 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2061 if (*cp++ != ':' || !isdigit((int)*cp))
2063 cal.second = (u_char)(*cp++ - '0');
2064 if (isdigit((int)*cp)) {
2065 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2066 cal.second = (u_char)(cal.second + *cp++ - '0');
2070 * For RT-11, 1972 seems to be the pivot year
2077 lfp->l_ui = caltontp(&cal);
2084 * decodets - decode a timestamp into an l_fp format number, with
2085 * consideration of fuzzball formats.
2098 * If it starts with a 0x, decode as hex.
2100 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2101 return hextolfp(str+2, lfp);
2104 * If it starts with a '"', try it as an RT-11 date.
2109 while ('"' != *cp && '\0' != *cp &&
2110 b < COUNTOF(buf) - 1)
2113 return rtdatetolfp(buf, lfp);
2117 * Might still be hex. Check out the first character. Talk
2120 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2121 return hextolfp(str, lfp);
2124 * Try it as a decimal. If this fails, try as an unquoted
2125 * RT-11 date. This code should go away eventually.
2127 if (atolfp(str, lfp))
2130 return rtdatetolfp(str, lfp);
2135 * decodetime - decode a time value. It should be in milliseconds
2143 return mstolfp(str, lfp);
2148 * decodeint - decode an integer
2157 if (*(str+1) == 'x' || *(str+1) == 'X')
2158 return hextoint(str+2, (u_long *)val);
2159 return octtoint(str, (u_long *)val);
2161 return atoint(str, val);
2166 * decodeuint - decode an unsigned integer
2175 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2176 return (hextoint(str + 2, val));
2177 return (octtoint(str, val));
2179 return (atouint(str, val));
2184 * decodearr - decode an array of time values
2193 register char *cp, *bp;
2202 while (isspace((int)*cp))
2208 while (!isspace((int)*cp) && *cp != '\0')
2212 if (!decodetime(buf, lfp))
2222 * Finally, the built in command handlers
2226 * help - tell about commands, or details of a particular command
2234 struct xcmd *xcp = NULL; /* quiet warning */
2236 const char *list[100];
2242 if (pcmd->nargs == 0) {
2244 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2245 if (*(xcp->keyword) != '?' &&
2246 words < COUNTOF(list))
2247 list[words++] = xcp->keyword;
2249 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2250 if (words < COUNTOF(list))
2251 list[words++] = xcp->keyword;
2253 qsort((void *)list, words, sizeof(list[0]), helpsort);
2255 for (word = 0; word < words; word++) {
2256 length = strlen(list[word]);
2257 col = max(col, length);
2260 cols = SCREENWIDTH / ++col;
2261 rows = (words + cols - 1) / cols;
2263 fprintf(fp, "ntpq commands:\n");
2265 for (row = 0; row < rows; row++) {
2266 for (word = row; word < words; word += rows)
2267 fprintf(fp, "%-*.*s", (int)col,
2268 (int)col - 1, list[word]);
2272 cmd = pcmd->argval[0].string;
2273 words = findcmd(cmd, builtins, opcmds, &xcp);
2276 "Command `%s' is unknown\n", cmd);
2278 } else if (words >= 2) {
2280 "Command `%s' is ambiguous\n", cmd);
2283 fprintf(fp, "function: %s\n", xcp->comment);
2284 printusage(xcp, fp);
2290 * helpsort - do hostname qsort comparisons
2298 const char * const * name1 = t1;
2299 const char * const * name2 = t2;
2301 return strcmp(*name1, *name2);
2306 * printusage - print usage information for a command
2316 /* XXX: Do we need to warn about extra args here too? */
2318 (void) fprintf(fp, "usage: %s", xcp->keyword);
2319 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2320 if (xcp->arg[i] & OPT)
2321 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2323 (void) fprintf(fp, " %s", xcp->desc[i]);
2325 (void) fprintf(fp, "\n");
2330 * timeout - set time out time
2340 if (pcmd->nargs == 0) {
2341 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2342 (void) fprintf(fp, "primary timeout %d ms\n", val);
2344 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2345 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2352 * auth_delay - set delay for auth requests
2363 if (pcmd->nargs == 0) {
2364 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2365 (void) fprintf(fp, "delay %lu ms\n", val);
2367 if (pcmd->argval[0].ival < 0) {
2369 val = (u_long)(-pcmd->argval[0].ival);
2372 val = (u_long)pcmd->argval[0].ival;
2375 delay_time.l_ui = val / 1000;
2377 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2386 * host - set the host we are dealing with.
2396 if (pcmd->nargs == 0) {
2398 (void) fprintf(fp, "current host is %s\n",
2401 (void) fprintf(fp, "no current host\n");
2406 ai_fam_templ = ai_fam_default;
2407 if (pcmd->nargs == 2) {
2408 if (!strcmp("-4", pcmd->argval[i].string))
2409 ai_fam_templ = AF_INET;
2410 else if (!strcmp("-6", pcmd->argval[i].string))
2411 ai_fam_templ = AF_INET6;
2416 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2417 fprintf(fp, "current host set to %s\n", currenthost);
2421 fprintf(fp, "current host remains %s\n",
2424 fprintf(fp, "still no current host\n");
2430 * poll - do one (or more) polls of the host via NTP
2439 (void) fprintf(fp, "poll not implemented yet\n");
2444 * keyid - get a keyid to use for authenticating requests
2452 if (pcmd->nargs == 0) {
2453 if (info_auth_keyid == 0)
2454 (void) fprintf(fp, "no keyid defined\n");
2456 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2458 /* allow zero so that keyid can be cleared. */
2459 if(pcmd->argval[0].uval > NTP_MAXKEY)
2460 (void) fprintf(fp, "Invalid key identifier\n");
2461 info_auth_keyid = pcmd->argval[0].uval;
2466 * keytype - get type of key to use for authenticating requests
2474 const char * digest_name;
2479 fprintf(fp, "keytype is %s with %lu octet digests\n",
2480 keytype_name(info_auth_keytype),
2481 (u_long)info_auth_hashlen);
2485 digest_name = pcmd->argval[0].string;
2487 key_type = keytype_from_text(digest_name, &digest_len);
2490 fprintf(fp, "keytype is not valid. "
2492 "Type \"help keytype\" for the available digest types.\n");
2494 "Only \"md5\" is available.\n");
2499 info_auth_keytype = key_type;
2500 info_auth_hashlen = digest_len;
2505 * passwd - get an authentication key
2516 if (info_auth_keyid == 0) {
2517 info_auth_keyid = getkeyid("Keyid: ");
2518 if (info_auth_keyid == 0) {
2519 (void)fprintf(fp, "Keyid must be defined\n");
2523 if (pcmd->nargs >= 1)
2524 pass = pcmd->argval[0].string;
2526 pass = getpass_keytype(info_auth_keytype);
2527 if ('\0' == pass[0]) {
2528 fprintf(fp, "Password unchanged\n");
2532 authusekey(info_auth_keyid, info_auth_keytype,
2533 (const u_char *)pass);
2534 authtrust(info_auth_keyid, 1);
2539 * hostnames - set the showhostnames flag
2547 if (pcmd->nargs == 0) {
2549 (void) fprintf(fp, "hostnames being shown\n");
2551 (void) fprintf(fp, "hostnames not being shown\n");
2553 if (STREQ(pcmd->argval[0].string, "yes"))
2555 else if (STREQ(pcmd->argval[0].string, "no"))
2558 (void)fprintf(stderr, "What?\n");
2565 * setdebug - set/change debugging level
2573 if (pcmd->nargs == 0) {
2574 (void) fprintf(fp, "debug level is %d\n", debug);
2576 } else if (STREQ(pcmd->argval[0].string, "no")) {
2578 } else if (STREQ(pcmd->argval[0].string, "more")) {
2580 } else if (STREQ(pcmd->argval[0].string, "less")) {
2583 (void) fprintf(fp, "What?\n");
2586 (void) fprintf(fp, "debug level set to %d\n", debug);
2591 * quit - stop this nonsense
2601 closesocket(sockfd); /* cleanliness next to godliness */
2607 * version - print the current version number
2617 (void) fprintf(fp, "%s\n", Version);
2623 * raw - set raw mode output
2633 (void) fprintf(fp, "Output set to raw\n");
2638 * cooked - set cooked mode output
2648 (void) fprintf(fp, "Output set to cooked\n");
2654 * authenticate - always authenticate requests to this host
2662 if (pcmd->nargs == 0) {
2665 "authenticated requests being sent\n");
2668 "unauthenticated requests being sent\n");
2670 if (STREQ(pcmd->argval[0].string, "yes")) {
2672 } else if (STREQ(pcmd->argval[0].string, "no")) {
2675 (void)fprintf(stderr, "What?\n");
2681 * ntpversion - choose the NTP version to use
2689 if (pcmd->nargs == 0) {
2691 "NTP version being claimed is %d\n", pktversion);
2693 if (pcmd->argval[0].uval < NTP_OLDVERSION
2694 || pcmd->argval[0].uval > NTP_VERSION) {
2695 (void) fprintf(stderr, "versions %d to %d, please\n",
2696 NTP_OLDVERSION, NTP_VERSION);
2698 pktversion = (u_char) pcmd->argval[0].uval;
2704 static void __attribute__((__format__(__printf__, 1, 0)))
2705 vwarning(const char *fmt, va_list ap)
2708 (void) fprintf(stderr, "%s: ", progname);
2709 vfprintf(stderr, fmt, ap);
2710 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2714 * warning - print a warning message
2716 static void __attribute__((__format__(__printf__, 1, 2)))
2730 * error - print a message and exit
2732 static void __attribute__((__format__(__printf__, 1, 2)))
2745 * getkeyid - prompt the user for a keyid to use
2749 const char *keyprompt
2759 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2761 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2762 #endif /* SYS_WINNT */
2765 setbuf(fi, (char *)NULL);
2766 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2767 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2768 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2770 pbuf[i++] = (char)c;
2775 return (u_long) atoi(pbuf);
2780 * atoascii - printable-ize possibly ascii data using the character
2781 * transformations cat -v uses.
2791 const u_char * pchIn;
2792 const u_char * pchInLimit;
2796 pchIn = (const u_char *)in;
2797 pchInLimit = pchIn + in_octets;
2798 pchOut = (u_char *)out;
2800 if (NULL == pchIn) {
2808 if (0 == --out_octets) { \
2815 for ( ; pchIn < pchInLimit; pchIn++) {
2826 ONEOUT((u_char)(c + '@'));
2827 } else if (0x7f == c) {
2840 * makeascii - print possibly ascii data using the character
2841 * transformations that cat -v uses.
2850 const u_char *data_u_char;
2854 data_u_char = (const u_char *)data;
2856 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2867 } else if (0x7f == c) {
2877 * asciize - same thing as makeascii except add a newline
2886 makeascii(length, data, fp);
2892 * truncate string to fit clipping excess at end.
2893 * "too long" -> "too l"
2894 * Used for hostnames.
2907 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2909 memcpy(out, src, width);
2920 * truncate string to fit by preserving right side and using '_' to hint
2921 * "too long" -> "_long"
2922 * Used for local IPv6 addresses, where low bits differentiate.
2935 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2938 memcpy(&out[1], &src[sl + 1 - width], width);
2948 * Some circular buffer space
2953 char circ_buf[NUMCB][CBLEN];
2957 * nextvar - find the next variable in the buffer
2972 static char name[MAXVARLEN];
2973 static char value[MAXVALLEN];
2976 cpend = cp + *datalen;
2979 * Space past commas and white space
2981 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
2987 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
2988 * over any white space and terminate it.
2990 srclen = strcspn(cp, ",=\r\n");
2991 srclen = min(srclen, (size_t)(cpend - cp));
2993 while (len > 0 && isspace((unsigned char)cp[len - 1]))
2995 if (len >= sizeof(name))
2998 memcpy(name, cp, len);
3004 * Check if we hit the end of the buffer or a ','. If so we are done.
3006 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
3010 *datalen = size2int_sat(cpend - cp);
3016 * So far, so good. Copy out the value
3018 cp++; /* past '=' */
3019 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
3025 } while (np < cpend && '"' != *np);
3026 if (np < cpend && '"' == *np)
3029 while (np < cpend && ',' != *np && '\r' != *np)
3033 if (np > cpend || len >= sizeof(value) ||
3034 (np < cpend && ',' != *np && '\r' != *np))
3036 memcpy(value, cp, len);
3038 * Trim off any trailing whitespace
3040 while (len > 0 && isspace((unsigned char)value[len - 1]))
3045 * Return this. All done.
3047 if (np < cpend && ',' == *np)
3050 *datalen = size2int_sat(cpend - np);
3057 varfmt(const char * varname)
3061 for (n = 0; n < COUNTOF(cookedvars); n++)
3062 if (!strcmp(varname, cookedvars[n].varname))
3063 return cookedvars[n].fmt;
3070 * printvars - print variables returned in response packet
3083 rawprint(sttype, length, data, status, quiet, fp);
3085 cookedprint(sttype, length, data, status, quiet, fp);
3090 * rawprint - do a printout of the data in raw mode
3106 * Essentially print the data as is. We reformat unprintables, though.
3109 cpend = data + length;
3112 (void) fprintf(fp, "status=0x%04x,\n", status);
3114 while (cp < cpend) {
3117 * If this is a \r and the next character is a
3118 * \n, supress this, else pretty print it. Otherwise
3119 * just output the character.
3121 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3122 makeascii(1, cp, fp);
3123 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3126 makeascii(1, cp, fp);
3133 * Global data used by the cooked output routines
3135 int out_chars; /* number of characters output */
3136 int out_linecount; /* number of characters output on this line */
3140 * startoutput - get ready to do cooked output
3151 * output - output a variable=value combination
3162 /* strlen of "name=value" */
3163 len = size2int_sat(strlen(name) + 1 + strlen(value));
3165 if (out_chars != 0) {
3167 if ((out_linecount + len + 2) > MAXOUTLINE) {
3180 out_linecount += len;
3185 * endoutput - terminate a block of cooked output
3198 * outputarr - output an array of values
3216 * Hack to align delay and offset values
3218 for (i = (int)strlen(name); i < 11; i++)
3221 for (i = narr; i > 0; i--) {
3224 cp = lfptoms(lfp, 2);
3239 output(fp, name, buf);
3247 register char *cp, *s;
3250 register const char *sep;
3253 s = cp = circ_buf[nextcb];
3254 if (++nextcb >= NUMCB)
3256 cb = sizeof(circ_buf[0]);
3258 snprintf(cp, cb, "%02lx", val);
3262 strlcat(cp, " ok", cb);
3270 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3272 snprintf(cp, cb, "%s%s", sep,
3288 * cookedprint - output variables in cooked mode
3311 char bn[2 * MAXVARLEN];
3312 char bv[2 * MAXVALLEN];
3314 UNUSED_ARG(datatype);
3317 fprintf(fp, "status=%04x %s,\n", status,
3318 statustoa(datatype, status));
3321 while (nextvar(&length, &data, &name, &value)) {
3331 if (!decodets(value, &lfp))
3334 output(fp, name, prettydate(&lfp));
3337 case HA: /* fallthru */
3339 if (!decodenetnum(value, &hval)) {
3341 } else if (fmt == HA){
3342 output(fp, name, nntohost(&hval));
3344 output(fp, name, stoa(&hval));
3349 if (decodenetnum(value, &hval)) {
3350 if (ISREFCLOCKADR(&hval))
3354 output(fp, name, stoa(&hval));
3355 } else if (strlen(value) <= 4) {
3356 output(fp, name, value);
3363 if (!decodeuint(value, &uval) || uval > 3) {
3373 output(fp, name, b);
3378 if (!decodeuint(value, &uval)) {
3381 snprintf(b, sizeof(b), "%03lo", uval);
3382 output(fp, name, b);
3387 if (!decodearr(value, &narr, lfparr))
3390 outputarr(fp, name, narr, lfparr);
3394 if (!decodeuint(value, &uval))
3397 output(fp, name, tstflags(uval));
3401 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3407 if (output_raw != 0) {
3408 /* TALOS-CAN-0063: avoid buffer overrun */
3409 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3410 if (output_raw != '*') {
3411 atoascii(value, MAXVALLEN,
3412 bv, sizeof(bv) - 1);
3414 bv[len] = output_raw;
3417 atoascii(value, MAXVALLEN,
3428 * sortassoc - sort associations in the cache into ascending order
3434 qsort(assoc_cache, (size_t)numassoc,
3435 sizeof(assoc_cache[0]), &assoccmp);
3440 * assoccmp - compare two associations
3448 const struct association *ass1 = t1;
3449 const struct association *ass2 = t2;
3451 if (ass1->assid < ass2->assid)
3453 if (ass1->assid > ass2->assid)
3460 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3462 * The strategy is to add an assumed 4k page size at a time, leaving
3463 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3466 grow_assoc_cache(void)
3468 static size_t prior_sz;
3471 new_sz = prior_sz + 4 * 1024;
3472 if (0 == prior_sz) {
3473 new_sz -= 4 * sizeof(void *);
3475 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3477 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3482 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3484 * By default, autoopts loses the relative order of -c and -p options
3485 * on the command line. This routine replaces the default handler for
3486 * those routines and builds a list of commands to execute preserving
3490 ntpq_custom_opt_handler(
3495 switch (pOptDesc->optValue) {
3499 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3500 pOptDesc->optValue, pOptDesc->optValue);
3504 ADDCMD(pOptDesc->pzLastArg);
3513 * Obtain list of digest names
3517 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3523 #define K_PER_LINE 8
3524 #define K_NL_PFX_STR "\n "
3525 #define K_DELIM_STR ", "
3526 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3529 const char *name, *cp, **seen;
3530 struct hstate *hstate = arg;
3533 u_char digest[EVP_MAX_MD_SIZE];
3536 return; /* Ignore aliases */
3538 name = EVP_MD_name(m);
3540 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3542 for( cp = name; *cp; cp++ ) {
3546 len = (cp - name) + 1;
3548 /* There are duplicates. Discard if name has been seen. */
3550 for (seen = hstate->seen; *seen; seen++)
3551 if (!strcmp(*seen, name))
3553 n = (seen - hstate->seen) + 2;
3554 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3555 hstate->seen[n-2] = name;
3556 hstate->seen[n-1] = NULL;
3558 /* Discard MACs that NTP won't accept.
3559 * Keep this consistent with keytype_from_text() in ssl_init.c.
3562 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3563 EVP_DigestFinal(&ctx, digest, &digest_len);
3564 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3567 if (hstate->list != NULL)
3568 len += strlen(hstate->list);
3569 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3571 if (hstate->list == NULL) {
3572 hstate->list = (char *)emalloc(len);
3573 hstate->list[0] = '\0';
3575 hstate->list = (char *)erealloc(hstate->list, len);
3577 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3578 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3580 if (hstate->idx >= K_PER_LINE)
3588 static char *list_digest_names(void)
3593 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3594 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3596 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3599 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3603 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3604 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3607 list = (char *)emalloc(sizeof("md5"));
3608 strcpy(list, "md5");
3614 #define CTRLC_STACK_MAX 4
3615 static volatile size_t ctrlc_stack_len = 0;
3616 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3621 push_ctrl_c_handler(
3625 size_t size = ctrlc_stack_len;
3626 if (func && (size < CTRLC_STACK_MAX)) {
3627 ctrlc_stack[size] = func;
3628 ctrlc_stack_len = size + 1;
3639 size_t size = ctrlc_stack_len;
3642 if (func == NULL || func == ctrlc_stack[size]) {
3643 ctrlc_stack_len = size;
3653 size_t size = ctrlc_stack_len;
3655 if ((*ctrlc_stack[--size])())
3669 char * buf = emalloc(len);
3672 /* Note: we expect the memory allocation to fail long before the
3673 * increment in buffer size actually overflows.
3675 buf = (buf) ? erealloc(buf, len) : emalloc(len);
3678 prc = vsnprintf(buf, len, fmt, va);
3682 /* might be very old vsnprintf. Or actually MSVC... */
3686 if ((size_t)prc >= len) {
3687 /* at least we have the proper size now... */
3688 len = (size_t)prc + 1;
3691 if ((size_t)prc < (len - 32))
3692 buf = erealloc(buf, (size_t)prc + 1);