2 * ntpq - query an NTP server using mode 6 commands
10 #include <sys/types.h>
22 #include <isc/result.h>
25 #include "ntp_assert.h"
26 #include "ntp_stdlib.h"
27 #include "ntp_unixtime.h"
28 #include "ntp_calendar.h"
29 #include "ntp_select.h"
30 #include "ntp_assert.h"
31 #include "lib_strbuf.h"
32 #include "ntp_lineedit.h"
33 #include "ntp_debug.h"
35 # include "openssl/evp.h"
36 # include "openssl/objects.h"
37 # include "openssl/err.h"
39 # include "openssl/opensslv.h"
40 # if !defined(HAVE_EVP_MD_DO_ALL_SORTED) && OPENSSL_VERSION_NUMBER > 0x10000000L
41 # define HAVE_EVP_MD_DO_ALL_SORTED 1
44 # include "libssl_compat.h"
45 # ifdef HAVE_OPENSSL_CMAC_H
46 # include <openssl/cmac.h>
47 # define CMAC "AES128CMAC"
50 #include <ssl_applink.c>
52 #include "ntp_libopts.h"
55 #ifdef SYS_VXWORKS /* vxWorks needs mode flag -casey*/
56 # define open(name, flags) open(name, flags, 0777)
57 # define SERVER_PORT_NUM 123
60 /* we use COMMAND as an autogen keyword */
66 * Because we potentially understand a lot of commands we will run
67 * interactive if connected to a terminal.
69 int interactive = 0; /* set to 1 when we should prompt */
70 const char *prompt = "ntpq> "; /* prompt to ask him about */
73 * use old readvars behavior? --old-rv processing in ntpq resets
74 * this value based on the presence or absence of --old-rv. It is
75 * initialized to 1 here to maintain backward compatibility with
76 * libntpq clients such as ntpsnmpd, which are free to reset it as
82 * How should we display the refid?
83 * REFID_HASH, REFID_IPV4
90 s_char sys_precision; /* local clock precision (log2 s) */
93 * Keyid used for authenticated requests. Obtained on the fly.
95 u_long info_auth_keyid = 0;
97 static int info_auth_keytype = NID_md5; /* MD5 */
98 static size_t info_auth_hashlen = 16; /* MD5 */
99 u_long current_time; /* needed by authkeys; not used */
102 * Flag which indicates we should always send authenticated requests
107 * Flag which indicates raw mode output.
112 * Packet version number we use
114 u_char pktversion = NTP_OLDVERSION + 1;
121 #define HA 1 /* host address */
122 #define NA 2 /* network address */
123 #define LP 3 /* leap (print in binary) */
124 #define RF 4 /* refid (sometimes string, sometimes not) */
125 #define AU 5 /* array of unsigned times */
126 #define FX 6 /* test flags */
127 #define TS 7 /* l_fp timestamp in hex */
128 #define OC 8 /* integer, print in octal */
129 #define AS 9 /* array of signed times */
130 #define SN 10 /* signed number: must display +/- sign */
131 #define EOV 255 /* end of table */
134 * For the most part ntpq simply displays what ntpd provides in the
135 * mostly plain-text mode 6 responses. A few variable names are by
136 * default "cooked" to provide more human-friendly output.
138 const var_format cookedvars[] = {
149 { "peeradr", HA }, /* compat with others */
152 { "filtoffset", AS },
154 { "filterror", AU }, /* compat with others */
164 static const char *tstflagnames[] = {
165 "pkt_dup", /* TEST1 */
166 "pkt_bogus", /* TEST2 */
167 "pkt_unsync", /* TEST3 */
168 "pkt_denied", /* TEST4 */
169 "pkt_auth", /* TEST5 */
170 "pkt_stratum", /* TEST6 */
171 "pkt_header", /* TEST7 */
172 "pkt_autokey", /* TEST8 */
173 "pkt_crypto", /* TEST9 */
174 "peer_stratum", /* TEST10 */
175 "peer_dist", /* TEST11 */
176 "peer_loop", /* TEST12 */
177 "peer_unreach" /* TEST13 */
181 int ntpqmain (int, char **);
183 * Built in command handler declarations
185 static int openhost (const char *, int);
186 static void dump_hex_printable(const void *, size_t);
187 static int sendpkt (void *, size_t);
188 static int getresponse (int, int, u_short *, size_t *, const char **, int);
189 static int sendrequest (int, associd_t, int, size_t, const char *);
190 static char * tstflags (u_long);
192 static void getcmds (void);
194 static int abortcmd (void);
195 #endif /* SYS_WINNT */
196 static void docmd (const char *);
197 static void tokenize (const char *, char **, int *);
198 static int getarg (const char *, int, arg_v *);
199 #endif /* BUILD_AS_LIB */
200 static int findcmd (const char *, struct xcmd *,
201 struct xcmd *, struct xcmd **);
202 static int rtdatetolfp (char *, l_fp *);
203 static int decodearr (char *, int *, l_fp *, int);
204 static void help (struct parse *, FILE *);
205 static int helpsort (const void *, const void *);
206 static void printusage (struct xcmd *, FILE *);
207 static void timeout (struct parse *, FILE *);
208 static void auth_delay (struct parse *, FILE *);
209 static void host (struct parse *, FILE *);
210 static void ntp_poll (struct parse *, FILE *);
211 static void keyid (struct parse *, FILE *);
212 static void keytype (struct parse *, FILE *);
213 static void passwd (struct parse *, FILE *);
214 static void hostnames (struct parse *, FILE *);
215 static void setdebug (struct parse *, FILE *);
216 static void quit (struct parse *, FILE *);
217 static void showdrefid (struct parse *, FILE *);
218 static void version (struct parse *, FILE *);
219 static void raw (struct parse *, FILE *);
220 static void cooked (struct parse *, FILE *);
221 static void authenticate (struct parse *, FILE *);
222 static void ntpversion (struct parse *, FILE *);
223 static void warning (const char *, ...) NTP_PRINTF(1, 2);
224 static void error (const char *, ...) NTP_PRINTF(1, 2);
225 static u_long getkeyid (const char *);
226 static void atoascii (const char *, size_t, char *, size_t);
227 static void cookedprint (int, size_t, const char *, int, int, FILE *);
228 static void rawprint (int, size_t, const char *, int, int, FILE *);
229 static void startoutput (void);
230 static void output (FILE *, const char *, const char *);
231 static void endoutput (FILE *);
232 static void outputarr (FILE *, char *, int, l_fp *, int);
233 static int assoccmp (const void *, const void *);
234 u_short varfmt (const char *);
235 void ntpq_custom_opt_handler(tOptions *, tOptDesc *);
238 static char *list_digest_names(void);
239 static char *insert_cmac (char *list);
240 static void on_ctrlc (void);
241 static int my_easprintf (char**, const char *, ...) NTP_PRINTF(2, 3);
242 # if defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED)
243 static void list_md_fn (const EVP_MD *m, const char *from,
244 const char *to, void *arg);
245 # endif /* defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED) */
246 #endif /* !defined(BUILD_AS_LIB) */
249 /* read a character from memory and expand to integer */
255 return (int)*(const unsigned char*)cp;
261 * Built-in commands we understand
263 struct xcmd builtins[] = {
264 { "?", help, { OPT|NTP_STR, NO, NO, NO },
265 { "command", "", "", "" },
266 "tell the use and syntax of commands" },
267 { "help", help, { OPT|NTP_STR, NO, NO, NO },
268 { "command", "", "", "" },
269 "tell the use and syntax of commands" },
270 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
271 { "msec", "", "", "" },
272 "set the primary receive time out" },
273 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
274 { "msec", "", "", "" },
275 "set the delay added to encryption time stamps" },
276 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
277 { "-4|-6", "hostname", "", "" },
278 "specify the host whose NTP server we talk to" },
279 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
280 { "n", "verbose", "", "" },
281 "poll an NTP server in client mode `n' times" },
282 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
284 "specify a password to use for authenticated requests"},
285 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
286 { "yes|no", "", "", "" },
287 "specify whether hostnames or net numbers are printed"},
288 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
289 { "no|more|less", "", "", "" },
290 "set/change debugging level" },
291 { "quit", quit, { NO, NO, NO, NO },
294 { "exit", quit, { NO, NO, NO, NO },
297 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
298 { "key#", "", "", "" },
299 "set keyid to use for authenticated requests" },
300 { "drefid", showdrefid, { OPT|NTP_STR, NO, NO, NO },
301 { "hash|ipv4", "", "", "" },
302 "display refid's as IPv4 or hash" },
303 { "version", version, { NO, NO, NO, NO },
305 "print version number" },
306 { "raw", raw, { NO, NO, NO, NO },
308 "do raw mode variable output" },
309 { "cooked", cooked, { NO, NO, NO, NO },
311 "do cooked mode variable output" },
312 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
313 { "yes|no", "", "", "" },
314 "always authenticate requests to this server" },
315 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
316 { "version number", "", "", "" },
317 "set the NTP version number to use for requests" },
318 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
319 { "key type %s", "", "", "" },
321 { 0, 0, { NO, NO, NO, NO },
322 { "", "", "", "" }, "" }
327 * Default values we use.
329 #define DEFHOST "localhost" /* default host name */
330 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
331 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
333 * Requests are automatically retried once, so total timeout with no
334 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
335 * extreme, a request eliciting 32 packets of responses each for some
336 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
337 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
338 * 93 seconds to fail each of two times, or 186 seconds.
339 * Some commands involve a series of requests, such as "peers" and
340 * "mrulist", so the cumulative timeouts are even longer for those.
342 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
343 #define LENHOSTNAME 256 /* host name is 256 characters long */
344 #define MAXCMDS 100 /* maximum commands on cmd line */
345 #define MAXHOSTS 200 /* maximum hosts on cmd line */
346 #define MAXLINE 512 /* maximum line length */
347 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
348 #define MAXVARLEN 256 /* maximum length of a variable name */
349 #define MAXVALLEN 2048 /* maximum length of a variable value */
350 #define MAXOUTLINE 72 /* maximum length of an output line */
351 #define SCREENWIDTH 76 /* nominal screen width in columns */
354 * Some variables used and manipulated locally
356 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
357 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
358 l_fp delay_time; /* delay time */
359 char currenthost[LENHOSTNAME]; /* current host name */
360 int currenthostisnum; /* is prior text from IP? */
361 struct sockaddr_in hostaddr; /* host address */
362 int showhostnames = 1; /* show host names by default */
363 int wideremote = 0; /* show wide remote names? */
365 int ai_fam_templ; /* address family */
366 int ai_fam_default; /* default address family */
367 SOCKET sockfd; /* fd socket is opened on */
368 int havehost = 0; /* set to 1 when host open */
370 struct servent *server_entry = NULL; /* server entry for ntp */
374 * Sequence number used for requests. It is incremented before
380 * Holds data returned from queries. Declare buffer long to be sure of
383 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
384 long pktdata[DATASIZE/sizeof(long)];
387 * assoc_cache[] is a dynamic array which allows references to
388 * associations using &1 ... &N for n associations, avoiding manual
389 * lookup of the current association IDs for a given ntpd. It also
390 * caches the status word for each association, retrieved incidentally.
392 struct association * assoc_cache;
393 u_int assoc_cache_slots;/* count of allocated array entries */
394 u_int numassoc; /* number of cached associations */
397 * For commands typed on the command line (with the -c option)
400 const char *ccmds[MAXCMDS];
401 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
404 * When multiple hosts are specified.
409 chost chosts[MAXHOSTS];
410 #define ADDHOST(cp) \
412 if (numhosts < MAXHOSTS) { \
413 chosts[numhosts].name = (cp); \
414 chosts[numhosts].fam = ai_fam_templ; \
420 * Macro definitions we use
422 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
423 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
424 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
427 * Jump buffer for longjumping back to the command level.
429 * Since we do this from a signal handler, we use 'sig{set,long}jmp()'
430 * if available. The signal is blocked by default during the excution of
431 * a signal handler, and it is unspecified if '{set,long}jmp()' save and
432 * restore the signal mask. They do on BSD, it depends on the GLIBC
433 * version on Linux, and the gods know what happens on other OSes...
435 * So we use the 'sig{set,long}jmp()' functions where available, because
436 * for them the semantics are well-defined. If we have to fall back to
437 * '{set,long}jmp()', the CTRL-C handling might be a bit erratic.
439 #if HAVE_DECL_SIGSETJMP && HAVE_DECL_SIGLONGJMP
440 # define JMP_BUF sigjmp_buf
441 # define SETJMP(x) sigsetjmp((x), 1)
442 # define LONGJMP(x, v) siglongjmp((x),(v))
444 # define JMP_BUF jmp_buf
445 # define SETJMP(x) setjmp((x))
446 # define LONGJMP(x, v) longjmp((x),(v))
448 static JMP_BUF interrupt_buf;
449 static volatile int jump = 0;
452 * Points at file being currently printed into
454 FILE *current_output = NULL;
457 * Command table imported from ntpdc_ops.c
459 extern struct xcmd opcmds[];
461 char const *progname;
463 #ifdef NO_MAIN_ALLOWED
465 CALL(ntpq,"ntpq",ntpqmain);
467 void clear_globals(void)
469 extern int ntp_optind;
470 showhostnames = 0; /* don'tshow host names by default */
472 server_entry = NULL; /* server entry for ntp */
473 havehost = 0; /* set to 1 when host open */
474 numassoc = 0; /* number of cached associations */
478 #endif /* !BUILD_AS_LIB */
479 #endif /* NO_MAIN_ALLOWED */
482 * main - parse arguments and handle options
484 #ifndef NO_MAIN_ALLOWED
491 return ntpqmain(argc, argv);
509 taskPrioritySet(taskIdSelf(), 100 );
513 delay_time.l_uf = DEFDELAY;
515 init_lib(); /* sets up ipv4_works, ipv6_works */
519 /* Check to see if we have IPv6. Otherwise default to IPv4 */
521 ai_fam_default = AF_INET;
523 /* Fixup keytype's help based on available digest names */
529 list = list_digest_names();
531 for (icmd = 0; icmd < sizeof(builtins)/sizeof(*builtins); icmd++) {
532 if (strcmp("keytype", builtins[icmd].keyword) == 0) {
538 /* This should only "trip" if "keytype" is removed from builtins */
539 INSIST(icmd < sizeof(builtins)/sizeof(*builtins));
542 builtins[icmd].desc[0] = "digest-name";
544 "set key type to use for authenticated requests, one of:%s",
547 builtins[icmd].desc[0] = "md5";
549 "set key type to use for authenticated requests (%s)",
552 builtins[icmd].comment = msg;
559 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
565 * Process options other than -c and -p, which are specially
566 * handled by ntpq_custom_opt_handler().
569 debug = OPT_VALUE_SET_DEBUG_LEVEL;
572 ai_fam_templ = AF_INET;
573 else if (HAVE_OPT(IPV6))
574 ai_fam_templ = AF_INET6;
576 ai_fam_templ = ai_fam_default;
578 if (HAVE_OPT(INTERACTIVE))
581 if (HAVE_OPT(NUMERIC))
587 old_rv = HAVE_OPT(OLD_RV);
589 drefid = OPT_VALUE_REFID;
594 for (ihost = 0; ihost < (u_int)argc; ihost++) {
595 if ('-' == *argv[ihost]) {
597 // If I really cared I'd also check:
598 // 0 == argv[ihost][2]
600 // and there are other cases as well...
602 if ('4' == argv[ihost][1]) {
603 ai_fam_templ = AF_INET;
605 } else if ('6' == argv[ihost][1]) {
606 ai_fam_templ = AF_INET6;
609 // XXX Throw a usage error
612 ADDHOST(argv[ihost]);
616 if (numcmds == 0 && interactive == 0
617 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
621 set_ctrl_c_hook(on_ctrlc);
622 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
624 push_ctrl_c_handler(abortcmd);
625 #endif /* SYS_WINNT */
628 (void) openhost(chosts[0].name, chosts[0].fam);
631 for (ihost = 0; ihost < numhosts; ihost++) {
632 if (openhost(chosts[ihost].name, chosts[ihost].fam)) {
633 if (ihost && current_output)
634 fputc('\n', current_output);
635 for (icmd = 0; icmd < numcmds; icmd++) {
636 if (icmd && current_output)
637 fputc('\n', current_output);
645 #endif /* SYS_WINNT */
648 #endif /* !BUILD_AS_LIB */
651 * openhost - open a socket to a host
659 const char svc[] = "ntp";
660 char temphost[LENHOSTNAME];
662 struct addrinfo hints, *ai;
666 char name[LENHOSTNAME];
669 * We need to get by the [] if they were entered
672 cp = strchr(hname + 1, ']');
673 if (!cp || (octets = (size_t)(cp - hname) - 1) >= sizeof(name)) {
675 warning("%s", "bad hostname/address");
678 memcpy(name, hname + 1, octets);
684 * First try to resolve it as an ip address and if that fails,
685 * do a fullblown (dns) lookup. That way we only use the dns
686 * when it is needed and work around some implementations that
687 * will return an "IPv4-mapped IPv6 address" address if you
688 * give it an IPv4 address to lookup.
691 hints.ai_family = fam;
692 hints.ai_protocol = IPPROTO_UDP;
693 hints.ai_socktype = SOCK_DGRAM;
694 hints.ai_flags = Z_AI_NUMERICHOST;
697 a_info = getaddrinfo(hname, svc, &hints, &ai);
698 if (a_info == EAI_NONAME
700 || a_info == EAI_NODATA
703 hints.ai_flags = AI_CANONNAME;
705 hints.ai_flags |= AI_ADDRCONFIG;
707 a_info = getaddrinfo(hname, svc, &hints, &ai);
710 /* Some older implementations don't like AI_ADDRCONFIG. */
711 if (a_info == EAI_BADFLAGS) {
712 hints.ai_flags &= ~AI_ADDRCONFIG;
713 a_info = getaddrinfo(hname, svc, &hints, &ai);
717 fprintf(stderr, "%s\n", gai_strerror(a_info));
723 octets = min(sizeof(addr), ai->ai_addrlen);
724 memcpy(&addr, ai->ai_addr, octets);
726 if (ai->ai_canonname == NULL) {
727 strlcpy(temphost, stoa(&addr), sizeof(temphost));
728 currenthostisnum = TRUE;
730 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
731 currenthostisnum = FALSE;
735 printf("Opening host %s (%s)\n",
737 (ai->ai_family == AF_INET)
739 : (ai->ai_family == AF_INET6)
746 printf("Closing old host %s\n", currenthost);
750 strlcpy(currenthost, temphost, sizeof(currenthost));
752 /* port maps to the same location in both families */
753 s_port = NSRCPORT(&addr);
755 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
756 if (ai->ai_family == AF_INET)
757 *(struct sockaddr_in *)&hostaddr=
758 *((struct sockaddr_in *)ai->ai_addr);
760 *(struct sockaddr_in6 *)&hostaddr=
761 *((struct sockaddr_in6 *)ai->ai_addr);
762 #endif /* SYS_VXWORKS */
766 int optionValue = SO_SYNCHRONOUS_NONALERT;
769 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
770 (void *)&optionValue, sizeof(optionValue));
773 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
779 #endif /* SYS_WINNT */
781 sockfd = socket(ai->ai_family, ai->ai_socktype,
783 if (sockfd == INVALID_SOCKET) {
790 #ifdef NEED_RCVBUF_SLOP
792 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
793 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
794 (void *)&rbufsize, sizeof(int)) == -1)
802 (connect(sockfd, (struct sockaddr *)&hostaddr,
803 sizeof(hostaddr)) == -1)
805 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
806 ai->ai_addrlen) == -1)
807 #endif /* SYS_VXWORKS */
827 /* every line shows at most 16 bytes, so we need a buffer of
828 * 4 * 16 (2 xdigits, 1 char, one sep for xdigits)
829 * + 2 * 1 (block separators)
834 static const char s_xdig[16] = "0123456789ABCDEF";
838 const u_char * cdata = data;
842 memset(lbuf, ' ', sizeof(lbuf));
844 pptr = lbuf + 3*16 + 2;
846 rowlen = (len > 16) ? 16 : (int)len;
852 *xptr++ = s_xdig[ch >> 4 ];
853 *xptr++ = s_xdig[ch & 0x0F];
854 if (++xptr == lbuf + 3*8)
857 *pptr++ = isprint(ch) ? (char)ch : '.';
867 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
869 * sendpkt - send a packet to the remote host
878 printf("Sending %zu octets\n", xdatalen);
880 if (send(sockfd, xdata, xdatalen, 0) == -1) {
881 warning("write to %s failed", currenthost);
886 printf("Request packet:\n");
887 dump_hex_printable(xdata, xdatalen);
893 * getresponse - get a (series of) response packet(s) and return the data
905 struct ntp_control rpkt;
906 struct sock_timeval tvo;
907 u_short offsets[MAXFRAGS+1];
908 u_short counts[MAXFRAGS+1];
919 /* absolute timeout checks. Not 'time_t' by intention! */
920 uint32_t tobase; /* base value for timeout */
921 uint32_t tospan; /* timeout span (max delay) */
922 uint32_t todiff; /* current delay */
924 memset(offsets, 0, sizeof(offsets));
925 memset(counts , 0, sizeof(counts ));
928 * This is pretty tricky. We may get between 1 and MAXFRAG packets
929 * back in response to the request. We peel the data out of
930 * each packet and collect it in one long block. When the last
931 * packet in the sequence is received we'll know how much data we
932 * should have had. Note we use one long time out, should reconsider.
937 *rdata = (char *)pktdata;
942 tobase = (uint32_t)time(NULL);
947 * Loop until we have an error or a complete response. Nearly all
948 * code paths to loop again use continue.
956 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
958 FD_SET(sockfd, &fds);
959 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
961 #if !defined(SYS_WINNT) && defined(EINTR)
962 /* Windows does not know about EINTR (until very
963 * recently) and the handling of console events
964 * is *very* different from POSIX/UNIX signal
967 * Under non-windows targets we map EINTR as
968 * 'last packet was received' and try to exit
969 * the receive sequence.
971 if (errno == EINTR) {
976 warning("select fails");
981 * Check if this is already too late. Trash the data and
982 * fake a timeout if this is so.
984 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
985 if ((n > 0) && (todiff > tospan)) {
986 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
987 n -= n; /* faked timeout return from 'select()',
988 * execute RMW cycle on 'n'
994 * Timed out. Return what we have
999 "%s: timed out, nothing received\n",
1005 "%s: timed out with incomplete data\n",
1009 "ERR_INCOMPLETE: Received fragments:\n");
1010 for (f = 0; f < numfrags; f++)
1012 "%2u: %5d %5d\t%3d octets\n",
1013 (u_int)f, offsets[f],
1018 "last fragment %sreceived\n",
1023 return ERR_INCOMPLETE;
1026 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
1033 printf("Response packet:\n");
1034 dump_hex_printable(&rpkt, n);
1038 * Check for format errors. Bug proofing.
1040 if (n < (int)CTL_HEADER_LEN) {
1042 printf("Short (%d byte) packet received\n", n);
1045 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
1046 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
1048 printf("Packet received with version %d\n",
1049 PKT_VERSION(rpkt.li_vn_mode));
1052 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
1054 printf("Packet received with mode %d\n",
1055 PKT_MODE(rpkt.li_vn_mode));
1058 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
1060 printf("Received request packet, wanted response\n");
1065 * Check opcode and sequence number for a match.
1066 * Could be old data getting to us.
1068 if (ntohs(rpkt.sequence) != sequence) {
1070 printf("Received sequnce number %d, wanted %d\n",
1071 ntohs(rpkt.sequence), sequence);
1074 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1077 "Received opcode %d, wanted %d (sequence number okay)\n",
1078 CTL_OP(rpkt.r_m_e_op), opcode);
1083 * Check the error code. If non-zero, return it.
1085 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1086 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1087 if (CTL_ISMORE(rpkt.r_m_e_op))
1088 TRACE(1, ("Error code %d received on not-final packet\n",
1090 if (errcode == CERR_UNSPEC)
1096 * Check the association ID to make sure it matches what
1099 if (ntohs(rpkt.associd) != associd) {
1100 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1101 ntohs(rpkt.associd), associd));
1103 * Hack for silly fuzzballs which, at the time of writing,
1104 * return an assID of sys.peer when queried for system variables.
1112 * Collect offset and count. Make sure they make sense.
1114 offset = ntohs(rpkt.offset);
1115 count = ntohs(rpkt.count);
1118 * validate received payload size is padded to next 32-bit
1119 * boundary and no smaller than claimed by rpkt.count
1122 TRACE(1, ("Response packet not padded, size = %d\n",
1127 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1129 if (n < shouldbesize) {
1130 printf("Response packet claims %u octets payload, above %ld received\n",
1131 count, (long)(n - CTL_HEADER_LEN));
1132 return ERR_INCOMPLETE;
1135 if (debug >= 3 && shouldbesize > n) {
1141 * Usually we ignore authentication, but for debugging purposes
1144 /* round to 8 octet boundary */
1145 shouldbesize = (shouldbesize + 7) & ~7;
1147 maclen = n - shouldbesize;
1148 if (maclen >= (int)MIN_MAC_LEN) {
1150 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1151 n, shouldbesize, maclen);
1152 lpkt = (u_int32 *)&rpkt;
1153 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1154 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1155 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1156 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1157 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1158 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1159 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1160 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1161 printf("Authenticated with keyid %lu\n", (u_long)key);
1162 if (key != 0 && key != info_auth_keyid) {
1163 printf("We don't know that key\n");
1165 if (authdecrypt(key, (u_int32 *)&rpkt,
1166 n - maclen, maclen)) {
1167 printf("Auth okay!\n");
1169 printf("Auth failed!\n");
1175 TRACE(2, ("Got packet, size = %d\n", n));
1176 if (count > (n - CTL_HEADER_LEN)) {
1177 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1178 count, (long)n - CTL_HEADER_LEN));
1181 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1182 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1185 if (offset + count > sizeof(pktdata)) {
1186 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1190 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1191 TRACE(1, ("Received second last fragment packet\n"));
1196 * So far, so good. Record this fragment, making sure it doesn't
1199 TRACE(2, ("Packet okay\n"));
1201 if (numfrags > (MAXFRAGS - 1)) {
1202 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1208 * Find the position for the fragment relative to any
1209 * previously received.
1212 f < numfrags && offsets[f] < offset;
1217 if (f < numfrags && offset == offsets[f]) {
1218 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1219 count, offset, counts[f], offsets[f]));
1223 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1224 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1225 offset, counts[f-1], offsets[f-1]));
1229 if (f < numfrags && (offset + count) > offsets[f]) {
1230 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1231 count, offset, offsets[f]));
1235 for (ff = numfrags; ff > f; ff--) {
1236 offsets[ff] = offsets[ff-1];
1237 counts[ff] = counts[ff-1];
1239 offsets[f] = offset;
1244 * Got that stuffed in right. Figure out if this was the last.
1245 * Record status info out of the last packet.
1247 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1250 *rstatus = ntohs(rpkt.status);
1254 * Copy the data into the data buffer, and bump the
1255 * timout base in case we need more.
1257 memcpy((char *)pktdata + offset, &rpkt.u, count);
1258 tobase = (uint32_t)time(NULL);
1261 * If we've seen the last fragment, look for holes in the sequence.
1262 * If there aren't any, we're done.
1264 #if !defined(SYS_WINNT) && defined(EINTR)
1268 if (seenlastfrag && offsets[0] == 0) {
1269 for (f = 1; f < numfrags; f++)
1270 if (offsets[f-1] + counts[f-1] !=
1273 if (f == numfrags) {
1274 *rsize = offsets[f-1] + counts[f-1];
1275 TRACE(1, ("%lu packets reassembled into response\n",
1280 } /* giant for (;;) collecting response packets */
1281 } /* getresponse() */
1285 * sendrequest - format and send a request packet
1296 struct ntp_control qpkt;
1303 * Check to make sure the data will fit in one packet
1305 if (qsize > CTL_MAX_DATA_LEN) {
1307 "***Internal error! qsize (%zu) too large\n",
1313 * Fill in the packet
1315 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1316 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1317 qpkt.sequence = htons(sequence);
1319 qpkt.associd = htons((u_short)associd);
1321 qpkt.count = htons((u_short)qsize);
1323 pktsize = CTL_HEADER_LEN;
1326 * If we have data, copy and pad it out to a 32-bit boundary.
1329 memcpy(&qpkt.u, qdata, (size_t)qsize);
1331 while (pktsize & (sizeof(u_int32) - 1)) {
1332 qpkt.u.data[qsize++] = 0;
1338 * If it isn't authenticated we can just send it. Otherwise
1339 * we're going to have to think about it a little.
1341 if (!auth && !always_auth) {
1342 return sendpkt(&qpkt, pktsize);
1346 * Pad out packet to a multiple of 8 octets to be sure
1347 * receiver can handle it.
1349 while (pktsize & 7) {
1350 qpkt.u.data[qsize++] = 0;
1355 * Get the keyid and the password if we don't have one.
1357 if (info_auth_keyid == 0) {
1358 key_id = getkeyid("Keyid: ");
1359 if (key_id == 0 || key_id > NTP_MAXKEY) {
1361 "Invalid key identifier\n");
1364 info_auth_keyid = key_id;
1366 if (!authistrusted(info_auth_keyid)) {
1367 pass = getpass_keytype(info_auth_keytype);
1368 if ('\0' == pass[0]) {
1369 fprintf(stderr, "Invalid password\n");
1372 authusekey(info_auth_keyid, info_auth_keytype,
1374 authtrust(info_auth_keyid, 1);
1378 * Do the encryption.
1380 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1382 fprintf(stderr, "Key not found\n");
1384 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1386 "%zu octet MAC, %zu expected with %zu octet digest\n",
1387 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1392 return sendpkt((char *)&qpkt, pktsize + maclen);
1397 * show_error_msg - display the error text for a mode 6 error response.
1406 fprintf(stderr, "server=%s ", currenthost);
1412 "***Server reports a bad format request packet\n");
1415 case CERR_PERMISSION:
1417 "***Server disallowed request (authentication?)\n");
1422 "***Server reports a bad opcode in request\n");
1427 "***Association ID %d unknown to server\n",
1431 case CERR_UNKNOWNVAR:
1433 "***A request variable unknown to the server\n");
1438 "***Server indicates a request variable was bad\n");
1443 "***Server returned an unspecified error\n");
1447 fprintf(stderr, "***Request timed out\n");
1450 case ERR_INCOMPLETE:
1452 "***Response from server was incomplete\n");
1457 "***Buffer size exceeded for returned data\n");
1462 "***Server returns unknown error code %d\n",
1468 * doquery - send a request and process the response, displaying
1469 * error messages for any error responses.
1483 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1484 rsize, rdata, FALSE);
1489 * doqueryex - send a request and process the response, optionally
1490 * displaying error messages for any error responses.
1509 * Check to make sure host is open
1512 fprintf(stderr, "***No host open, use `host' command\n");
1523 res = sendrequest(opcode, associd, auth, qsize, qdata);
1528 * Get the response. If we got a standard error, print a message
1530 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1533 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1534 if (res == ERR_INCOMPLETE) {
1536 * better bump the sequence so we don't
1537 * get confused about differing fragments.
1545 show_error_msg(res, associd);
1552 #ifndef BUILD_AS_LIB
1554 * getcmds - read commands from the standard input and execute them
1562 ntp_readline_init(interactive ? prompt : NULL);
1565 line = ntp_readline(&count);
1572 ntp_readline_uninit();
1574 #endif /* !BUILD_AS_LIB */
1577 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1579 * abortcmd - catch interrupts and abort the current command
1584 if (current_output == stdout)
1585 (void) fflush(stdout);
1587 (void) fflush(stderr);
1590 LONGJMP(interrupt_buf, 1);
1594 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1597 #ifndef BUILD_AS_LIB
1599 * docmd - decode the command line and execute a command
1606 char *tokens[1+MAXARGS+2];
1613 * Tokenize the command line. If nothing on it, return.
1615 tokenize(cmdline, tokens, &ntok);
1620 * Find the appropriate command description.
1622 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1624 (void) fprintf(stderr, "***Command `%s' unknown\n",
1627 } else if (i >= 2) {
1628 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1633 /* Warn about ignored extra args */
1634 for (i = MAXARGS + 1; i < ntok ; ++i) {
1635 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1639 * Save the keyword, then walk through the arguments, interpreting
1642 pcmd.keyword = tokens[0];
1644 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1645 if ((i+1) >= ntok) {
1646 if (!(xcmd->arg[i] & OPT)) {
1647 printusage(xcmd, stderr);
1652 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1654 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1660 if (i < ntok && *tokens[i] == '>') {
1663 if (*(tokens[i]+1) != '\0')
1664 fname = tokens[i]+1;
1665 else if ((i+1) < ntok)
1666 fname = tokens[i+1];
1668 (void) fprintf(stderr, "***No file for redirect\n");
1672 current_output = fopen(fname, "w");
1673 if (current_output == NULL) {
1674 (void) fprintf(stderr, "***Error opening %s: ", fname);
1679 current_output = stdout;
1683 if ( ! SETJMP(interrupt_buf)) {
1685 (xcmd->handler)(&pcmd, current_output);
1688 fflush(current_output);
1689 fputs("\n >>> command aborted <<<\n", stderr);
1695 (xcmd->handler)(&pcmd, current_output);
1697 if ((NULL != current_output) && (stdout != current_output)) {
1698 (void)fclose(current_output);
1699 current_output = NULL;
1705 * tokenize - turn a command line into tokens
1707 * SK: Modified to allow a quoted string
1709 * HMS: If the first character of the first token is a ':' then (after
1710 * eating inter-token whitespace) the 2nd token is the rest of the line.
1720 register const char *cp;
1722 static char tspace[MAXLINE];
1726 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1729 /* Skip inter-token whitespace */
1730 while (ISSPACE(*cp))
1733 /* If we're at EOL we're done */
1737 /* If this is the 2nd token and the first token begins
1738 * with a ':', then just grab to EOL.
1741 if (*ntok == 1 && tokens[0][0] == ':') {
1743 if (sp - tspace >= MAXLINE)
1746 } while (!ISEOL(*cp));
1749 /* Check if this token begins with a double quote.
1750 * If yes, continue reading till the next double quote
1752 else if (*cp == '\"') {
1755 if (sp - tspace >= MAXLINE)
1758 } while ((*cp != '\"') && !ISEOL(*cp));
1759 /* HMS: a missing closing " should be an error */
1763 if (sp - tspace >= MAXLINE)
1766 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1767 /* HMS: Why check for a " in the previous line? */
1770 if (sp - tspace >= MAXLINE)
1779 "***Line `%s' is too big\n",
1786 * getarg - interpret an argument token
1797 switch (code & ~OPT) {
1803 if (!getnetnum(str, &argp->netnum, NULL, 0))
1808 if ('&' == str[0]) {
1809 if (!atouint(&str[1], &ul)) {
1811 "***Association index `%s' invalid/undecodable\n",
1815 if (0 == numassoc) {
1817 if (0 == numassoc) {
1819 "***No associations found, `%s' unknown\n",
1824 ul = min(ul, numassoc);
1825 argp->uval = assoc_cache[ul - 1].assid;
1828 if (!atouint(str, &argp->uval)) {
1829 fprintf(stderr, "***Illegal unsigned value %s\n",
1836 if (!atoint(str, &argp->ival)) {
1837 fprintf(stderr, "***Illegal integer value %s\n",
1844 if (!strcmp("-6", str)) {
1846 } else if (!strcmp("-4", str)) {
1849 fprintf(stderr, "***Version must be either 4 or 6\n");
1857 #endif /* !BUILD_AS_LIB */
1861 * findcmd - find a command in a command description table
1866 struct xcmd * clist1,
1867 struct xcmd * clist2,
1874 struct xcmd *nearmatch = NULL;
1881 else if (clist2 != 0)
1887 for (cl = clist; cl->keyword != 0; cl++) {
1888 /* do a first character check, for efficiency */
1889 if (*str != *(cl->keyword))
1891 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1893 * Could be extact match, could be approximate.
1894 * Is exact if the length of the keyword is the
1897 if (*((cl->keyword) + clen) == '\0') {
1907 * See if there is more to do. If so, go again. Sorry about the
1908 * goto, too much looking at BSD sources...
1910 if (clist == clist1 && clist2 != 0) {
1916 * If we got extactly 1 near match, use it, else return number
1928 * getnetnum - given a host name, return its net number
1929 * and (optional) full name
1939 struct addrinfo hints, *ai = NULL;
1942 hints.ai_flags = AI_CANONNAME;
1943 #ifdef AI_ADDRCONFIG
1944 hints.ai_flags |= AI_ADDRCONFIG;
1948 * decodenetnum only works with addresses, but handles syntax
1949 * that getaddrinfo doesn't: [2001::1]:1234
1951 if (decodenetnum(hname, num)) {
1952 if (fullhost != NULL)
1953 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1954 LENHOSTNAME, NULL, 0, 0);
1956 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1957 INSIST(sizeof(*num) >= ai->ai_addrlen);
1958 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1959 if (fullhost != NULL) {
1960 if (ai->ai_canonname != NULL)
1961 strlcpy(fullhost, ai->ai_canonname,
1964 getnameinfo(&num->sa, SOCKLEN(num),
1965 fullhost, LENHOSTNAME, NULL,
1971 fprintf(stderr, "***Can't find host %s\n", hname);
1978 * nntohost - convert network number to host name. This routine enforces
1979 * the showhostnames setting.
1986 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1991 * nntohost_col - convert network number to host name in fixed width.
1992 * This routine enforces the showhostnames setting.
1993 * When displaying hostnames longer than the width,
1994 * the first part of the hostname is displayed. When
1995 * displaying numeric addresses longer than the width,
1996 * Such as IPv6 addresses, the caller decides whether
1997 * the first or last of the numeric address is used.
2003 int preserve_lowaddrbits
2008 if (!showhostnames || SOCK_UNSPEC(addr)) {
2009 if (preserve_lowaddrbits)
2010 out = trunc_left(stoa(addr), width);
2012 out = trunc_right(stoa(addr), width);
2013 } else if (ISREFCLOCKADR(addr)) {
2014 out = refnumtoa(addr);
2016 out = trunc_right(socktohost(addr), width);
2023 * nntohostp() is the same as nntohost() plus a :port suffix
2033 if (!showhostnames || SOCK_UNSPEC(netnum))
2034 return sptoa(netnum);
2035 else if (ISREFCLOCKADR(netnum))
2036 return refnumtoa(netnum);
2038 hostn = socktohost(netnum);
2040 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
2046 * rtdatetolfp - decode an RT-11 date into an l_fp
2056 struct calendar cal;
2062 * An RT-11 date looks like:
2064 * d[d]-Mth-y[y] hh:mm:ss
2066 * (No docs, but assume 4-digit years are also legal...)
2068 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
2071 if (!isdigit(pgetc(cp))) {
2074 * Catch special case
2082 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2083 if (isdigit(pgetc(cp))) {
2084 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2085 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2091 for (i = 0; i < 3; i++)
2095 for (i = 0; i < 12; i++)
2096 if (STREQ(buf, months[i]))
2100 cal.month = (u_char)(i + 1);
2105 if (!isdigit(pgetc(cp)))
2107 cal.year = (u_short)(*cp++ - '0');
2108 if (isdigit(pgetc(cp))) {
2109 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2110 cal.year = (u_short)(*cp++ - '0');
2112 if (isdigit(pgetc(cp))) {
2113 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2114 cal.year = (u_short)(cal.year + *cp++ - '0');
2116 if (isdigit(pgetc(cp))) {
2117 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2118 cal.year = (u_short)(cal.year + *cp++ - '0');
2122 * Catch special case. If cal.year == 0 this is a zero timestamp.
2124 if (cal.year == 0) {
2129 if (*cp++ != ' ' || !isdigit(pgetc(cp)))
2131 cal.hour = (u_char)(*cp++ - '0');
2132 if (isdigit(pgetc(cp))) {
2133 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2134 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2137 if (*cp++ != ':' || !isdigit(pgetc(cp)))
2139 cal.minute = (u_char)(*cp++ - '0');
2140 if (isdigit(pgetc(cp))) {
2141 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2142 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2145 if (*cp++ != ':' || !isdigit(pgetc(cp)))
2147 cal.second = (u_char)(*cp++ - '0');
2148 if (isdigit(pgetc(cp))) {
2149 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2150 cal.second = (u_char)(cal.second + *cp++ - '0');
2154 * For RT-11, 1972 seems to be the pivot year
2161 lfp->l_ui = caltontp(&cal);
2168 * decodets - decode a timestamp into an l_fp format number, with
2169 * consideration of fuzzball formats.
2182 * If it starts with a 0x, decode as hex.
2184 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2185 return hextolfp(str+2, lfp);
2188 * If it starts with a '"', try it as an RT-11 date.
2193 while ('"' != *cp && '\0' != *cp &&
2194 b < COUNTOF(buf) - 1)
2197 return rtdatetolfp(buf, lfp);
2201 * Might still be hex. Check out the first character. Talk
2204 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2205 return hextolfp(str, lfp);
2208 * Try it as a decimal. If this fails, try as an unquoted
2209 * RT-11 date. This code should go away eventually.
2211 if (atolfp(str, lfp))
2214 return rtdatetolfp(str, lfp);
2219 * decodetime - decode a time value. It should be in milliseconds
2227 return mstolfp(str, lfp);
2232 * decodeint - decode an integer
2241 if (*(str+1) == 'x' || *(str+1) == 'X')
2242 return hextoint(str+2, (u_long *)val);
2243 return octtoint(str, (u_long *)val);
2245 return atoint(str, val);
2250 * decodeuint - decode an unsigned integer
2259 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2260 return (hextoint(str + 2, val));
2261 return (octtoint(str, val));
2263 return (atouint(str, val));
2268 * decodearr - decode an array of time values
2283 while (*narr < amax && *cp) {
2284 if (isspace(pgetc(cp))) {
2287 while (*cp && isspace(pgetc(cp)));
2291 if (bp != (buf + sizeof(buf) - 1))
2294 } while (*cp && !isspace(pgetc(cp)));
2297 if (!decodetime(buf, lfpa))
2308 * Finally, the built in command handlers
2312 * help - tell about commands, or details of a particular command
2320 struct xcmd *xcp = NULL; /* quiet warning */
2322 const char *list[100];
2328 if (pcmd->nargs == 0) {
2330 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2331 if (*(xcp->keyword) != '?' &&
2332 words < COUNTOF(list))
2333 list[words++] = xcp->keyword;
2335 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2336 if (words < COUNTOF(list))
2337 list[words++] = xcp->keyword;
2339 qsort((void *)list, words, sizeof(list[0]), helpsort);
2341 for (word = 0; word < words; word++) {
2342 length = strlen(list[word]);
2343 col = max(col, length);
2346 cols = SCREENWIDTH / ++col;
2347 rows = (words + cols - 1) / cols;
2349 fprintf(fp, "ntpq commands:\n");
2351 for (row = 0; row < rows; row++) {
2352 for (word = row; word < words; word += rows)
2353 fprintf(fp, "%-*.*s", (int)col,
2354 (int)col - 1, list[word]);
2358 cmd = pcmd->argval[0].string;
2359 words = findcmd(cmd, builtins, opcmds, &xcp);
2362 "Command `%s' is unknown\n", cmd);
2364 } else if (words >= 2) {
2366 "Command `%s' is ambiguous\n", cmd);
2369 fprintf(fp, "function: %s\n", xcp->comment);
2370 printusage(xcp, fp);
2376 * helpsort - do hostname qsort comparisons
2384 const char * const * name1 = t1;
2385 const char * const * name2 = t2;
2387 return strcmp(*name1, *name2);
2392 * printusage - print usage information for a command
2402 /* XXX: Do we need to warn about extra args here too? */
2404 (void) fprintf(fp, "usage: %s", xcp->keyword);
2405 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2406 if (xcp->arg[i] & OPT)
2407 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2409 (void) fprintf(fp, " %s", xcp->desc[i]);
2411 (void) fprintf(fp, "\n");
2416 * timeout - set time out time
2426 if (pcmd->nargs == 0) {
2427 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2428 (void) fprintf(fp, "primary timeout %d ms\n", val);
2430 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2431 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2438 * auth_delay - set delay for auth requests
2449 if (pcmd->nargs == 0) {
2450 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2451 (void) fprintf(fp, "delay %lu ms\n", val);
2453 if (pcmd->argval[0].ival < 0) {
2455 val = (u_long)(-pcmd->argval[0].ival);
2458 val = (u_long)pcmd->argval[0].ival;
2461 delay_time.l_ui = val / 1000;
2463 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2472 * host - set the host we are dealing with.
2482 if (pcmd->nargs == 0) {
2484 (void) fprintf(fp, "current host is %s\n",
2487 (void) fprintf(fp, "no current host\n");
2492 ai_fam_templ = ai_fam_default;
2493 if (pcmd->nargs == 2) {
2494 if (!strcmp("-4", pcmd->argval[i].string))
2495 ai_fam_templ = AF_INET;
2496 else if (!strcmp("-6", pcmd->argval[i].string))
2497 ai_fam_templ = AF_INET6;
2502 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2503 fprintf(fp, "current host set to %s\n", currenthost);
2507 fprintf(fp, "current host remains %s\n",
2510 fprintf(fp, "still no current host\n");
2516 * poll - do one (or more) polls of the host via NTP
2525 (void) fprintf(fp, "poll not implemented yet\n");
2530 * showdrefid2str - return a string explanation of the value of drefid
2533 showdrefid2str(void)
2547 * drefid - display/change "display hash"
2555 if (pcmd->nargs == 0) {
2556 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2558 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2559 drefid = REFID_HASH;
2560 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2561 drefid = REFID_IPV4;
2563 (void) fprintf(fp, "What?\n");
2566 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2571 * keyid - get a keyid to use for authenticating requests
2579 if (pcmd->nargs == 0) {
2580 if (info_auth_keyid == 0)
2581 (void) fprintf(fp, "no keyid defined\n");
2583 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2585 /* allow zero so that keyid can be cleared. */
2586 if(pcmd->argval[0].uval > NTP_MAXKEY)
2587 (void) fprintf(fp, "Invalid key identifier\n");
2588 info_auth_keyid = pcmd->argval[0].uval;
2593 * keytype - get type of key to use for authenticating requests
2601 const char * digest_name;
2606 fprintf(fp, "keytype is %s with %lu octet digests\n",
2607 keytype_name(info_auth_keytype),
2608 (u_long)info_auth_hashlen);
2612 digest_name = pcmd->argval[0].string;
2614 key_type = keytype_from_text(digest_name, &digest_len);
2617 fprintf(fp, "keytype is not valid. "
2619 "Type \"help keytype\" for the available digest types.\n");
2621 "Only \"md5\" is available.\n");
2626 info_auth_keytype = key_type;
2627 info_auth_hashlen = digest_len;
2632 * passwd - get an authentication key
2643 if (info_auth_keyid == 0) {
2644 info_auth_keyid = getkeyid("Keyid: ");
2645 if (info_auth_keyid == 0) {
2646 (void)fprintf(fp, "Keyid must be defined\n");
2650 if (pcmd->nargs >= 1)
2651 pass = pcmd->argval[0].string;
2653 pass = getpass_keytype(info_auth_keytype);
2654 if ('\0' == pass[0]) {
2655 fprintf(fp, "Password unchanged\n");
2659 authusekey(info_auth_keyid, info_auth_keytype,
2660 (const u_char *)pass);
2661 authtrust(info_auth_keyid, 1);
2666 * hostnames - set the showhostnames flag
2674 if (pcmd->nargs == 0) {
2676 (void) fprintf(fp, "hostnames being shown\n");
2678 (void) fprintf(fp, "hostnames not being shown\n");
2680 if (STREQ(pcmd->argval[0].string, "yes"))
2682 else if (STREQ(pcmd->argval[0].string, "no"))
2685 (void)fprintf(stderr, "What?\n");
2692 * setdebug - set/change debugging level
2700 if (pcmd->nargs == 0) {
2701 (void) fprintf(fp, "debug level is %d\n", debug);
2703 } else if (STREQ(pcmd->argval[0].string, "no")) {
2705 } else if (STREQ(pcmd->argval[0].string, "more")) {
2707 } else if (STREQ(pcmd->argval[0].string, "less")) {
2710 (void) fprintf(fp, "What?\n");
2713 (void) fprintf(fp, "debug level set to %d\n", debug);
2718 * quit - stop this nonsense
2728 closesocket(sockfd); /* cleanliness next to godliness */
2734 * version - print the current version number
2744 (void) fprintf(fp, "%s\n", Version);
2750 * raw - set raw mode output
2760 (void) fprintf(fp, "Output set to raw\n");
2765 * cooked - set cooked mode output
2775 (void) fprintf(fp, "Output set to cooked\n");
2781 * authenticate - always authenticate requests to this host
2789 if (pcmd->nargs == 0) {
2792 "authenticated requests being sent\n");
2795 "unauthenticated requests being sent\n");
2797 if (STREQ(pcmd->argval[0].string, "yes")) {
2799 } else if (STREQ(pcmd->argval[0].string, "no")) {
2802 (void)fprintf(stderr, "What?\n");
2808 * ntpversion - choose the NTP version to use
2816 if (pcmd->nargs == 0) {
2818 "NTP version being claimed is %d\n", pktversion);
2820 if (pcmd->argval[0].uval < NTP_OLDVERSION
2821 || pcmd->argval[0].uval > NTP_VERSION) {
2822 (void) fprintf(stderr, "versions %d to %d, please\n",
2823 NTP_OLDVERSION, NTP_VERSION);
2825 pktversion = (u_char) pcmd->argval[0].uval;
2831 static void __attribute__((__format__(__printf__, 1, 0)))
2832 vwarning(const char *fmt, va_list ap)
2835 (void) fprintf(stderr, "%s: ", progname);
2836 vfprintf(stderr, fmt, ap);
2837 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2841 * warning - print a warning message
2843 static void __attribute__((__format__(__printf__, 1, 2)))
2857 * error - print a message and exit
2859 static void __attribute__((__format__(__printf__, 1, 2)))
2872 * getkeyid - prompt the user for a keyid to use
2876 const char *keyprompt
2886 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2888 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2889 #endif /* SYS_WINNT */
2892 setbuf(fi, (char *)NULL);
2893 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2894 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2895 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2897 pbuf[i++] = (char)c;
2902 return (u_long) atoi(pbuf);
2907 * atoascii - printable-ize possibly ascii data using the character
2908 * transformations cat -v uses.
2918 const u_char * pchIn;
2919 const u_char * pchInLimit;
2923 pchIn = (const u_char *)in;
2924 pchInLimit = pchIn + in_octets;
2925 pchOut = (u_char *)out;
2927 if (NULL == pchIn) {
2935 if (0 == --out_octets) { \
2942 for ( ; pchIn < pchInLimit; pchIn++) {
2953 ONEOUT((u_char)(c + '@'));
2954 } else if (0x7f == c) {
2967 * makeascii - print possibly ascii data using the character
2968 * transformations that cat -v uses.
2977 const u_char *data_u_char;
2981 data_u_char = (const u_char *)data;
2983 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2994 } else if (0x7f == c) {
3004 * asciize - same thing as makeascii except add a newline
3013 makeascii(length, data, fp);
3019 * truncate string to fit clipping excess at end.
3020 * "too long" -> "too l"
3021 * Used for hostnames.
3034 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
3036 memcpy(out, src, width);
3047 * truncate string to fit by preserving right side and using '_' to hint
3048 * "too long" -> "_long"
3049 * Used for local IPv6 addresses, where low bits differentiate.
3062 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
3065 memcpy(&out[1], &src[sl + 1 - width], width);
3075 * Some circular buffer space
3080 char circ_buf[NUMCB][CBLEN];
3083 /* --------------------------------------------------------------------
3084 * Parsing a response value list
3086 * This sounds simple (and it actually is not really hard) but it has
3089 * Rule1: CR/LF is never embedded in an item
3090 * Rule2: An item is a name, optionally followed by a value
3091 * Rule3: The value is separated from the name by a '='
3092 * Rule4: Items are separated by a ','
3093 * Rule5: values can be quoted by '"', in which case they can contain
3094 * arbitrary characters but *not* '"', CR and LF
3096 * There are a few implementations out there that require a somewhat
3097 * relaxed attitude when parsing a value list, especially since we want
3098 * to copy names and values into local buffers. If these would overflow,
3099 * the item should be skipped without terminating the parsing sequence.
3101 * Also, for empty values, there might be a '=' after the name or not;
3102 * we treat that equivalent.
3104 * Parsing an item definitely breaks on a CR/LF. If an item is not
3105 * followed by a comma (','), parsing stops. In the middle of a quoted
3106 * character sequence CR/LF terminates the parsing finally without
3107 * returning a value.
3109 * White space and other noise is ignored when parsing the data buffer;
3110 * only CR, LF, ',', '=' and '"' are characters with a special meaning.
3111 * White space is stripped from the names and values *after* working
3112 * through the buffer, before making the local copies. If whitespace
3113 * stripping results in an empty name, parsing resumes.
3117 * nextvar parsing helpers
3120 /* predicate: allowed chars inside a quoted string */
3121 static int/*BOOL*/ cp_qschar(int ch)
3123 return ch && (ch != '"' && ch != '\r' && ch != '\n');
3126 /* predicate: allowed chars inside an unquoted string */
3127 static int/*BOOL*/ cp_uqchar(int ch)
3129 return ch && (ch != ',' && ch != '"' && ch != '\r' && ch != '\n');
3132 /* predicate: allowed chars inside a value name */
3133 static int/*BOOL*/ cp_namechar(int ch)
3135 return ch && (ch != ',' && ch != '=' && ch != '\r' && ch != '\n');
3138 /* predicate: characters *between* list items. We're relaxed here. */
3139 static int/*BOOL*/ cp_ivspace(int ch)
3141 return (ch == ',' || (ch > 0 && ch <= ' '));
3144 /* get current character (or NUL when on end) */
3147 const char ** datap,
3151 return (*datap != endp)
3152 ? *(const unsigned char*)*datap
3156 /* get next character (or NUL when on end) */
3159 const char ** datap,
3163 return (*datap != endp && ++(*datap) != endp)
3164 ? *(const unsigned char*)*datap
3170 const char ** datap,
3174 static const char empty[] = "";
3176 if (*datap && len) {
3177 const char * cpl = *datap;
3178 const char * cpr = cpl + len;
3180 while (cpl != cpr && *(const unsigned char*)cpl <= ' ')
3182 while (cpl != cpr && *(const unsigned char*)(cpr - 1) <= ' ')
3185 len = (size_t)(cpr - cpl);
3200 # ifndef BUILD_AS_LIB
3202 FILE * ofp = (debug > 0) ? stdout : stderr;
3203 size_t len = (size_t)(whend - where);
3205 if (len > 50) /* *must* fit into an 'int'! */
3207 fprintf(ofp, "nextvar: %s: '%.*s'\n",
3208 what, (int)len, where);
3210 # else /*defined(BUILD_AS_LIB)*/
3216 # endif /*defined(BUILD_AS_LIB)*/
3220 * nextvar - find the next variable in the buffer
3230 enum PState { sDone, sInit, sName, sValU, sValQ };
3232 static char name[MAXVARLEN], value[MAXVALLEN];
3234 const char *cp, *cpend;
3235 const char *np, *vp;
3240 cpend = *datap + *datalen;
3247 ch = pf_getch(datap, cpend);
3249 while (st != sDone) {
3252 case sInit: /* handle inter-item chars */
3253 while (cp_ivspace(ch))
3254 ch = pf_nextch(datap, cpend);
3255 if (cp_namechar(ch)) {
3259 ch = pf_nextch(datap, cpend);
3265 case sName: /* collect name */
3266 while (cp_namechar(ch))
3267 ch = pf_nextch(datap, cpend);
3268 nlen = (size_t)(*datap - np);
3270 ch = pf_nextch(datap, cpend);
3280 case sValU: /* collect unquoted part(s) of value */
3281 while (cp_uqchar(ch))
3282 ch = pf_nextch(datap, cpend);
3284 ch = pf_nextch(datap, cpend);
3287 vlen = (size_t)(*datap - vp);
3294 case sValQ: /* collect quoted part(s) of value */
3295 while (cp_qschar(ch))
3296 ch = pf_nextch(datap, cpend);
3298 ch = pf_nextch(datap, cpend);
3301 pf_error("no closing quote, stop", cp, cpend);
3307 pf_error("state machine error, stop", *datap, cpend);
3312 /* If name or value do not fit their buffer, croak and start
3313 * over. If there's no name at all after whitespace stripping,
3316 nlen = str_strip(&np, nlen);
3317 vlen = str_strip(&vp, vlen);
3322 if (nlen >= sizeof(name)) {
3323 pf_error("runaway name", np, cpend);
3326 if (vlen >= sizeof(value)) {
3327 pf_error("runaway value", vp, cpend);
3331 /* copy name and value into NUL-terminated buffers */
3332 memcpy(name, np, nlen);
3336 memcpy(value, vp, vlen);
3340 /* check if there's more to do or if we are finshed */
3341 *datalen = (size_t)(cpend - *datap);
3352 varfmt(const char * varname)
3356 for (n = 0; n < COUNTOF(cookedvars); n++)
3357 if (!strcmp(varname, cookedvars[n].varname))
3358 return cookedvars[n].fmt;
3365 * printvars - print variables returned in response packet
3378 rawprint(sttype, length, data, status, quiet, fp);
3380 cookedprint(sttype, length, data, status, quiet, fp);
3385 * rawprint - do a printout of the data in raw mode
3401 * Essentially print the data as is. We reformat unprintables, though.
3404 cpend = data + length;
3407 (void) fprintf(fp, "status=0x%04x,\n", status);
3409 while (cp < cpend) {
3412 * If this is a \r and the next character is a
3413 * \n, supress this, else pretty print it. Otherwise
3414 * just output the character.
3416 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3417 makeascii(1, cp, fp);
3418 } else if (isspace(pgetc(cp)) || isprint(pgetc(cp)))
3421 makeascii(1, cp, fp);
3428 * Global data used by the cooked output routines
3430 int out_chars; /* number of characters output */
3431 int out_linecount; /* number of characters output on this line */
3435 * startoutput - get ready to do cooked output
3446 * output - output a variable=value combination
3457 /* strlen of "name=value" */
3458 len = size2int_sat(strlen(name) + 1 + strlen(value));
3460 if (out_chars != 0) {
3462 if ((out_linecount + len + 2) > MAXOUTLINE) {
3475 out_linecount += len;
3480 * endoutput - terminate a block of cooked output
3493 * outputarr - output an array of values
3512 * Hack to align delay and offset values
3514 for (i = (int)strlen(name); i < 11; i++)
3517 for (i = narr; i > 0; i--) {
3518 if (i != (size_t)narr)
3520 cp = (issigned ? lfptoms(lfp, 2) : ulfptoms(lfp, 2));
3535 output(fp, name, buf);
3544 # error BLEN is too small -- increase!
3551 s = cp = circ_buf[nextcb];
3552 if (++nextcb >= NUMCB)
3554 cb = sizeof(circ_buf[0]);
3556 l = snprintf(cp, cb, "%02lx", val);
3557 if (l < 0 || (size_t)l >= cb)
3562 l = strlcat(cp, " ok", cb);
3563 if ((size_t)l >= cb)
3571 for (i = 0; i < COUNTOF(tstflagnames); i++) {
3573 l = snprintf(cp, cb, "%s%s", sep,
3577 if ((size_t)l >= cb) {
3580 l = strlcpy (cp, "...", cb);
3601 * cookedprint - output variables in cooked mode
3624 char bn[2 * MAXVARLEN];
3625 char bv[2 * MAXVALLEN];
3627 UNUSED_ARG(datatype);
3630 fprintf(fp, "status=%04x %s,\n", status,
3631 statustoa(datatype, status));
3634 while (nextvar(&length, &data, &name, &value)) {
3644 if (!value || !decodets(value, &lfp))
3647 output(fp, name, prettydate(&lfp));
3650 case HA: /* fallthru */
3652 if (!value || !decodenetnum(value, &hval)) {
3654 } else if (fmt == HA){
3655 output(fp, name, nntohost(&hval));
3657 output(fp, name, stoa(&hval));
3664 } else if (decodenetnum(value, &hval)) {
3665 if (datatype == TYPE_CLOCK && IS_IPV4(&hval)) {
3667 * Workaround to override numeric refid formats
3668 * for refclocks received from faulty nptd servers
3669 * and output them as text.
3672 unsigned char *str = (unsigned char *)&(hval.sa4).sin_addr;
3674 for (i=0; i<4 && str[i]; i++)
3675 refid_buf[i] = (isprint(str[i]) ? str[i] : '?');
3676 refid_buf[i] = 0; /* Null terminator */
3677 output(fp, name, refid_buf);
3678 } else if (ISREFCLOCKADR(&hval)) {
3679 output(fp, name, refnumtoa(&hval));
3681 if (drefid == REFID_IPV4) {
3682 output(fp, name, stoa(&hval));
3685 snprintf (refid_buf, sizeof(refid_buf),
3686 "0x%08x", ntohl(addr2refid(&hval)));
3687 output(fp, name, refid_buf);
3690 } else if (strlen(value) <= 4) {
3691 output(fp, name, value);
3698 if (!value || !decodeuint(value, &uval) || uval > 3) {
3708 output(fp, name, b);
3713 if (!value || !decodeuint(value, &uval)) {
3716 snprintf(b, sizeof(b), "%03lo", uval);
3717 output(fp, name, b);
3723 if (!value || !decodearr(value, &narr, lfparr, 8))
3726 outputarr(fp, name, narr, lfparr, (fmt==AS));
3730 if (!value || !decodeuint(value, &uval))
3733 output(fp, name, tstflags(uval));
3739 else if (isdigit(*value)) { /* number without sign */
3741 atoascii (value, MAXVALLEN, bv+1, sizeof(bv)-1);
3742 output(fp, name, bv);
3744 output_raw = '*'; /* output as-is */
3748 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3754 if (output_raw != 0) {
3755 /* TALOS-CAN-0063: avoid buffer overrun */
3756 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3757 if (output_raw != '*') {
3758 atoascii(value, MAXVALLEN,
3759 bv, sizeof(bv) - 1);
3761 bv[len] = output_raw;
3764 atoascii(value, MAXVALLEN,
3775 * sortassoc - sort associations in the cache into ascending order
3781 qsort(assoc_cache, (size_t)numassoc,
3782 sizeof(assoc_cache[0]), &assoccmp);
3787 * assoccmp - compare two associations
3795 const struct association *ass1 = t1;
3796 const struct association *ass2 = t2;
3798 if (ass1->assid < ass2->assid)
3800 if (ass1->assid > ass2->assid)
3807 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3809 * The strategy is to add an assumed 4k page size at a time, leaving
3810 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3813 grow_assoc_cache(void)
3815 static size_t prior_sz;
3818 new_sz = prior_sz + 4 * 1024;
3819 if (0 == prior_sz) {
3820 new_sz -= 4 * sizeof(void *);
3822 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3824 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3829 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3831 * By default, autoopts loses the relative order of -c and -p options
3832 * on the command line. This routine replaces the default handler for
3833 * those routines and builds a list of commands to execute preserving
3837 ntpq_custom_opt_handler(
3842 switch (pOptDesc->optValue) {
3846 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3847 pOptDesc->optValue, pOptDesc->optValue);
3851 ADDCMD(pOptDesc->pzLastArg);
3860 * Obtain list of digest names
3863 #if defined(OPENSSL) && !defined(HAVE_EVP_MD_DO_ALL_SORTED)
3864 # if defined(_MSC_VER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
3865 # define HAVE_EVP_MD_DO_ALL_SORTED
3870 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3871 # define K_PER_LINE 8
3872 # define K_NL_PFX_STR "\n "
3873 # define K_DELIM_STR ", "
3882 # ifndef BUILD_AS_LIB
3884 list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg)
3887 const char *name, **seen;
3888 struct hstate *hstate = arg;
3891 /* m is MD obj, from is name or alias, to is base name for alias */
3892 if (!m || !from || to)
3893 return; /* Ignore aliases */
3895 /* Discard MACs that NTP won't accept. */
3896 /* Keep this consistent with keytype_from_text() in ssl_init.c. */
3897 if (EVP_MD_size(m) > (MAX_MAC_LEN - sizeof(keyid_t)))
3900 name = EVP_MD_name(m);
3902 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3904 for (cp = name; *cp; cp++)
3905 if (islower((unsigned char)*cp))
3908 len = (cp - name) + 1;
3910 /* There are duplicates. Discard if name has been seen. */
3912 for (seen = hstate->seen; *seen; seen++)
3913 if (!strcmp(*seen, name))
3916 n = (seen - hstate->seen) + 2;
3917 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3918 hstate->seen[n-2] = name;
3919 hstate->seen[n-1] = NULL;
3921 if (hstate->list != NULL)
3922 len += strlen(hstate->list);
3924 len += (hstate->idx >= K_PER_LINE)
3925 ? strlen(K_NL_PFX_STR)
3926 : strlen(K_DELIM_STR);
3928 if (hstate->list == NULL) {
3929 hstate->list = (char *)emalloc(len);
3930 hstate->list[0] = '\0';
3932 hstate->list = (char *)erealloc(hstate->list, len);
3935 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3936 ((hstate->idx >= K_PER_LINE) ? K_NL_PFX_STR : K_DELIM_STR),
3939 if (hstate->idx >= K_PER_LINE)
3944 # endif /* !defined(BUILD_AS_LIB) */
3946 # ifndef BUILD_AS_LIB
3947 /* Insert CMAC into SSL digests list */
3949 insert_cmac(char *list)
3956 /* If list empty, we need to insert CMAC on new line */
3957 insert = (!list || !*list);
3960 len = strlen(K_NL_PFX_STR) + strlen(CMAC);
3961 list = (char *)erealloc(list, len + 1);
3962 sprintf(list, "%s%s", K_NL_PFX_STR, CMAC);
3963 } else { /* List not empty */
3964 /* Check if CMAC already in list - future proofing */
3965 const char *cmac_sn;
3968 cmac_sn = OBJ_nid2sn(NID_cmac);
3970 insert = cmac_sn != NULL && *cmac_sn != '\0';
3972 /* CMAC in list if found, followed by nul char or ',' */
3973 while (insert && NULL != (cmac_p = strstr(cmac_p, cmac_sn))) {
3974 cmac_p += strlen(cmac_sn);
3975 /* Still need to insert if not nul and not ',' */
3976 insert = *cmac_p && ',' != *cmac_p;
3979 /* Find proper insertion point */
3986 /* Default to start if list empty */
3991 /* While new lines */
3992 while (delim < list + len && *delim &&
3993 !strncmp(K_NL_PFX_STR, delim, strlen(K_NL_PFX_STR))) {
3994 point = delim + strlen(K_NL_PFX_STR);
3996 /* While digest names on line */
3997 while (point < list + len && *point) {
3998 /* Another digest after on same or next line? */
3999 delim = strstr( point, K_DELIM_STR);
4000 last_nl = strstr( point, K_NL_PFX_STR);
4002 /* No - end of list */
4003 if (!delim && !last_nl) {
4006 /* New line and no delim or before delim? */
4007 if (last_nl && (!delim || last_nl < delim)) {
4011 /* Found insertion point where CMAC before entry? */
4012 if (strncmp(CMAC, point, delim - point) < 0) {
4017 if (delim < list + len && *delim &&
4018 !strncmp(K_DELIM_STR, delim, strlen(K_DELIM_STR))) {
4019 point += strlen(K_DELIM_STR);
4023 } /* While digest names on line */
4024 } /* While new lines */
4026 /* If found in list */
4028 /* insert cmac and delim */
4029 /* Space for list could move - save offset */
4030 ptrdiff_t p_offset = point - list;
4031 len += strlen(CMAC) + strlen(K_DELIM_STR);
4032 list = (char *)erealloc(list, len + 1);
4033 point = list + p_offset;
4034 /* move to handle src/dest overlap */
4035 memmove(point + strlen(CMAC) + strlen(K_DELIM_STR),
4036 point, strlen(point) + 1);
4037 strncpy(point, CMAC, strlen(CMAC));
4038 strncpy(point + strlen(CMAC), K_DELIM_STR, strlen(K_DELIM_STR));
4039 } else { /* End of list */
4040 /* append delim and cmac */
4041 len += strlen(K_DELIM_STR) + strlen(CMAC);
4042 list = (char *)erealloc(list, len + 1);
4043 strcpy(list + strlen(list), K_DELIM_STR);
4044 strcpy(list + strlen(list), CMAC);
4047 } /* List not empty */
4048 #endif /*ENABLE_CMAC*/
4051 # endif /* !defined(BUILD_AS_LIB) */
4056 #ifndef BUILD_AS_LIB
4058 list_digest_names(void)
4063 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
4064 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
4066 /* replace calloc(1, sizeof(const char *)) */
4067 hstate.seen = (const char **)emalloc_zero(sizeof(const char *));
4070 EVP_MD_do_all_sorted(list_md_fn, &hstate);
4074 list = insert_cmac(list); /* Insert CMAC into SSL digests list */
4077 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
4078 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
4081 list = (char *)emalloc(sizeof("md5"));
4082 strcpy(list, "md5");
4087 #endif /* !defined(BUILD_AS_LIB) */
4089 #define CTRLC_STACK_MAX 4
4090 static volatile size_t ctrlc_stack_len = 0;
4091 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
4096 push_ctrl_c_handler(
4100 size_t size = ctrlc_stack_len;
4101 if (func && (size < CTRLC_STACK_MAX)) {
4102 ctrlc_stack[size] = func;
4103 ctrlc_stack_len = size + 1;
4114 size_t size = ctrlc_stack_len;
4117 if (func == NULL || func == ctrlc_stack[size]) {
4118 ctrlc_stack_len = size;
4125 #ifndef BUILD_AS_LIB
4129 size_t size = ctrlc_stack_len;
4131 if ((*ctrlc_stack[--size])())
4134 #endif /* !defined(BUILD_AS_LIB) */
4136 #ifndef BUILD_AS_LIB
4147 char * buf = emalloc(len);
4150 /* Note: we expect the memory allocation to fail long before the
4151 * increment in buffer size actually overflows.
4153 buf = (buf) ? erealloc(buf, len) : emalloc(len);
4156 prc = vsnprintf(buf, len, fmt, va);
4160 /* might be very old vsnprintf. Or actually MSVC... */
4164 if ((size_t)prc >= len) {
4165 /* at least we have the proper size now... */
4166 len = (size_t)prc + 1;
4169 if ((size_t)prc < (len - 32))
4170 buf = erealloc(buf, (size_t)prc + 1);
4174 #endif /* !defined(BUILD_AS_LIB) */