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 *);
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";
489 fmt = "set key type to use for authenticated requests, one of:%s";
491 builtins[icmd].desc[0] = "md5";
492 fmt = "set key type to use for authenticated requests (%s)";
494 msg = emalloc(strlen(fmt) + strlen(list) - strlen("%s") +1);
495 sprintf(msg, fmt, list);
496 builtins[icmd].comment = msg;
503 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
509 * Process options other than -c and -p, which are specially
510 * handled by ntpq_custom_opt_handler().
513 debug = OPT_VALUE_SET_DEBUG_LEVEL;
516 ai_fam_templ = AF_INET;
517 else if (HAVE_OPT(IPV6))
518 ai_fam_templ = AF_INET6;
520 ai_fam_templ = ai_fam_default;
522 if (HAVE_OPT(INTERACTIVE))
525 if (HAVE_OPT(NUMERIC))
531 old_rv = HAVE_OPT(OLD_RV);
536 for (ihost = 0; ihost < (u_int)argc; ihost++) {
537 if ('-' == *argv[ihost]) {
539 // If I really cared I'd also check:
540 // 0 == argv[ihost][2]
542 // and there are other cases as well...
544 if ('4' == argv[ihost][1]) {
545 ai_fam_templ = AF_INET;
547 } else if ('6' == argv[ihost][1]) {
548 ai_fam_templ = AF_INET6;
551 // XXX Throw a usage error
554 ADDHOST(argv[ihost]);
558 if (numcmds == 0 && interactive == 0
559 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
563 set_ctrl_c_hook(on_ctrlc);
564 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
566 push_ctrl_c_handler(abortcmd);
567 #endif /* SYS_WINNT */
570 (void) openhost(chosts[0].name, chosts[0].fam);
573 for (ihost = 0; ihost < numhosts; ihost++) {
574 if (openhost(chosts[ihost].name, chosts[ihost].fam))
575 for (icmd = 0; icmd < numcmds; icmd++)
581 #endif /* SYS_WINNT */
584 #endif /* !BUILD_AS_LIB */
587 * openhost - open a socket to a host
595 const char svc[] = "ntp";
596 char temphost[LENHOSTNAME];
598 struct addrinfo hints, *ai;
601 register const char *cp;
602 char name[LENHOSTNAME];
605 * We need to get by the [] if they were entered
612 for (i = 0; *cp && *cp != ']'; cp++, i++)
623 * First try to resolve it as an ip address and if that fails,
624 * do a fullblown (dns) lookup. That way we only use the dns
625 * when it is needed and work around some implementations that
626 * will return an "IPv4-mapped IPv6 address" address if you
627 * give it an IPv4 address to lookup.
630 hints.ai_family = fam;
631 hints.ai_protocol = IPPROTO_UDP;
632 hints.ai_socktype = SOCK_DGRAM;
633 hints.ai_flags = Z_AI_NUMERICHOST;
636 a_info = getaddrinfo(hname, svc, &hints, &ai);
637 if (a_info == EAI_NONAME
639 || a_info == EAI_NODATA
642 hints.ai_flags = AI_CANONNAME;
644 hints.ai_flags |= AI_ADDRCONFIG;
646 a_info = getaddrinfo(hname, svc, &hints, &ai);
649 /* Some older implementations don't like AI_ADDRCONFIG. */
650 if (a_info == EAI_BADFLAGS) {
651 hints.ai_flags &= ~AI_ADDRCONFIG;
652 a_info = getaddrinfo(hname, svc, &hints, &ai);
656 fprintf(stderr, "%s\n", gai_strerror(a_info));
662 octets = min(sizeof(addr), ai->ai_addrlen);
663 memcpy(&addr, ai->ai_addr, octets);
665 if (ai->ai_canonname == NULL) {
666 strlcpy(temphost, stoa(&addr), sizeof(temphost));
667 currenthostisnum = TRUE;
669 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
670 currenthostisnum = FALSE;
674 printf("Opening host %s (%s)\n",
676 (ai->ai_family == AF_INET)
678 : (ai->ai_family == AF_INET6)
685 printf("Closing old host %s\n", currenthost);
689 strlcpy(currenthost, temphost, sizeof(currenthost));
691 /* port maps to the same location in both families */
692 s_port = NSRCPORT(&addr);
694 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
695 if (ai->ai_family == AF_INET)
696 *(struct sockaddr_in *)&hostaddr=
697 *((struct sockaddr_in *)ai->ai_addr);
699 *(struct sockaddr_in6 *)&hostaddr=
700 *((struct sockaddr_in6 *)ai->ai_addr);
701 #endif /* SYS_VXWORKS */
705 int optionValue = SO_SYNCHRONOUS_NONALERT;
708 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
709 (char *)&optionValue, sizeof(optionValue));
712 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
718 #endif /* SYS_WINNT */
720 sockfd = socket(ai->ai_family, ai->ai_socktype,
722 if (sockfd == INVALID_SOCKET) {
729 #ifdef NEED_RCVBUF_SLOP
731 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
732 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
733 &rbufsize, sizeof(int)) == -1)
741 (connect(sockfd, (struct sockaddr *)&hostaddr,
742 sizeof(hostaddr)) == -1)
744 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
745 ai->ai_addrlen) == -1)
746 #endif /* SYS_VXWORKS */
767 const char * rowstart;
775 rowlen = min(16, len);
776 for (idx = 0; idx < rowlen; idx++) {
778 printf("%02x ", uch);
780 for ( ; idx < 16 ; idx++)
783 for (idx = 0; idx < rowlen; idx++) {
785 printf("%c", (isprint(uch))
795 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
797 * sendpkt - send a packet to the remote host
806 printf("Sending %zu octets\n", xdatalen);
808 if (send(sockfd, xdata, xdatalen, 0) == -1) {
809 warning("write to %s failed", currenthost);
814 printf("Request packet:\n");
815 dump_hex_printable(xdata, xdatalen);
821 * getresponse - get a (series of) response packet(s) and return the data
833 struct ntp_control rpkt;
834 struct sock_timeval tvo;
835 u_short offsets[MAXFRAGS+1];
836 u_short counts[MAXFRAGS+1];
849 * This is pretty tricky. We may get between 1 and MAXFRAG packets
850 * back in response to the request. We peel the data out of
851 * each packet and collect it in one long block. When the last
852 * packet in the sequence is received we'll know how much data we
853 * should have had. Note we use one long time out, should reconsider.
858 *rdata = (char *)pktdata;
866 * Loop until we have an error or a complete response. Nearly all
867 * code paths to loop again use continue.
876 FD_SET(sockfd, &fds);
877 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
879 warning("select fails");
884 * Timed out. Return what we have
889 "%s: timed out, nothing received\n",
895 "%s: timed out with incomplete data\n",
899 "ERR_INCOMPLETE: Received fragments:\n");
900 for (f = 0; f < numfrags; f++)
902 "%2u: %5d %5d\t%3d octets\n",
903 (u_int)f, offsets[f],
908 "last fragment %sreceived\n",
913 return ERR_INCOMPLETE;
916 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
923 printf("Response packet:\n");
924 dump_hex_printable(&rpkt, n);
928 * Check for format errors. Bug proofing.
930 if (n < (int)CTL_HEADER_LEN) {
932 printf("Short (%d byte) packet received\n", n);
935 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
936 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
938 printf("Packet received with version %d\n",
939 PKT_VERSION(rpkt.li_vn_mode));
942 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
944 printf("Packet received with mode %d\n",
945 PKT_MODE(rpkt.li_vn_mode));
948 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
950 printf("Received request packet, wanted response\n");
955 * Check opcode and sequence number for a match.
956 * Could be old data getting to us.
958 if (ntohs(rpkt.sequence) != sequence) {
960 printf("Received sequnce number %d, wanted %d\n",
961 ntohs(rpkt.sequence), sequence);
964 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
967 "Received opcode %d, wanted %d (sequence number okay)\n",
968 CTL_OP(rpkt.r_m_e_op), opcode);
973 * Check the error code. If non-zero, return it.
975 if (CTL_ISERROR(rpkt.r_m_e_op)) {
976 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
977 if (CTL_ISMORE(rpkt.r_m_e_op))
978 TRACE(1, ("Error code %d received on not-final packet\n",
980 if (errcode == CERR_UNSPEC)
986 * Check the association ID to make sure it matches what
989 if (ntohs(rpkt.associd) != associd) {
990 TRACE(1, ("Association ID %d doesn't match expected %d\n",
991 ntohs(rpkt.associd), associd));
993 * Hack for silly fuzzballs which, at the time of writing,
994 * return an assID of sys.peer when queried for system variables.
1002 * Collect offset and count. Make sure they make sense.
1004 offset = ntohs(rpkt.offset);
1005 count = ntohs(rpkt.count);
1008 * validate received payload size is padded to next 32-bit
1009 * boundary and no smaller than claimed by rpkt.count
1012 TRACE(1, ("Response packet not padded, size = %d\n",
1017 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1019 if (n < shouldbesize) {
1020 printf("Response packet claims %u octets payload, above %ld received\n",
1021 count, (long)n - CTL_HEADER_LEN);
1022 return ERR_INCOMPLETE;
1025 if (debug >= 3 && shouldbesize > n) {
1031 * Usually we ignore authentication, but for debugging purposes
1034 /* round to 8 octet boundary */
1035 shouldbesize = (shouldbesize + 7) & ~7;
1037 maclen = n - shouldbesize;
1038 if (maclen >= (int)MIN_MAC_LEN) {
1040 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1041 n, shouldbesize, maclen);
1042 lpkt = (u_int32 *)&rpkt;
1043 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1044 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1045 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1046 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1047 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1048 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1049 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1050 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1051 printf("Authenticated with keyid %lu\n", (u_long)key);
1052 if (key != 0 && key != info_auth_keyid) {
1053 printf("We don't know that key\n");
1055 if (authdecrypt(key, (u_int32 *)&rpkt,
1056 n - maclen, maclen)) {
1057 printf("Auth okay!\n");
1059 printf("Auth failed!\n");
1065 TRACE(2, ("Got packet, size = %d\n", n));
1066 if (count > (n - CTL_HEADER_LEN)) {
1067 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1068 count, (long)n - CTL_HEADER_LEN));
1071 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1072 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1075 if (offset + count > sizeof(pktdata)) {
1076 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1080 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1081 TRACE(1, ("Received second last fragment packet\n"));
1086 * So far, so good. Record this fragment, making sure it doesn't
1089 TRACE(2, ("Packet okay\n"));
1091 if (numfrags > (MAXFRAGS - 1)) {
1092 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1098 * Find the position for the fragment relative to any
1099 * previously received.
1102 f < numfrags && offsets[f] < offset;
1107 if (f < numfrags && offset == offsets[f]) {
1108 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1109 count, offset, counts[f], offsets[f]));
1113 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1114 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1115 offset, counts[f-1], offsets[f-1]));
1119 if (f < numfrags && (offset + count) > offsets[f]) {
1120 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1121 count, offset, offsets[f]));
1125 for (ff = numfrags; ff > f; ff--) {
1126 offsets[ff] = offsets[ff-1];
1127 counts[ff] = counts[ff-1];
1129 offsets[f] = offset;
1134 * Got that stuffed in right. Figure out if this was the last.
1135 * Record status info out of the last packet.
1137 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1140 *rstatus = ntohs(rpkt.status);
1144 * Copy the data into the data buffer.
1146 memcpy((char *)pktdata + offset, &rpkt.u, count);
1149 * If we've seen the last fragment, look for holes in the sequence.
1150 * If there aren't any, we're done.
1152 if (seenlastfrag && offsets[0] == 0) {
1153 for (f = 1; f < numfrags; f++)
1154 if (offsets[f-1] + counts[f-1] !=
1157 if (f == numfrags) {
1158 *rsize = offsets[f-1] + counts[f-1];
1159 TRACE(1, ("%lu packets reassembled into response\n",
1164 } /* giant for (;;) collecting response packets */
1165 } /* getresponse() */
1169 * sendrequest - format and send a request packet
1180 struct ntp_control qpkt;
1187 * Check to make sure the data will fit in one packet
1189 if (qsize > CTL_MAX_DATA_LEN) {
1191 "***Internal error! qsize (%zu) too large\n",
1197 * Fill in the packet
1199 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1200 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1201 qpkt.sequence = htons(sequence);
1203 qpkt.associd = htons((u_short)associd);
1205 qpkt.count = htons((u_short)qsize);
1207 pktsize = CTL_HEADER_LEN;
1210 * If we have data, copy and pad it out to a 32-bit boundary.
1213 memcpy(&qpkt.u, qdata, (size_t)qsize);
1215 while (pktsize & (sizeof(u_int32) - 1)) {
1216 qpkt.u.data[qsize++] = 0;
1222 * If it isn't authenticated we can just send it. Otherwise
1223 * we're going to have to think about it a little.
1225 if (!auth && !always_auth) {
1226 return sendpkt(&qpkt, pktsize);
1230 * Pad out packet to a multiple of 8 octets to be sure
1231 * receiver can handle it.
1233 while (pktsize & 7) {
1234 qpkt.u.data[qsize++] = 0;
1239 * Get the keyid and the password if we don't have one.
1241 if (info_auth_keyid == 0) {
1242 key_id = getkeyid("Keyid: ");
1243 if (key_id == 0 || key_id > NTP_MAXKEY) {
1245 "Invalid key identifier\n");
1248 info_auth_keyid = key_id;
1250 if (!authistrusted(info_auth_keyid)) {
1251 pass = getpass_keytype(info_auth_keytype);
1252 if ('\0' == pass[0]) {
1253 fprintf(stderr, "Invalid password\n");
1256 authusekey(info_auth_keyid, info_auth_keytype,
1258 authtrust(info_auth_keyid, 1);
1262 * Do the encryption.
1264 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1266 fprintf(stderr, "Key not found\n");
1268 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1270 "%zu octet MAC, %zu expected with %zu octet digest\n",
1271 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1276 return sendpkt((char *)&qpkt, pktsize + maclen);
1281 * show_error_msg - display the error text for a mode 6 error response.
1290 fprintf(stderr, "server=%s ", currenthost);
1296 "***Server reports a bad format request packet\n");
1299 case CERR_PERMISSION:
1301 "***Server disallowed request (authentication?)\n");
1306 "***Server reports a bad opcode in request\n");
1311 "***Association ID %d unknown to server\n",
1315 case CERR_UNKNOWNVAR:
1317 "***A request variable unknown to the server\n");
1322 "***Server indicates a request variable was bad\n");
1327 "***Server returned an unspecified error\n");
1331 fprintf(stderr, "***Request timed out\n");
1334 case ERR_INCOMPLETE:
1336 "***Response from server was incomplete\n");
1341 "***Buffer size exceeded for returned data\n");
1346 "***Server returns unknown error code %d\n",
1352 * doquery - send a request and process the response, displaying
1353 * error messages for any error responses.
1367 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1368 rsize, rdata, FALSE);
1373 * doqueryex - send a request and process the response, optionally
1374 * displaying error messages for any error responses.
1393 * Check to make sure host is open
1396 fprintf(stderr, "***No host open, use `host' command\n");
1407 res = sendrequest(opcode, associd, auth, qsize, qdata);
1412 * Get the response. If we got a standard error, print a message
1414 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1417 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1418 if (res == ERR_INCOMPLETE) {
1420 * better bump the sequence so we don't
1421 * get confused about differing fragments.
1429 show_error_msg(res, associd);
1436 #ifndef BUILD_AS_LIB
1438 * getcmds - read commands from the standard input and execute them
1446 ntp_readline_init(interactive ? prompt : NULL);
1449 line = ntp_readline(&count);
1456 ntp_readline_uninit();
1458 #endif /* !BUILD_AS_LIB */
1461 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1463 * abortcmd - catch interrupts and abort the current command
1468 if (current_output == stdout)
1469 (void) fflush(stdout);
1471 (void) fflush(stderr);
1474 longjmp(interrupt_buf, 1);
1478 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1481 #ifndef BUILD_AS_LIB
1483 * docmd - decode the command line and execute a command
1490 char *tokens[1+MAXARGS+2];
1497 * Tokenize the command line. If nothing on it, return.
1499 tokenize(cmdline, tokens, &ntok);
1504 * Find the appropriate command description.
1506 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1508 (void) fprintf(stderr, "***Command `%s' unknown\n",
1511 } else if (i >= 2) {
1512 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1517 /* Warn about ignored extra args */
1518 for (i = MAXARGS + 1; i < ntok ; ++i) {
1519 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1523 * Save the keyword, then walk through the arguments, interpreting
1526 pcmd.keyword = tokens[0];
1528 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1529 if ((i+1) >= ntok) {
1530 if (!(xcmd->arg[i] & OPT)) {
1531 printusage(xcmd, stderr);
1536 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1538 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1544 if (i < ntok && *tokens[i] == '>') {
1547 if (*(tokens[i]+1) != '\0')
1548 fname = tokens[i]+1;
1549 else if ((i+1) < ntok)
1550 fname = tokens[i+1];
1552 (void) fprintf(stderr, "***No file for redirect\n");
1556 current_output = fopen(fname, "w");
1557 if (current_output == NULL) {
1558 (void) fprintf(stderr, "***Error opening %s: ", fname);
1562 i = 1; /* flag we need a close */
1564 current_output = stdout;
1565 i = 0; /* flag no close */
1568 if (interactive && setjmp(interrupt_buf)) {
1573 (xcmd->handler)(&pcmd, current_output);
1574 jump = 0; /* HMS: 961106: was after fclose() */
1575 if (i) (void) fclose(current_output);
1583 * tokenize - turn a command line into tokens
1585 * SK: Modified to allow a quoted string
1587 * HMS: If the first character of the first token is a ':' then (after
1588 * eating inter-token whitespace) the 2nd token is the rest of the line.
1598 register const char *cp;
1600 static char tspace[MAXLINE];
1604 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1607 /* Skip inter-token whitespace */
1608 while (ISSPACE(*cp))
1611 /* If we're at EOL we're done */
1615 /* If this is the 2nd token and the first token begins
1616 * with a ':', then just grab to EOL.
1619 if (*ntok == 1 && tokens[0][0] == ':') {
1621 if (sp - tspace >= MAXLINE)
1624 } while (!ISEOL(*cp));
1627 /* Check if this token begins with a double quote.
1628 * If yes, continue reading till the next double quote
1630 else if (*cp == '\"') {
1633 if (sp - tspace >= MAXLINE)
1636 } while ((*cp != '\"') && !ISEOL(*cp));
1637 /* HMS: a missing closing " should be an error */
1641 if (sp - tspace >= MAXLINE)
1644 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1645 /* HMS: Why check for a " in the previous line? */
1648 if (sp - tspace >= MAXLINE)
1657 "***Line `%s' is too big\n",
1664 * getarg - interpret an argument token
1675 switch (code & ~OPT) {
1681 if (!getnetnum(str, &argp->netnum, NULL, 0))
1686 if ('&' == str[0]) {
1687 if (!atouint(&str[1], &ul)) {
1689 "***Association index `%s' invalid/undecodable\n",
1693 if (0 == numassoc) {
1695 if (0 == numassoc) {
1697 "***No associations found, `%s' unknown\n",
1702 ul = min(ul, numassoc);
1703 argp->uval = assoc_cache[ul - 1].assid;
1706 if (!atouint(str, &argp->uval)) {
1707 fprintf(stderr, "***Illegal unsigned value %s\n",
1714 if (!atoint(str, &argp->ival)) {
1715 fprintf(stderr, "***Illegal integer value %s\n",
1722 if (!strcmp("-6", str)) {
1724 } else if (!strcmp("-4", str)) {
1727 fprintf(stderr, "***Version must be either 4 or 6\n");
1735 #endif /* !BUILD_AS_LIB */
1739 * findcmd - find a command in a command description table
1744 struct xcmd * clist1,
1745 struct xcmd * clist2,
1752 struct xcmd *nearmatch = NULL;
1759 else if (clist2 != 0)
1765 for (cl = clist; cl->keyword != 0; cl++) {
1766 /* do a first character check, for efficiency */
1767 if (*str != *(cl->keyword))
1769 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1771 * Could be extact match, could be approximate.
1772 * Is exact if the length of the keyword is the
1775 if (*((cl->keyword) + clen) == '\0') {
1785 * See if there is more to do. If so, go again. Sorry about the
1786 * goto, too much looking at BSD sources...
1788 if (clist == clist1 && clist2 != 0) {
1794 * If we got extactly 1 near match, use it, else return number
1806 * getnetnum - given a host name, return its net number
1807 * and (optional) full name
1817 struct addrinfo hints, *ai = NULL;
1820 hints.ai_flags = AI_CANONNAME;
1821 #ifdef AI_ADDRCONFIG
1822 hints.ai_flags |= AI_ADDRCONFIG;
1826 * decodenetnum only works with addresses, but handles syntax
1827 * that getaddrinfo doesn't: [2001::1]:1234
1829 if (decodenetnum(hname, num)) {
1830 if (fullhost != NULL)
1831 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1832 LENHOSTNAME, NULL, 0, 0);
1834 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1835 INSIST(sizeof(*num) >= ai->ai_addrlen);
1836 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1837 if (fullhost != NULL) {
1838 if (ai->ai_canonname != NULL)
1839 strlcpy(fullhost, ai->ai_canonname,
1842 getnameinfo(&num->sa, SOCKLEN(num),
1843 fullhost, LENHOSTNAME, NULL,
1849 fprintf(stderr, "***Can't find host %s\n", hname);
1856 * nntohost - convert network number to host name. This routine enforces
1857 * the showhostnames setting.
1864 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1869 * nntohost_col - convert network number to host name in fixed width.
1870 * This routine enforces the showhostnames setting.
1871 * When displaying hostnames longer than the width,
1872 * the first part of the hostname is displayed. When
1873 * displaying numeric addresses longer than the width,
1874 * Such as IPv6 addresses, the caller decides whether
1875 * the first or last of the numeric address is used.
1881 int preserve_lowaddrbits
1886 if (!showhostnames || SOCK_UNSPEC(addr)) {
1887 if (preserve_lowaddrbits)
1888 out = trunc_left(stoa(addr), width);
1890 out = trunc_right(stoa(addr), width);
1891 } else if (ISREFCLOCKADR(addr)) {
1892 out = refnumtoa(addr);
1894 out = trunc_right(socktohost(addr), width);
1901 * nntohostp() is the same as nntohost() plus a :port suffix
1911 if (!showhostnames || SOCK_UNSPEC(netnum))
1912 return sptoa(netnum);
1913 else if (ISREFCLOCKADR(netnum))
1914 return refnumtoa(netnum);
1916 hostn = socktohost(netnum);
1918 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1924 * rtdatetolfp - decode an RT-11 date into an l_fp
1934 struct calendar cal;
1940 * An RT-11 date looks like:
1942 * d[d]-Mth-y[y] hh:mm:ss
1944 * (No docs, but assume 4-digit years are also legal...)
1946 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
1949 if (!isdigit((int)*cp)) {
1952 * Catch special case
1960 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
1961 if (isdigit((int)*cp)) {
1962 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
1963 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
1969 for (i = 0; i < 3; i++)
1973 for (i = 0; i < 12; i++)
1974 if (STREQ(buf, months[i]))
1978 cal.month = (u_char)(i + 1);
1983 if (!isdigit((int)*cp))
1985 cal.year = (u_short)(*cp++ - '0');
1986 if (isdigit((int)*cp)) {
1987 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1988 cal.year = (u_short)(*cp++ - '0');
1990 if (isdigit((int)*cp)) {
1991 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1992 cal.year = (u_short)(cal.year + *cp++ - '0');
1994 if (isdigit((int)*cp)) {
1995 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1996 cal.year = (u_short)(cal.year + *cp++ - '0');
2000 * Catch special case. If cal.year == 0 this is a zero timestamp.
2002 if (cal.year == 0) {
2007 if (*cp++ != ' ' || !isdigit((int)*cp))
2009 cal.hour = (u_char)(*cp++ - '0');
2010 if (isdigit((int)*cp)) {
2011 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2012 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2015 if (*cp++ != ':' || !isdigit((int)*cp))
2017 cal.minute = (u_char)(*cp++ - '0');
2018 if (isdigit((int)*cp)) {
2019 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2020 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2023 if (*cp++ != ':' || !isdigit((int)*cp))
2025 cal.second = (u_char)(*cp++ - '0');
2026 if (isdigit((int)*cp)) {
2027 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2028 cal.second = (u_char)(cal.second + *cp++ - '0');
2032 * For RT-11, 1972 seems to be the pivot year
2039 lfp->l_ui = caltontp(&cal);
2046 * decodets - decode a timestamp into an l_fp format number, with
2047 * consideration of fuzzball formats.
2060 * If it starts with a 0x, decode as hex.
2062 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2063 return hextolfp(str+2, lfp);
2066 * If it starts with a '"', try it as an RT-11 date.
2071 while ('"' != *cp && '\0' != *cp &&
2072 b < COUNTOF(buf) - 1)
2075 return rtdatetolfp(buf, lfp);
2079 * Might still be hex. Check out the first character. Talk
2082 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2083 return hextolfp(str, lfp);
2086 * Try it as a decimal. If this fails, try as an unquoted
2087 * RT-11 date. This code should go away eventually.
2089 if (atolfp(str, lfp))
2092 return rtdatetolfp(str, lfp);
2097 * decodetime - decode a time value. It should be in milliseconds
2105 return mstolfp(str, lfp);
2110 * decodeint - decode an integer
2119 if (*(str+1) == 'x' || *(str+1) == 'X')
2120 return hextoint(str+2, (u_long *)val);
2121 return octtoint(str, (u_long *)val);
2123 return atoint(str, val);
2128 * decodeuint - decode an unsigned integer
2137 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2138 return (hextoint(str + 2, val));
2139 return (octtoint(str, val));
2141 return (atouint(str, val));
2146 * decodearr - decode an array of time values
2155 register char *cp, *bp;
2164 while (isspace((int)*cp))
2170 while (!isspace((int)*cp) && *cp != '\0')
2174 if (!decodetime(buf, lfp))
2184 * Finally, the built in command handlers
2188 * help - tell about commands, or details of a particular command
2196 struct xcmd *xcp = NULL; /* quiet warning */
2198 const char *list[100];
2204 if (pcmd->nargs == 0) {
2206 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2207 if (*(xcp->keyword) != '?' &&
2208 words < COUNTOF(list))
2209 list[words++] = xcp->keyword;
2211 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2212 if (words < COUNTOF(list))
2213 list[words++] = xcp->keyword;
2215 qsort((void *)list, words, sizeof(list[0]), helpsort);
2217 for (word = 0; word < words; word++) {
2218 length = strlen(list[word]);
2219 col = max(col, length);
2222 cols = SCREENWIDTH / ++col;
2223 rows = (words + cols - 1) / cols;
2225 fprintf(fp, "ntpq commands:\n");
2227 for (row = 0; row < rows; row++) {
2228 for (word = row; word < words; word += rows)
2229 fprintf(fp, "%-*.*s", (int)col,
2230 (int)col - 1, list[word]);
2234 cmd = pcmd->argval[0].string;
2235 words = findcmd(cmd, builtins, opcmds, &xcp);
2238 "Command `%s' is unknown\n", cmd);
2240 } else if (words >= 2) {
2242 "Command `%s' is ambiguous\n", cmd);
2245 fprintf(fp, "function: %s\n", xcp->comment);
2246 printusage(xcp, fp);
2252 * helpsort - do hostname qsort comparisons
2260 const char * const * name1 = t1;
2261 const char * const * name2 = t2;
2263 return strcmp(*name1, *name2);
2268 * printusage - print usage information for a command
2278 /* XXX: Do we need to warn about extra args here too? */
2280 (void) fprintf(fp, "usage: %s", xcp->keyword);
2281 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2282 if (xcp->arg[i] & OPT)
2283 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2285 (void) fprintf(fp, " %s", xcp->desc[i]);
2287 (void) fprintf(fp, "\n");
2292 * timeout - set time out time
2302 if (pcmd->nargs == 0) {
2303 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2304 (void) fprintf(fp, "primary timeout %d ms\n", val);
2306 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2307 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2314 * auth_delay - set delay for auth requests
2325 if (pcmd->nargs == 0) {
2326 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2327 (void) fprintf(fp, "delay %lu ms\n", val);
2329 if (pcmd->argval[0].ival < 0) {
2331 val = (u_long)(-pcmd->argval[0].ival);
2334 val = (u_long)pcmd->argval[0].ival;
2337 delay_time.l_ui = val / 1000;
2339 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2348 * host - set the host we are dealing with.
2358 if (pcmd->nargs == 0) {
2360 (void) fprintf(fp, "current host is %s\n",
2363 (void) fprintf(fp, "no current host\n");
2368 ai_fam_templ = ai_fam_default;
2369 if (pcmd->nargs == 2) {
2370 if (!strcmp("-4", pcmd->argval[i].string))
2371 ai_fam_templ = AF_INET;
2372 else if (!strcmp("-6", pcmd->argval[i].string))
2373 ai_fam_templ = AF_INET6;
2378 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2379 fprintf(fp, "current host set to %s\n", currenthost);
2383 fprintf(fp, "current host remains %s\n",
2386 fprintf(fp, "still no current host\n");
2392 * poll - do one (or more) polls of the host via NTP
2401 (void) fprintf(fp, "poll not implemented yet\n");
2406 * keyid - get a keyid to use for authenticating requests
2414 if (pcmd->nargs == 0) {
2415 if (info_auth_keyid == 0)
2416 (void) fprintf(fp, "no keyid defined\n");
2418 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2420 /* allow zero so that keyid can be cleared. */
2421 if(pcmd->argval[0].uval > NTP_MAXKEY)
2422 (void) fprintf(fp, "Invalid key identifier\n");
2423 info_auth_keyid = pcmd->argval[0].uval;
2428 * keytype - get type of key to use for authenticating requests
2436 const char * digest_name;
2441 fprintf(fp, "keytype is %s with %lu octet digests\n",
2442 keytype_name(info_auth_keytype),
2443 (u_long)info_auth_hashlen);
2447 digest_name = pcmd->argval[0].string;
2449 key_type = keytype_from_text(digest_name, &digest_len);
2452 fprintf(fp, "keytype is not valid. "
2454 "Type \"help keytype\" for the available digest types.\n");
2456 "Only \"md5\" is available.\n");
2461 info_auth_keytype = key_type;
2462 info_auth_hashlen = digest_len;
2467 * passwd - get an authentication key
2478 if (info_auth_keyid == 0) {
2479 info_auth_keyid = getkeyid("Keyid: ");
2480 if (info_auth_keyid == 0) {
2481 (void)fprintf(fp, "Keyid must be defined\n");
2485 if (pcmd->nargs >= 1)
2486 pass = pcmd->argval[0].string;
2488 pass = getpass_keytype(info_auth_keytype);
2489 if ('\0' == pass[0]) {
2490 fprintf(fp, "Password unchanged\n");
2494 authusekey(info_auth_keyid, info_auth_keytype,
2495 (const u_char *)pass);
2496 authtrust(info_auth_keyid, 1);
2501 * hostnames - set the showhostnames flag
2509 if (pcmd->nargs == 0) {
2511 (void) fprintf(fp, "hostnames being shown\n");
2513 (void) fprintf(fp, "hostnames not being shown\n");
2515 if (STREQ(pcmd->argval[0].string, "yes"))
2517 else if (STREQ(pcmd->argval[0].string, "no"))
2520 (void)fprintf(stderr, "What?\n");
2527 * setdebug - set/change debugging level
2535 if (pcmd->nargs == 0) {
2536 (void) fprintf(fp, "debug level is %d\n", debug);
2538 } else if (STREQ(pcmd->argval[0].string, "no")) {
2540 } else if (STREQ(pcmd->argval[0].string, "more")) {
2542 } else if (STREQ(pcmd->argval[0].string, "less")) {
2545 (void) fprintf(fp, "What?\n");
2548 (void) fprintf(fp, "debug level set to %d\n", debug);
2553 * quit - stop this nonsense
2563 closesocket(sockfd); /* cleanliness next to godliness */
2569 * version - print the current version number
2579 (void) fprintf(fp, "%s\n", Version);
2585 * raw - set raw mode output
2595 (void) fprintf(fp, "Output set to raw\n");
2600 * cooked - set cooked mode output
2610 (void) fprintf(fp, "Output set to cooked\n");
2616 * authenticate - always authenticate requests to this host
2624 if (pcmd->nargs == 0) {
2627 "authenticated requests being sent\n");
2630 "unauthenticated requests being sent\n");
2632 if (STREQ(pcmd->argval[0].string, "yes")) {
2634 } else if (STREQ(pcmd->argval[0].string, "no")) {
2637 (void)fprintf(stderr, "What?\n");
2643 * ntpversion - choose the NTP version to use
2651 if (pcmd->nargs == 0) {
2653 "NTP version being claimed is %d\n", pktversion);
2655 if (pcmd->argval[0].uval < NTP_OLDVERSION
2656 || pcmd->argval[0].uval > NTP_VERSION) {
2657 (void) fprintf(stderr, "versions %d to %d, please\n",
2658 NTP_OLDVERSION, NTP_VERSION);
2660 pktversion = (u_char) pcmd->argval[0].uval;
2666 static void __attribute__((__format__(__printf__, 1, 0)))
2667 vwarning(const char *fmt, va_list ap)
2670 (void) fprintf(stderr, "%s: ", progname);
2671 vfprintf(stderr, fmt, ap);
2672 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2676 * warning - print a warning message
2678 static void __attribute__((__format__(__printf__, 1, 2)))
2692 * error - print a message and exit
2694 static void __attribute__((__format__(__printf__, 1, 2)))
2707 * getkeyid - prompt the user for a keyid to use
2711 const char *keyprompt
2721 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2723 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2724 #endif /* SYS_WINNT */
2727 setbuf(fi, (char *)NULL);
2728 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2729 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2730 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2732 pbuf[i++] = (char)c;
2737 return (u_long) atoi(pbuf);
2742 * atoascii - printable-ize possibly ascii data using the character
2743 * transformations cat -v uses.
2753 const u_char * pchIn;
2754 const u_char * pchInLimit;
2758 pchIn = (const u_char *)in;
2759 pchInLimit = pchIn + in_octets;
2760 pchOut = (u_char *)out;
2762 if (NULL == pchIn) {
2770 if (0 == --out_octets) { \
2777 for ( ; pchIn < pchInLimit; pchIn++) {
2788 ONEOUT((u_char)(c + '@'));
2789 } else if (0x7f == c) {
2802 * makeascii - print possibly ascii data using the character
2803 * transformations that cat -v uses.
2812 const u_char *data_u_char;
2816 data_u_char = (const u_char *)data;
2818 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2829 } else if (0x7f == c) {
2839 * asciize - same thing as makeascii except add a newline
2848 makeascii(length, data, fp);
2854 * truncate string to fit clipping excess at end.
2855 * "too long" -> "too l"
2856 * Used for hostnames.
2869 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2871 memcpy(out, src, width);
2882 * truncate string to fit by preserving right side and using '_' to hint
2883 * "too long" -> "_long"
2884 * Used for local IPv6 addresses, where low bits differentiate.
2897 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2900 memcpy(&out[1], &src[sl + 1 - width], width);
2910 * Some circular buffer space
2915 char circ_buf[NUMCB][CBLEN];
2919 * nextvar - find the next variable in the buffer
2934 static char name[MAXVARLEN];
2935 static char value[MAXVALLEN];
2938 cpend = cp + *datalen;
2941 * Space past commas and white space
2943 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
2949 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
2950 * over any white space and terminate it.
2952 srclen = strcspn(cp, ",=\r\n");
2953 srclen = min(srclen, (size_t)(cpend - cp));
2955 while (len > 0 && isspace((unsigned char)cp[len - 1]))
2958 memcpy(name, cp, len);
2964 * Check if we hit the end of the buffer or a ','. If so we are done.
2966 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
2970 *datalen = size2int_sat(cpend - cp);
2976 * So far, so good. Copy out the value
2978 cp++; /* past '=' */
2979 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
2985 } while (np < cpend && '"' != *np);
2986 if (np < cpend && '"' == *np)
2989 while (np < cpend && ',' != *np && '\r' != *np)
2993 if (np > cpend || len >= sizeof(value) ||
2994 (np < cpend && ',' != *np && '\r' != *np))
2996 memcpy(value, cp, len);
2998 * Trim off any trailing whitespace
3000 while (len > 0 && isspace((unsigned char)value[len - 1]))
3005 * Return this. All done.
3007 if (np < cpend && ',' == *np)
3010 *datalen = size2int_sat(cpend - np);
3017 varfmt(const char * varname)
3021 for (n = 0; n < COUNTOF(cookedvars); n++)
3022 if (!strcmp(varname, cookedvars[n].varname))
3023 return cookedvars[n].fmt;
3030 * printvars - print variables returned in response packet
3043 rawprint(sttype, length, data, status, quiet, fp);
3045 cookedprint(sttype, length, data, status, quiet, fp);
3050 * rawprint - do a printout of the data in raw mode
3066 * Essentially print the data as is. We reformat unprintables, though.
3069 cpend = data + length;
3072 (void) fprintf(fp, "status=0x%04x,\n", status);
3074 while (cp < cpend) {
3077 * If this is a \r and the next character is a
3078 * \n, supress this, else pretty print it. Otherwise
3079 * just output the character.
3081 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3082 makeascii(1, cp, fp);
3083 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3086 makeascii(1, cp, fp);
3093 * Global data used by the cooked output routines
3095 int out_chars; /* number of characters output */
3096 int out_linecount; /* number of characters output on this line */
3100 * startoutput - get ready to do cooked output
3111 * output - output a variable=value combination
3122 /* strlen of "name=value" */
3123 len = size2int_sat(strlen(name) + 1 + strlen(value));
3125 if (out_chars != 0) {
3127 if ((out_linecount + len + 2) > MAXOUTLINE) {
3140 out_linecount += len;
3145 * endoutput - terminate a block of cooked output
3158 * outputarr - output an array of values
3176 * Hack to align delay and offset values
3178 for (i = (int)strlen(name); i < 11; i++)
3181 for (i = narr; i > 0; i--) {
3184 cp = lfptoms(lfp, 2);
3199 output(fp, name, buf);
3207 register char *cp, *s;
3210 register const char *sep;
3213 s = cp = circ_buf[nextcb];
3214 if (++nextcb >= NUMCB)
3216 cb = sizeof(circ_buf[0]);
3218 snprintf(cp, cb, "%02lx", val);
3222 strlcat(cp, " ok", cb);
3230 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3232 snprintf(cp, cb, "%s%s", sep,
3248 * cookedprint - output variables in cooked mode
3271 char bn[2 * MAXVARLEN];
3272 char bv[2 * MAXVALLEN];
3274 UNUSED_ARG(datatype);
3277 fprintf(fp, "status=%04x %s,\n", status,
3278 statustoa(datatype, status));
3281 while (nextvar(&length, &data, &name, &value)) {
3291 if (!decodets(value, &lfp))
3294 output(fp, name, prettydate(&lfp));
3297 case HA: /* fallthru */
3299 if (!decodenetnum(value, &hval)) {
3301 } else if (fmt == HA){
3302 output(fp, name, nntohost(&hval));
3304 output(fp, name, stoa(&hval));
3309 if (decodenetnum(value, &hval)) {
3310 if (ISREFCLOCKADR(&hval))
3314 output(fp, name, stoa(&hval));
3315 } else if (strlen(value) <= 4) {
3316 output(fp, name, value);
3323 if (!decodeuint(value, &uval) || uval > 3) {
3333 output(fp, name, b);
3338 if (!decodeuint(value, &uval)) {
3341 snprintf(b, sizeof(b), "%03lo", uval);
3342 output(fp, name, b);
3347 if (!decodearr(value, &narr, lfparr))
3350 outputarr(fp, name, narr, lfparr);
3354 if (!decodeuint(value, &uval))
3357 output(fp, name, tstflags(uval));
3361 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3367 if (output_raw != 0) {
3368 /* TALOS-CAN-0063: avoid buffer overrun */
3369 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3370 if (output_raw != '*') {
3371 atoascii(value, MAXVALLEN,
3372 bv, sizeof(bv) - 1);
3374 bv[len] = output_raw;
3377 atoascii(value, MAXVALLEN,
3388 * sortassoc - sort associations in the cache into ascending order
3394 qsort(assoc_cache, (size_t)numassoc,
3395 sizeof(assoc_cache[0]), &assoccmp);
3400 * assoccmp - compare two associations
3408 const struct association *ass1 = t1;
3409 const struct association *ass2 = t2;
3411 if (ass1->assid < ass2->assid)
3413 if (ass1->assid > ass2->assid)
3420 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3422 * The strategy is to add an assumed 4k page size at a time, leaving
3423 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3426 grow_assoc_cache(void)
3428 static size_t prior_sz;
3431 new_sz = prior_sz + 4 * 1024;
3432 if (0 == prior_sz) {
3433 new_sz -= 4 * sizeof(void *);
3435 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3437 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3442 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3444 * By default, autoopts loses the relative order of -c and -p options
3445 * on the command line. This routine replaces the default handler for
3446 * those routines and builds a list of commands to execute preserving
3450 ntpq_custom_opt_handler(
3455 switch (pOptDesc->optValue) {
3459 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3460 pOptDesc->optValue, pOptDesc->optValue);
3464 ADDCMD(pOptDesc->pzLastArg);
3473 * Obtain list of digest names
3477 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3483 #define K_PER_LINE 8
3484 #define K_NL_PFX_STR "\n "
3485 #define K_DELIM_STR ", "
3486 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3489 const char *name, *cp, **seen;
3490 struct hstate *hstate = arg;
3493 u_char digest[EVP_MAX_MD_SIZE];
3496 return; /* Ignore aliases */
3498 name = EVP_MD_name(m);
3500 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3502 for( cp = name; *cp; cp++ ) {
3506 len = (cp - name) + 1;
3508 /* There are duplicates. Discard if name has been seen. */
3510 for (seen = hstate->seen; *seen; seen++)
3511 if (!strcmp(*seen, name))
3513 n = (seen - hstate->seen) + 2;
3514 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3515 hstate->seen[n-2] = name;
3516 hstate->seen[n-1] = NULL;
3518 /* Discard MACs that NTP won't accept.
3519 * Keep this consistent with keytype_from_text() in ssl_init.c.
3522 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3523 EVP_DigestFinal(&ctx, digest, &digest_len);
3524 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3527 if (hstate->list != NULL)
3528 len += strlen(hstate->list);
3529 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3531 if (hstate->list == NULL) {
3532 hstate->list = (char *)emalloc(len);
3533 hstate->list[0] = '\0';
3535 hstate->list = (char *)erealloc(hstate->list, len);
3537 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3538 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3540 if (hstate->idx >= K_PER_LINE)
3548 static char *list_digest_names(void)
3553 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3554 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3556 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3559 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3563 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3564 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3567 list = (char *)emalloc(sizeof("md5"));
3568 strcpy(list, "md5");
3574 #define CTRLC_STACK_MAX 4
3575 static volatile size_t ctrlc_stack_len = 0;
3576 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3581 push_ctrl_c_handler(
3585 size_t size = ctrlc_stack_len;
3586 if (func && (size < CTRLC_STACK_MAX)) {
3587 ctrlc_stack[size] = func;
3588 ctrlc_stack_len = size + 1;
3599 size_t size = ctrlc_stack_len;
3602 if (func == NULL || func == ctrlc_stack[size]) {
3603 ctrlc_stack_len = size;
3613 size_t size = ctrlc_stack_len;
3615 if ((*ctrlc_stack[--size])())