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 AR 5 /* array of 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 EOV 255 /* end of table */
132 * For the most part ntpq simply displays what ntpd provides in the
133 * mostly plain-text mode 6 responses. A few variable names are by
134 * default "cooked" to provide more human-friendly output.
136 const var_format cookedvars[] = {
147 { "peeradr", HA }, /* compat with others */
150 { "filtoffset", AR },
152 { "filterror", AR }, /* compat with others */
160 static const char *tstflagnames[] = {
161 "pkt_dup", /* TEST1 */
162 "pkt_bogus", /* TEST2 */
163 "pkt_unsync", /* TEST3 */
164 "pkt_denied", /* TEST4 */
165 "pkt_auth", /* TEST5 */
166 "pkt_stratum", /* TEST6 */
167 "pkt_header", /* TEST7 */
168 "pkt_autokey", /* TEST8 */
169 "pkt_crypto", /* TEST9 */
170 "peer_stratum", /* TEST10 */
171 "peer_dist", /* TEST11 */
172 "peer_loop", /* TEST12 */
173 "peer_unreach" /* TEST13 */
177 int ntpqmain (int, char **);
179 * Built in command handler declarations
181 static int openhost (const char *, int);
182 static void dump_hex_printable(const void *, size_t);
183 static int sendpkt (void *, size_t);
184 static int getresponse (int, int, u_short *, size_t *, const char **, int);
185 static int sendrequest (int, associd_t, int, size_t, const char *);
186 static char * tstflags (u_long);
188 static void getcmds (void);
190 static int abortcmd (void);
191 #endif /* SYS_WINNT */
192 static void docmd (const char *);
193 static void tokenize (const char *, char **, int *);
194 static int getarg (const char *, int, arg_v *);
195 #endif /* BUILD_AS_LIB */
196 static int findcmd (const char *, struct xcmd *,
197 struct xcmd *, struct xcmd **);
198 static int rtdatetolfp (char *, l_fp *);
199 static int decodearr (char *, int *, l_fp *, int);
200 static void help (struct parse *, FILE *);
201 static int helpsort (const void *, const void *);
202 static void printusage (struct xcmd *, FILE *);
203 static void timeout (struct parse *, FILE *);
204 static void auth_delay (struct parse *, FILE *);
205 static void host (struct parse *, FILE *);
206 static void ntp_poll (struct parse *, FILE *);
207 static void keyid (struct parse *, FILE *);
208 static void keytype (struct parse *, FILE *);
209 static void passwd (struct parse *, FILE *);
210 static void hostnames (struct parse *, FILE *);
211 static void setdebug (struct parse *, FILE *);
212 static void quit (struct parse *, FILE *);
213 static void showdrefid (struct parse *, FILE *);
214 static void version (struct parse *, FILE *);
215 static void raw (struct parse *, FILE *);
216 static void cooked (struct parse *, FILE *);
217 static void authenticate (struct parse *, FILE *);
218 static void ntpversion (struct parse *, FILE *);
219 static void warning (const char *, ...) NTP_PRINTF(1, 2);
220 static void error (const char *, ...) NTP_PRINTF(1, 2);
221 static u_long getkeyid (const char *);
222 static void atoascii (const char *, size_t, char *, size_t);
223 static void cookedprint (int, size_t, const char *, int, int, FILE *);
224 static void rawprint (int, size_t, const char *, int, int, FILE *);
225 static void startoutput (void);
226 static void output (FILE *, const char *, const char *);
227 static void endoutput (FILE *);
228 static void outputarr (FILE *, char *, int, l_fp *);
229 static int assoccmp (const void *, const void *);
230 u_short varfmt (const char *);
231 void ntpq_custom_opt_handler(tOptions *, tOptDesc *);
234 static char *list_digest_names(void);
235 static char *insert_cmac (char *list);
236 static void on_ctrlc (void);
237 static int my_easprintf (char**, const char *, ...) NTP_PRINTF(2, 3);
238 # if defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED)
239 static void list_md_fn (const EVP_MD *m, const char *from,
240 const char *to, void *arg);
241 # endif /* defined(OPENSSL) && defined(HAVE_EVP_MD_DO_ALL_SORTED) */
242 #endif /* !defined(BUILD_AS_LIB) */
245 /* read a character from memory and expand to integer */
251 return (int)*(const unsigned char*)cp;
257 * Built-in commands we understand
259 struct xcmd builtins[] = {
260 { "?", help, { OPT|NTP_STR, NO, NO, NO },
261 { "command", "", "", "" },
262 "tell the use and syntax of commands" },
263 { "help", help, { OPT|NTP_STR, NO, NO, NO },
264 { "command", "", "", "" },
265 "tell the use and syntax of commands" },
266 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
267 { "msec", "", "", "" },
268 "set the primary receive time out" },
269 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
270 { "msec", "", "", "" },
271 "set the delay added to encryption time stamps" },
272 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
273 { "-4|-6", "hostname", "", "" },
274 "specify the host whose NTP server we talk to" },
275 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
276 { "n", "verbose", "", "" },
277 "poll an NTP server in client mode `n' times" },
278 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
280 "specify a password to use for authenticated requests"},
281 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
282 { "yes|no", "", "", "" },
283 "specify whether hostnames or net numbers are printed"},
284 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
285 { "no|more|less", "", "", "" },
286 "set/change debugging level" },
287 { "quit", quit, { NO, NO, NO, NO },
290 { "exit", quit, { NO, NO, NO, NO },
293 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
294 { "key#", "", "", "" },
295 "set keyid to use for authenticated requests" },
296 { "drefid", showdrefid, { OPT|NTP_STR, NO, NO, NO },
297 { "hash|ipv4", "", "", "" },
298 "display refid's as IPv4 or hash" },
299 { "version", version, { NO, NO, NO, NO },
301 "print version number" },
302 { "raw", raw, { NO, NO, NO, NO },
304 "do raw mode variable output" },
305 { "cooked", cooked, { NO, NO, NO, NO },
307 "do cooked mode variable output" },
308 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
309 { "yes|no", "", "", "" },
310 "always authenticate requests to this server" },
311 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
312 { "version number", "", "", "" },
313 "set the NTP version number to use for requests" },
314 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
315 { "key type %s", "", "", "" },
317 { 0, 0, { NO, NO, NO, NO },
318 { "", "", "", "" }, "" }
323 * Default values we use.
325 #define DEFHOST "localhost" /* default host name */
326 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
327 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
329 * Requests are automatically retried once, so total timeout with no
330 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
331 * extreme, a request eliciting 32 packets of responses each for some
332 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
333 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
334 * 93 seconds to fail each of two times, or 186 seconds.
335 * Some commands involve a series of requests, such as "peers" and
336 * "mrulist", so the cumulative timeouts are even longer for those.
338 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
339 #define LENHOSTNAME 256 /* host name is 256 characters long */
340 #define MAXCMDS 100 /* maximum commands on cmd line */
341 #define MAXHOSTS 200 /* maximum hosts on cmd line */
342 #define MAXLINE 512 /* maximum line length */
343 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
344 #define MAXVARLEN 256 /* maximum length of a variable name */
345 #define MAXVALLEN 2048 /* maximum length of a variable value */
346 #define MAXOUTLINE 72 /* maximum length of an output line */
347 #define SCREENWIDTH 76 /* nominal screen width in columns */
350 * Some variables used and manipulated locally
352 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
353 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
354 l_fp delay_time; /* delay time */
355 char currenthost[LENHOSTNAME]; /* current host name */
356 int currenthostisnum; /* is prior text from IP? */
357 struct sockaddr_in hostaddr; /* host address */
358 int showhostnames = 1; /* show host names by default */
359 int wideremote = 0; /* show wide remote names? */
361 int ai_fam_templ; /* address family */
362 int ai_fam_default; /* default address family */
363 SOCKET sockfd; /* fd socket is opened on */
364 int havehost = 0; /* set to 1 when host open */
366 struct servent *server_entry = NULL; /* server entry for ntp */
370 * Sequence number used for requests. It is incremented before
376 * Holds data returned from queries. Declare buffer long to be sure of
379 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
380 long pktdata[DATASIZE/sizeof(long)];
383 * assoc_cache[] is a dynamic array which allows references to
384 * associations using &1 ... &N for n associations, avoiding manual
385 * lookup of the current association IDs for a given ntpd. It also
386 * caches the status word for each association, retrieved incidentally.
388 struct association * assoc_cache;
389 u_int assoc_cache_slots;/* count of allocated array entries */
390 u_int numassoc; /* number of cached associations */
393 * For commands typed on the command line (with the -c option)
396 const char *ccmds[MAXCMDS];
397 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
400 * When multiple hosts are specified.
405 chost chosts[MAXHOSTS];
406 #define ADDHOST(cp) \
408 if (numhosts < MAXHOSTS) { \
409 chosts[numhosts].name = (cp); \
410 chosts[numhosts].fam = ai_fam_templ; \
416 * Macro definitions we use
418 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
419 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
420 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
423 * Jump buffer for longjumping back to the command level.
425 * Since we do this from a signal handler, we use 'sig{set,long}jmp()'
426 * if available. The signal is blocked by default during the excution of
427 * a signal handler, and it is unspecified if '{set,long}jmp()' save and
428 * restore the signal mask. They do on BSD, it depends on the GLIBC
429 * version on Linux, and the gods know what happens on other OSes...
431 * So we use the 'sig{set,long}jmp()' functions where available, because
432 * for them the semantics are well-defined. If we have to fall back to
433 * '{set,long}jmp()', the CTRL-C handling might be a bit erratic.
435 #if HAVE_DECL_SIGSETJMP && HAVE_DECL_SIGLONGJMP
436 # define JMP_BUF sigjmp_buf
437 # define SETJMP(x) sigsetjmp((x), 1)
438 # define LONGJMP(x, v) siglongjmp((x),(v))
440 # define JMP_BUF jmp_buf
441 # define SETJMP(x) setjmp((x))
442 # define LONGJMP(x, v) longjmp((x),(v))
444 static JMP_BUF interrupt_buf;
445 static volatile int jump = 0;
448 * Points at file being currently printed into
450 FILE *current_output = NULL;
453 * Command table imported from ntpdc_ops.c
455 extern struct xcmd opcmds[];
457 char const *progname;
459 #ifdef NO_MAIN_ALLOWED
461 CALL(ntpq,"ntpq",ntpqmain);
463 void clear_globals(void)
465 extern int ntp_optind;
466 showhostnames = 0; /* don'tshow host names by default */
468 server_entry = NULL; /* server entry for ntp */
469 havehost = 0; /* set to 1 when host open */
470 numassoc = 0; /* number of cached associations */
474 #endif /* !BUILD_AS_LIB */
475 #endif /* NO_MAIN_ALLOWED */
478 * main - parse arguments and handle options
480 #ifndef NO_MAIN_ALLOWED
487 return ntpqmain(argc, argv);
505 taskPrioritySet(taskIdSelf(), 100 );
509 delay_time.l_uf = DEFDELAY;
511 init_lib(); /* sets up ipv4_works, ipv6_works */
515 /* Check to see if we have IPv6. Otherwise default to IPv4 */
517 ai_fam_default = AF_INET;
519 /* Fixup keytype's help based on available digest names */
525 list = list_digest_names();
527 for (icmd = 0; icmd < sizeof(builtins)/sizeof(*builtins); icmd++) {
528 if (strcmp("keytype", builtins[icmd].keyword) == 0) {
534 /* This should only "trip" if "keytype" is removed from builtins */
535 INSIST(icmd < sizeof(builtins)/sizeof(*builtins));
538 builtins[icmd].desc[0] = "digest-name";
540 "set key type to use for authenticated requests, one of:%s",
543 builtins[icmd].desc[0] = "md5";
545 "set key type to use for authenticated requests (%s)",
548 builtins[icmd].comment = msg;
555 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
561 * Process options other than -c and -p, which are specially
562 * handled by ntpq_custom_opt_handler().
565 debug = OPT_VALUE_SET_DEBUG_LEVEL;
568 ai_fam_templ = AF_INET;
569 else if (HAVE_OPT(IPV6))
570 ai_fam_templ = AF_INET6;
572 ai_fam_templ = ai_fam_default;
574 if (HAVE_OPT(INTERACTIVE))
577 if (HAVE_OPT(NUMERIC))
583 old_rv = HAVE_OPT(OLD_RV);
585 drefid = OPT_VALUE_REFID;
590 for (ihost = 0; ihost < (u_int)argc; ihost++) {
591 if ('-' == *argv[ihost]) {
593 // If I really cared I'd also check:
594 // 0 == argv[ihost][2]
596 // and there are other cases as well...
598 if ('4' == argv[ihost][1]) {
599 ai_fam_templ = AF_INET;
601 } else if ('6' == argv[ihost][1]) {
602 ai_fam_templ = AF_INET6;
605 // XXX Throw a usage error
608 ADDHOST(argv[ihost]);
612 if (numcmds == 0 && interactive == 0
613 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
617 set_ctrl_c_hook(on_ctrlc);
618 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
620 push_ctrl_c_handler(abortcmd);
621 #endif /* SYS_WINNT */
624 (void) openhost(chosts[0].name, chosts[0].fam);
627 for (ihost = 0; ihost < numhosts; ihost++) {
628 if (openhost(chosts[ihost].name, chosts[ihost].fam)) {
629 if (ihost && current_output)
630 fputc('\n', current_output);
631 for (icmd = 0; icmd < numcmds; icmd++) {
632 if (icmd && current_output)
633 fputc('\n', current_output);
641 #endif /* SYS_WINNT */
644 #endif /* !BUILD_AS_LIB */
647 * openhost - open a socket to a host
655 const char svc[] = "ntp";
656 char temphost[LENHOSTNAME];
658 struct addrinfo hints, *ai;
662 char name[LENHOSTNAME];
665 * We need to get by the [] if they were entered
668 cp = strchr(hname + 1, ']');
669 if (!cp || (octets = (size_t)(cp - hname) - 1) >= sizeof(name)) {
671 warning("%s", "bad hostname/address");
674 memcpy(name, hname + 1, octets);
680 * First try to resolve it as an ip address and if that fails,
681 * do a fullblown (dns) lookup. That way we only use the dns
682 * when it is needed and work around some implementations that
683 * will return an "IPv4-mapped IPv6 address" address if you
684 * give it an IPv4 address to lookup.
687 hints.ai_family = fam;
688 hints.ai_protocol = IPPROTO_UDP;
689 hints.ai_socktype = SOCK_DGRAM;
690 hints.ai_flags = Z_AI_NUMERICHOST;
693 a_info = getaddrinfo(hname, svc, &hints, &ai);
694 if (a_info == EAI_NONAME
696 || a_info == EAI_NODATA
699 hints.ai_flags = AI_CANONNAME;
701 hints.ai_flags |= AI_ADDRCONFIG;
703 a_info = getaddrinfo(hname, svc, &hints, &ai);
706 /* Some older implementations don't like AI_ADDRCONFIG. */
707 if (a_info == EAI_BADFLAGS) {
708 hints.ai_flags &= ~AI_ADDRCONFIG;
709 a_info = getaddrinfo(hname, svc, &hints, &ai);
713 fprintf(stderr, "%s\n", gai_strerror(a_info));
719 octets = min(sizeof(addr), ai->ai_addrlen);
720 memcpy(&addr, ai->ai_addr, octets);
722 if (ai->ai_canonname == NULL) {
723 strlcpy(temphost, stoa(&addr), sizeof(temphost));
724 currenthostisnum = TRUE;
726 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
727 currenthostisnum = FALSE;
731 printf("Opening host %s (%s)\n",
733 (ai->ai_family == AF_INET)
735 : (ai->ai_family == AF_INET6)
742 printf("Closing old host %s\n", currenthost);
746 strlcpy(currenthost, temphost, sizeof(currenthost));
748 /* port maps to the same location in both families */
749 s_port = NSRCPORT(&addr);
751 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
752 if (ai->ai_family == AF_INET)
753 *(struct sockaddr_in *)&hostaddr=
754 *((struct sockaddr_in *)ai->ai_addr);
756 *(struct sockaddr_in6 *)&hostaddr=
757 *((struct sockaddr_in6 *)ai->ai_addr);
758 #endif /* SYS_VXWORKS */
762 int optionValue = SO_SYNCHRONOUS_NONALERT;
765 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
766 (void *)&optionValue, sizeof(optionValue));
769 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
775 #endif /* SYS_WINNT */
777 sockfd = socket(ai->ai_family, ai->ai_socktype,
779 if (sockfd == INVALID_SOCKET) {
786 #ifdef NEED_RCVBUF_SLOP
788 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
789 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
790 (void *)&rbufsize, sizeof(int)) == -1)
798 (connect(sockfd, (struct sockaddr *)&hostaddr,
799 sizeof(hostaddr)) == -1)
801 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
802 ai->ai_addrlen) == -1)
803 #endif /* SYS_VXWORKS */
823 /* every line shows at most 16 bytes, so we need a buffer of
824 * 4 * 16 (2 xdigits, 1 char, one sep for xdigits)
825 * + 2 * 1 (block separators)
830 static const char s_xdig[16] = "0123456789ABCDEF";
834 const u_char * cdata = data;
838 memset(lbuf, ' ', sizeof(lbuf));
840 pptr = lbuf + 3*16 + 2;
842 rowlen = (len > 16) ? 16 : (int)len;
848 *xptr++ = s_xdig[ch >> 4 ];
849 *xptr++ = s_xdig[ch & 0x0F];
850 if (++xptr == lbuf + 3*8)
853 *pptr++ = isprint(ch) ? (char)ch : '.';
863 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
865 * sendpkt - send a packet to the remote host
874 printf("Sending %zu octets\n", xdatalen);
876 if (send(sockfd, xdata, xdatalen, 0) == -1) {
877 warning("write to %s failed", currenthost);
882 printf("Request packet:\n");
883 dump_hex_printable(xdata, xdatalen);
889 * getresponse - get a (series of) response packet(s) and return the data
901 struct ntp_control rpkt;
902 struct sock_timeval tvo;
903 u_short offsets[MAXFRAGS+1];
904 u_short counts[MAXFRAGS+1];
915 /* absolute timeout checks. Not 'time_t' by intention! */
916 uint32_t tobase; /* base value for timeout */
917 uint32_t tospan; /* timeout span (max delay) */
918 uint32_t todiff; /* current delay */
920 memset(offsets, 0, sizeof(offsets));
921 memset(counts , 0, sizeof(counts ));
924 * This is pretty tricky. We may get between 1 and MAXFRAG packets
925 * back in response to the request. We peel the data out of
926 * each packet and collect it in one long block. When the last
927 * packet in the sequence is received we'll know how much data we
928 * should have had. Note we use one long time out, should reconsider.
933 *rdata = (char *)pktdata;
938 tobase = (uint32_t)time(NULL);
943 * Loop until we have an error or a complete response. Nearly all
944 * code paths to loop again use continue.
952 tospan = (uint32_t)tvo.tv_sec + (tvo.tv_usec != 0);
954 FD_SET(sockfd, &fds);
955 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
957 #if !defined(SYS_WINNT) && defined(EINTR)
958 /* Windows does not know about EINTR (until very
959 * recently) and the handling of console events
960 * is *very* different from POSIX/UNIX signal
963 * Under non-windows targets we map EINTR as
964 * 'last packet was received' and try to exit
965 * the receive sequence.
967 if (errno == EINTR) {
972 warning("select fails");
977 * Check if this is already too late. Trash the data and
978 * fake a timeout if this is so.
980 todiff = (((uint32_t)time(NULL)) - tobase) & 0x7FFFFFFFu;
981 if ((n > 0) && (todiff > tospan)) {
982 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
983 n -= n; /* faked timeout return from 'select()',
984 * execute RMW cycle on 'n'
990 * Timed out. Return what we have
995 "%s: timed out, nothing received\n",
1001 "%s: timed out with incomplete data\n",
1005 "ERR_INCOMPLETE: Received fragments:\n");
1006 for (f = 0; f < numfrags; f++)
1008 "%2u: %5d %5d\t%3d octets\n",
1009 (u_int)f, offsets[f],
1014 "last fragment %sreceived\n",
1019 return ERR_INCOMPLETE;
1022 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
1029 printf("Response packet:\n");
1030 dump_hex_printable(&rpkt, n);
1034 * Check for format errors. Bug proofing.
1036 if (n < (int)CTL_HEADER_LEN) {
1038 printf("Short (%d byte) packet received\n", n);
1041 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
1042 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
1044 printf("Packet received with version %d\n",
1045 PKT_VERSION(rpkt.li_vn_mode));
1048 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
1050 printf("Packet received with mode %d\n",
1051 PKT_MODE(rpkt.li_vn_mode));
1054 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
1056 printf("Received request packet, wanted response\n");
1061 * Check opcode and sequence number for a match.
1062 * Could be old data getting to us.
1064 if (ntohs(rpkt.sequence) != sequence) {
1066 printf("Received sequnce number %d, wanted %d\n",
1067 ntohs(rpkt.sequence), sequence);
1070 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
1073 "Received opcode %d, wanted %d (sequence number okay)\n",
1074 CTL_OP(rpkt.r_m_e_op), opcode);
1079 * Check the error code. If non-zero, return it.
1081 if (CTL_ISERROR(rpkt.r_m_e_op)) {
1082 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
1083 if (CTL_ISMORE(rpkt.r_m_e_op))
1084 TRACE(1, ("Error code %d received on not-final packet\n",
1086 if (errcode == CERR_UNSPEC)
1092 * Check the association ID to make sure it matches what
1095 if (ntohs(rpkt.associd) != associd) {
1096 TRACE(1, ("Association ID %d doesn't match expected %d\n",
1097 ntohs(rpkt.associd), associd));
1099 * Hack for silly fuzzballs which, at the time of writing,
1100 * return an assID of sys.peer when queried for system variables.
1108 * Collect offset and count. Make sure they make sense.
1110 offset = ntohs(rpkt.offset);
1111 count = ntohs(rpkt.count);
1114 * validate received payload size is padded to next 32-bit
1115 * boundary and no smaller than claimed by rpkt.count
1118 TRACE(1, ("Response packet not padded, size = %d\n",
1123 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1125 if (n < shouldbesize) {
1126 printf("Response packet claims %u octets payload, above %ld received\n",
1127 count, (long)(n - CTL_HEADER_LEN));
1128 return ERR_INCOMPLETE;
1131 if (debug >= 3 && shouldbesize > n) {
1137 * Usually we ignore authentication, but for debugging purposes
1140 /* round to 8 octet boundary */
1141 shouldbesize = (shouldbesize + 7) & ~7;
1143 maclen = n - shouldbesize;
1144 if (maclen >= (int)MIN_MAC_LEN) {
1146 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1147 n, shouldbesize, maclen);
1148 lpkt = (u_int32 *)&rpkt;
1149 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1150 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1151 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1152 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1153 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1154 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1155 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1156 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1157 printf("Authenticated with keyid %lu\n", (u_long)key);
1158 if (key != 0 && key != info_auth_keyid) {
1159 printf("We don't know that key\n");
1161 if (authdecrypt(key, (u_int32 *)&rpkt,
1162 n - maclen, maclen)) {
1163 printf("Auth okay!\n");
1165 printf("Auth failed!\n");
1171 TRACE(2, ("Got packet, size = %d\n", n));
1172 if (count > (n - CTL_HEADER_LEN)) {
1173 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1174 count, (long)n - CTL_HEADER_LEN));
1177 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1178 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1181 if (offset + count > sizeof(pktdata)) {
1182 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1186 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1187 TRACE(1, ("Received second last fragment packet\n"));
1192 * So far, so good. Record this fragment, making sure it doesn't
1195 TRACE(2, ("Packet okay\n"));
1197 if (numfrags > (MAXFRAGS - 1)) {
1198 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1204 * Find the position for the fragment relative to any
1205 * previously received.
1208 f < numfrags && offsets[f] < offset;
1213 if (f < numfrags && offset == offsets[f]) {
1214 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1215 count, offset, counts[f], offsets[f]));
1219 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1220 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1221 offset, counts[f-1], offsets[f-1]));
1225 if (f < numfrags && (offset + count) > offsets[f]) {
1226 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1227 count, offset, offsets[f]));
1231 for (ff = numfrags; ff > f; ff--) {
1232 offsets[ff] = offsets[ff-1];
1233 counts[ff] = counts[ff-1];
1235 offsets[f] = offset;
1240 * Got that stuffed in right. Figure out if this was the last.
1241 * Record status info out of the last packet.
1243 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1246 *rstatus = ntohs(rpkt.status);
1250 * Copy the data into the data buffer, and bump the
1251 * timout base in case we need more.
1253 memcpy((char *)pktdata + offset, &rpkt.u, count);
1254 tobase = (uint32_t)time(NULL);
1257 * If we've seen the last fragment, look for holes in the sequence.
1258 * If there aren't any, we're done.
1260 #if !defined(SYS_WINNT) && defined(EINTR)
1264 if (seenlastfrag && offsets[0] == 0) {
1265 for (f = 1; f < numfrags; f++)
1266 if (offsets[f-1] + counts[f-1] !=
1269 if (f == numfrags) {
1270 *rsize = offsets[f-1] + counts[f-1];
1271 TRACE(1, ("%lu packets reassembled into response\n",
1276 } /* giant for (;;) collecting response packets */
1277 } /* getresponse() */
1281 * sendrequest - format and send a request packet
1292 struct ntp_control qpkt;
1299 * Check to make sure the data will fit in one packet
1301 if (qsize > CTL_MAX_DATA_LEN) {
1303 "***Internal error! qsize (%zu) too large\n",
1309 * Fill in the packet
1311 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1312 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1313 qpkt.sequence = htons(sequence);
1315 qpkt.associd = htons((u_short)associd);
1317 qpkt.count = htons((u_short)qsize);
1319 pktsize = CTL_HEADER_LEN;
1322 * If we have data, copy and pad it out to a 32-bit boundary.
1325 memcpy(&qpkt.u, qdata, (size_t)qsize);
1327 while (pktsize & (sizeof(u_int32) - 1)) {
1328 qpkt.u.data[qsize++] = 0;
1334 * If it isn't authenticated we can just send it. Otherwise
1335 * we're going to have to think about it a little.
1337 if (!auth && !always_auth) {
1338 return sendpkt(&qpkt, pktsize);
1342 * Pad out packet to a multiple of 8 octets to be sure
1343 * receiver can handle it.
1345 while (pktsize & 7) {
1346 qpkt.u.data[qsize++] = 0;
1351 * Get the keyid and the password if we don't have one.
1353 if (info_auth_keyid == 0) {
1354 key_id = getkeyid("Keyid: ");
1355 if (key_id == 0 || key_id > NTP_MAXKEY) {
1357 "Invalid key identifier\n");
1360 info_auth_keyid = key_id;
1362 if (!authistrusted(info_auth_keyid)) {
1363 pass = getpass_keytype(info_auth_keytype);
1364 if ('\0' == pass[0]) {
1365 fprintf(stderr, "Invalid password\n");
1368 authusekey(info_auth_keyid, info_auth_keytype,
1370 authtrust(info_auth_keyid, 1);
1374 * Do the encryption.
1376 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1378 fprintf(stderr, "Key not found\n");
1380 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1382 "%zu octet MAC, %zu expected with %zu octet digest\n",
1383 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1388 return sendpkt((char *)&qpkt, pktsize + maclen);
1393 * show_error_msg - display the error text for a mode 6 error response.
1402 fprintf(stderr, "server=%s ", currenthost);
1408 "***Server reports a bad format request packet\n");
1411 case CERR_PERMISSION:
1413 "***Server disallowed request (authentication?)\n");
1418 "***Server reports a bad opcode in request\n");
1423 "***Association ID %d unknown to server\n",
1427 case CERR_UNKNOWNVAR:
1429 "***A request variable unknown to the server\n");
1434 "***Server indicates a request variable was bad\n");
1439 "***Server returned an unspecified error\n");
1443 fprintf(stderr, "***Request timed out\n");
1446 case ERR_INCOMPLETE:
1448 "***Response from server was incomplete\n");
1453 "***Buffer size exceeded for returned data\n");
1458 "***Server returns unknown error code %d\n",
1464 * doquery - send a request and process the response, displaying
1465 * error messages for any error responses.
1479 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1480 rsize, rdata, FALSE);
1485 * doqueryex - send a request and process the response, optionally
1486 * displaying error messages for any error responses.
1505 * Check to make sure host is open
1508 fprintf(stderr, "***No host open, use `host' command\n");
1519 res = sendrequest(opcode, associd, auth, qsize, qdata);
1524 * Get the response. If we got a standard error, print a message
1526 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1529 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1530 if (res == ERR_INCOMPLETE) {
1532 * better bump the sequence so we don't
1533 * get confused about differing fragments.
1541 show_error_msg(res, associd);
1548 #ifndef BUILD_AS_LIB
1550 * getcmds - read commands from the standard input and execute them
1558 ntp_readline_init(interactive ? prompt : NULL);
1561 line = ntp_readline(&count);
1568 ntp_readline_uninit();
1570 #endif /* !BUILD_AS_LIB */
1573 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1575 * abortcmd - catch interrupts and abort the current command
1580 if (current_output == stdout)
1581 (void) fflush(stdout);
1583 (void) fflush(stderr);
1586 LONGJMP(interrupt_buf, 1);
1590 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1593 #ifndef BUILD_AS_LIB
1595 * docmd - decode the command line and execute a command
1602 char *tokens[1+MAXARGS+2];
1609 * Tokenize the command line. If nothing on it, return.
1611 tokenize(cmdline, tokens, &ntok);
1616 * Find the appropriate command description.
1618 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1620 (void) fprintf(stderr, "***Command `%s' unknown\n",
1623 } else if (i >= 2) {
1624 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1629 /* Warn about ignored extra args */
1630 for (i = MAXARGS + 1; i < ntok ; ++i) {
1631 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1635 * Save the keyword, then walk through the arguments, interpreting
1638 pcmd.keyword = tokens[0];
1640 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1641 if ((i+1) >= ntok) {
1642 if (!(xcmd->arg[i] & OPT)) {
1643 printusage(xcmd, stderr);
1648 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1650 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1656 if (i < ntok && *tokens[i] == '>') {
1659 if (*(tokens[i]+1) != '\0')
1660 fname = tokens[i]+1;
1661 else if ((i+1) < ntok)
1662 fname = tokens[i+1];
1664 (void) fprintf(stderr, "***No file for redirect\n");
1668 current_output = fopen(fname, "w");
1669 if (current_output == NULL) {
1670 (void) fprintf(stderr, "***Error opening %s: ", fname);
1675 current_output = stdout;
1679 if ( ! SETJMP(interrupt_buf)) {
1681 (xcmd->handler)(&pcmd, current_output);
1684 fflush(current_output);
1685 fputs("\n >>> command aborted <<<\n", stderr);
1691 (xcmd->handler)(&pcmd, current_output);
1693 if ((NULL != current_output) && (stdout != current_output)) {
1694 (void)fclose(current_output);
1695 current_output = NULL;
1701 * tokenize - turn a command line into tokens
1703 * SK: Modified to allow a quoted string
1705 * HMS: If the first character of the first token is a ':' then (after
1706 * eating inter-token whitespace) the 2nd token is the rest of the line.
1716 register const char *cp;
1718 static char tspace[MAXLINE];
1722 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1725 /* Skip inter-token whitespace */
1726 while (ISSPACE(*cp))
1729 /* If we're at EOL we're done */
1733 /* If this is the 2nd token and the first token begins
1734 * with a ':', then just grab to EOL.
1737 if (*ntok == 1 && tokens[0][0] == ':') {
1739 if (sp - tspace >= MAXLINE)
1742 } while (!ISEOL(*cp));
1745 /* Check if this token begins with a double quote.
1746 * If yes, continue reading till the next double quote
1748 else if (*cp == '\"') {
1751 if (sp - tspace >= MAXLINE)
1754 } while ((*cp != '\"') && !ISEOL(*cp));
1755 /* HMS: a missing closing " should be an error */
1759 if (sp - tspace >= MAXLINE)
1762 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1763 /* HMS: Why check for a " in the previous line? */
1766 if (sp - tspace >= MAXLINE)
1775 "***Line `%s' is too big\n",
1782 * getarg - interpret an argument token
1793 switch (code & ~OPT) {
1799 if (!getnetnum(str, &argp->netnum, NULL, 0))
1804 if ('&' == str[0]) {
1805 if (!atouint(&str[1], &ul)) {
1807 "***Association index `%s' invalid/undecodable\n",
1811 if (0 == numassoc) {
1813 if (0 == numassoc) {
1815 "***No associations found, `%s' unknown\n",
1820 ul = min(ul, numassoc);
1821 argp->uval = assoc_cache[ul - 1].assid;
1824 if (!atouint(str, &argp->uval)) {
1825 fprintf(stderr, "***Illegal unsigned value %s\n",
1832 if (!atoint(str, &argp->ival)) {
1833 fprintf(stderr, "***Illegal integer value %s\n",
1840 if (!strcmp("-6", str)) {
1842 } else if (!strcmp("-4", str)) {
1845 fprintf(stderr, "***Version must be either 4 or 6\n");
1853 #endif /* !BUILD_AS_LIB */
1857 * findcmd - find a command in a command description table
1862 struct xcmd * clist1,
1863 struct xcmd * clist2,
1870 struct xcmd *nearmatch = NULL;
1877 else if (clist2 != 0)
1883 for (cl = clist; cl->keyword != 0; cl++) {
1884 /* do a first character check, for efficiency */
1885 if (*str != *(cl->keyword))
1887 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1889 * Could be extact match, could be approximate.
1890 * Is exact if the length of the keyword is the
1893 if (*((cl->keyword) + clen) == '\0') {
1903 * See if there is more to do. If so, go again. Sorry about the
1904 * goto, too much looking at BSD sources...
1906 if (clist == clist1 && clist2 != 0) {
1912 * If we got extactly 1 near match, use it, else return number
1924 * getnetnum - given a host name, return its net number
1925 * and (optional) full name
1935 struct addrinfo hints, *ai = NULL;
1938 hints.ai_flags = AI_CANONNAME;
1939 #ifdef AI_ADDRCONFIG
1940 hints.ai_flags |= AI_ADDRCONFIG;
1944 * decodenetnum only works with addresses, but handles syntax
1945 * that getaddrinfo doesn't: [2001::1]:1234
1947 if (decodenetnum(hname, num)) {
1948 if (fullhost != NULL)
1949 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1950 LENHOSTNAME, NULL, 0, 0);
1952 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1953 INSIST(sizeof(*num) >= ai->ai_addrlen);
1954 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1955 if (fullhost != NULL) {
1956 if (ai->ai_canonname != NULL)
1957 strlcpy(fullhost, ai->ai_canonname,
1960 getnameinfo(&num->sa, SOCKLEN(num),
1961 fullhost, LENHOSTNAME, NULL,
1967 fprintf(stderr, "***Can't find host %s\n", hname);
1974 * nntohost - convert network number to host name. This routine enforces
1975 * the showhostnames setting.
1982 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1987 * nntohost_col - convert network number to host name in fixed width.
1988 * This routine enforces the showhostnames setting.
1989 * When displaying hostnames longer than the width,
1990 * the first part of the hostname is displayed. When
1991 * displaying numeric addresses longer than the width,
1992 * Such as IPv6 addresses, the caller decides whether
1993 * the first or last of the numeric address is used.
1999 int preserve_lowaddrbits
2004 if (!showhostnames || SOCK_UNSPEC(addr)) {
2005 if (preserve_lowaddrbits)
2006 out = trunc_left(stoa(addr), width);
2008 out = trunc_right(stoa(addr), width);
2009 } else if (ISREFCLOCKADR(addr)) {
2010 out = refnumtoa(addr);
2012 out = trunc_right(socktohost(addr), width);
2019 * nntohostp() is the same as nntohost() plus a :port suffix
2029 if (!showhostnames || SOCK_UNSPEC(netnum))
2030 return sptoa(netnum);
2031 else if (ISREFCLOCKADR(netnum))
2032 return refnumtoa(netnum);
2034 hostn = socktohost(netnum);
2036 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
2042 * rtdatetolfp - decode an RT-11 date into an l_fp
2052 struct calendar cal;
2058 * An RT-11 date looks like:
2060 * d[d]-Mth-y[y] hh:mm:ss
2062 * (No docs, but assume 4-digit years are also legal...)
2064 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
2067 if (!isdigit(pgetc(cp))) {
2070 * Catch special case
2078 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
2079 if (isdigit(pgetc(cp))) {
2080 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
2081 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
2087 for (i = 0; i < 3; i++)
2091 for (i = 0; i < 12; i++)
2092 if (STREQ(buf, months[i]))
2096 cal.month = (u_char)(i + 1);
2101 if (!isdigit(pgetc(cp)))
2103 cal.year = (u_short)(*cp++ - '0');
2104 if (isdigit(pgetc(cp))) {
2105 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2106 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)(cal.year + *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');
2118 * Catch special case. If cal.year == 0 this is a zero timestamp.
2120 if (cal.year == 0) {
2125 if (*cp++ != ' ' || !isdigit(pgetc(cp)))
2127 cal.hour = (u_char)(*cp++ - '0');
2128 if (isdigit(pgetc(cp))) {
2129 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2130 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2133 if (*cp++ != ':' || !isdigit(pgetc(cp)))
2135 cal.minute = (u_char)(*cp++ - '0');
2136 if (isdigit(pgetc(cp))) {
2137 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2138 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2141 if (*cp++ != ':' || !isdigit(pgetc(cp)))
2143 cal.second = (u_char)(*cp++ - '0');
2144 if (isdigit(pgetc(cp))) {
2145 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2146 cal.second = (u_char)(cal.second + *cp++ - '0');
2150 * For RT-11, 1972 seems to be the pivot year
2157 lfp->l_ui = caltontp(&cal);
2164 * decodets - decode a timestamp into an l_fp format number, with
2165 * consideration of fuzzball formats.
2178 * If it starts with a 0x, decode as hex.
2180 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2181 return hextolfp(str+2, lfp);
2184 * If it starts with a '"', try it as an RT-11 date.
2189 while ('"' != *cp && '\0' != *cp &&
2190 b < COUNTOF(buf) - 1)
2193 return rtdatetolfp(buf, lfp);
2197 * Might still be hex. Check out the first character. Talk
2200 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2201 return hextolfp(str, lfp);
2204 * Try it as a decimal. If this fails, try as an unquoted
2205 * RT-11 date. This code should go away eventually.
2207 if (atolfp(str, lfp))
2210 return rtdatetolfp(str, lfp);
2215 * decodetime - decode a time value. It should be in milliseconds
2223 return mstolfp(str, lfp);
2228 * decodeint - decode an integer
2237 if (*(str+1) == 'x' || *(str+1) == 'X')
2238 return hextoint(str+2, (u_long *)val);
2239 return octtoint(str, (u_long *)val);
2241 return atoint(str, val);
2246 * decodeuint - decode an unsigned integer
2255 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2256 return (hextoint(str + 2, val));
2257 return (octtoint(str, val));
2259 return (atouint(str, val));
2264 * decodearr - decode an array of time values
2279 while (*narr < amax && *cp) {
2280 if (isspace(pgetc(cp))) {
2283 while (*cp && isspace(pgetc(cp)));
2287 if (bp != (buf + sizeof(buf) - 1))
2290 } while (*cp && !isspace(pgetc(cp)));
2293 if (!decodetime(buf, lfpa))
2304 * Finally, the built in command handlers
2308 * help - tell about commands, or details of a particular command
2316 struct xcmd *xcp = NULL; /* quiet warning */
2318 const char *list[100];
2324 if (pcmd->nargs == 0) {
2326 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2327 if (*(xcp->keyword) != '?' &&
2328 words < COUNTOF(list))
2329 list[words++] = xcp->keyword;
2331 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2332 if (words < COUNTOF(list))
2333 list[words++] = xcp->keyword;
2335 qsort((void *)list, words, sizeof(list[0]), helpsort);
2337 for (word = 0; word < words; word++) {
2338 length = strlen(list[word]);
2339 col = max(col, length);
2342 cols = SCREENWIDTH / ++col;
2343 rows = (words + cols - 1) / cols;
2345 fprintf(fp, "ntpq commands:\n");
2347 for (row = 0; row < rows; row++) {
2348 for (word = row; word < words; word += rows)
2349 fprintf(fp, "%-*.*s", (int)col,
2350 (int)col - 1, list[word]);
2354 cmd = pcmd->argval[0].string;
2355 words = findcmd(cmd, builtins, opcmds, &xcp);
2358 "Command `%s' is unknown\n", cmd);
2360 } else if (words >= 2) {
2362 "Command `%s' is ambiguous\n", cmd);
2365 fprintf(fp, "function: %s\n", xcp->comment);
2366 printusage(xcp, fp);
2372 * helpsort - do hostname qsort comparisons
2380 const char * const * name1 = t1;
2381 const char * const * name2 = t2;
2383 return strcmp(*name1, *name2);
2388 * printusage - print usage information for a command
2398 /* XXX: Do we need to warn about extra args here too? */
2400 (void) fprintf(fp, "usage: %s", xcp->keyword);
2401 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2402 if (xcp->arg[i] & OPT)
2403 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2405 (void) fprintf(fp, " %s", xcp->desc[i]);
2407 (void) fprintf(fp, "\n");
2412 * timeout - set time out time
2422 if (pcmd->nargs == 0) {
2423 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2424 (void) fprintf(fp, "primary timeout %d ms\n", val);
2426 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2427 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2434 * auth_delay - set delay for auth requests
2445 if (pcmd->nargs == 0) {
2446 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2447 (void) fprintf(fp, "delay %lu ms\n", val);
2449 if (pcmd->argval[0].ival < 0) {
2451 val = (u_long)(-pcmd->argval[0].ival);
2454 val = (u_long)pcmd->argval[0].ival;
2457 delay_time.l_ui = val / 1000;
2459 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2468 * host - set the host we are dealing with.
2478 if (pcmd->nargs == 0) {
2480 (void) fprintf(fp, "current host is %s\n",
2483 (void) fprintf(fp, "no current host\n");
2488 ai_fam_templ = ai_fam_default;
2489 if (pcmd->nargs == 2) {
2490 if (!strcmp("-4", pcmd->argval[i].string))
2491 ai_fam_templ = AF_INET;
2492 else if (!strcmp("-6", pcmd->argval[i].string))
2493 ai_fam_templ = AF_INET6;
2498 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2499 fprintf(fp, "current host set to %s\n", currenthost);
2503 fprintf(fp, "current host remains %s\n",
2506 fprintf(fp, "still no current host\n");
2512 * poll - do one (or more) polls of the host via NTP
2521 (void) fprintf(fp, "poll not implemented yet\n");
2526 * showdrefid2str - return a string explanation of the value of drefid
2529 showdrefid2str(void)
2543 * drefid - display/change "display hash"
2551 if (pcmd->nargs == 0) {
2552 (void) fprintf(fp, "drefid value is %s\n", showdrefid2str());
2554 } else if (STREQ(pcmd->argval[0].string, "hash")) {
2555 drefid = REFID_HASH;
2556 } else if (STREQ(pcmd->argval[0].string, "ipv4")) {
2557 drefid = REFID_IPV4;
2559 (void) fprintf(fp, "What?\n");
2562 (void) fprintf(fp, "drefid value set to %s\n", showdrefid2str());
2567 * keyid - get a keyid to use for authenticating requests
2575 if (pcmd->nargs == 0) {
2576 if (info_auth_keyid == 0)
2577 (void) fprintf(fp, "no keyid defined\n");
2579 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2581 /* allow zero so that keyid can be cleared. */
2582 if(pcmd->argval[0].uval > NTP_MAXKEY)
2583 (void) fprintf(fp, "Invalid key identifier\n");
2584 info_auth_keyid = pcmd->argval[0].uval;
2589 * keytype - get type of key to use for authenticating requests
2597 const char * digest_name;
2602 fprintf(fp, "keytype is %s with %lu octet digests\n",
2603 keytype_name(info_auth_keytype),
2604 (u_long)info_auth_hashlen);
2608 digest_name = pcmd->argval[0].string;
2610 key_type = keytype_from_text(digest_name, &digest_len);
2613 fprintf(fp, "keytype is not valid. "
2615 "Type \"help keytype\" for the available digest types.\n");
2617 "Only \"md5\" is available.\n");
2622 info_auth_keytype = key_type;
2623 info_auth_hashlen = digest_len;
2628 * passwd - get an authentication key
2639 if (info_auth_keyid == 0) {
2640 info_auth_keyid = getkeyid("Keyid: ");
2641 if (info_auth_keyid == 0) {
2642 (void)fprintf(fp, "Keyid must be defined\n");
2646 if (pcmd->nargs >= 1)
2647 pass = pcmd->argval[0].string;
2649 pass = getpass_keytype(info_auth_keytype);
2650 if ('\0' == pass[0]) {
2651 fprintf(fp, "Password unchanged\n");
2655 authusekey(info_auth_keyid, info_auth_keytype,
2656 (const u_char *)pass);
2657 authtrust(info_auth_keyid, 1);
2662 * hostnames - set the showhostnames flag
2670 if (pcmd->nargs == 0) {
2672 (void) fprintf(fp, "hostnames being shown\n");
2674 (void) fprintf(fp, "hostnames not being shown\n");
2676 if (STREQ(pcmd->argval[0].string, "yes"))
2678 else if (STREQ(pcmd->argval[0].string, "no"))
2681 (void)fprintf(stderr, "What?\n");
2688 * setdebug - set/change debugging level
2696 if (pcmd->nargs == 0) {
2697 (void) fprintf(fp, "debug level is %d\n", debug);
2699 } else if (STREQ(pcmd->argval[0].string, "no")) {
2701 } else if (STREQ(pcmd->argval[0].string, "more")) {
2703 } else if (STREQ(pcmd->argval[0].string, "less")) {
2706 (void) fprintf(fp, "What?\n");
2709 (void) fprintf(fp, "debug level set to %d\n", debug);
2714 * quit - stop this nonsense
2724 closesocket(sockfd); /* cleanliness next to godliness */
2730 * version - print the current version number
2740 (void) fprintf(fp, "%s\n", Version);
2746 * raw - set raw mode output
2756 (void) fprintf(fp, "Output set to raw\n");
2761 * cooked - set cooked mode output
2771 (void) fprintf(fp, "Output set to cooked\n");
2777 * authenticate - always authenticate requests to this host
2785 if (pcmd->nargs == 0) {
2788 "authenticated requests being sent\n");
2791 "unauthenticated requests being sent\n");
2793 if (STREQ(pcmd->argval[0].string, "yes")) {
2795 } else if (STREQ(pcmd->argval[0].string, "no")) {
2798 (void)fprintf(stderr, "What?\n");
2804 * ntpversion - choose the NTP version to use
2812 if (pcmd->nargs == 0) {
2814 "NTP version being claimed is %d\n", pktversion);
2816 if (pcmd->argval[0].uval < NTP_OLDVERSION
2817 || pcmd->argval[0].uval > NTP_VERSION) {
2818 (void) fprintf(stderr, "versions %d to %d, please\n",
2819 NTP_OLDVERSION, NTP_VERSION);
2821 pktversion = (u_char) pcmd->argval[0].uval;
2827 static void __attribute__((__format__(__printf__, 1, 0)))
2828 vwarning(const char *fmt, va_list ap)
2831 (void) fprintf(stderr, "%s: ", progname);
2832 vfprintf(stderr, fmt, ap);
2833 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2837 * warning - print a warning message
2839 static void __attribute__((__format__(__printf__, 1, 2)))
2853 * error - print a message and exit
2855 static void __attribute__((__format__(__printf__, 1, 2)))
2868 * getkeyid - prompt the user for a keyid to use
2872 const char *keyprompt
2882 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2884 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2885 #endif /* SYS_WINNT */
2888 setbuf(fi, (char *)NULL);
2889 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2890 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2891 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2893 pbuf[i++] = (char)c;
2898 return (u_long) atoi(pbuf);
2903 * atoascii - printable-ize possibly ascii data using the character
2904 * transformations cat -v uses.
2914 const u_char * pchIn;
2915 const u_char * pchInLimit;
2919 pchIn = (const u_char *)in;
2920 pchInLimit = pchIn + in_octets;
2921 pchOut = (u_char *)out;
2923 if (NULL == pchIn) {
2931 if (0 == --out_octets) { \
2938 for ( ; pchIn < pchInLimit; pchIn++) {
2949 ONEOUT((u_char)(c + '@'));
2950 } else if (0x7f == c) {
2963 * makeascii - print possibly ascii data using the character
2964 * transformations that cat -v uses.
2973 const u_char *data_u_char;
2977 data_u_char = (const u_char *)data;
2979 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2990 } else if (0x7f == c) {
3000 * asciize - same thing as makeascii except add a newline
3009 makeascii(length, data, fp);
3015 * truncate string to fit clipping excess at end.
3016 * "too long" -> "too l"
3017 * Used for hostnames.
3030 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
3032 memcpy(out, src, width);
3043 * truncate string to fit by preserving right side and using '_' to hint
3044 * "too long" -> "_long"
3045 * Used for local IPv6 addresses, where low bits differentiate.
3058 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
3061 memcpy(&out[1], &src[sl + 1 - width], width);
3071 * Some circular buffer space
3076 char circ_buf[NUMCB][CBLEN];
3079 /* --------------------------------------------------------------------
3080 * Parsing a response value list
3082 * This sounds simple (and it actually is not really hard) but it has
3085 * Rule1: CR/LF is never embedded in an item
3086 * Rule2: An item is a name, optionally followed by a value
3087 * Rule3: The value is separated from the name by a '='
3088 * Rule4: Items are separated by a ','
3089 * Rule5: values can be quoted by '"', in which case they can contain
3090 * arbitrary characters but *not* '"', CR and LF
3092 * There are a few implementations out there that require a somewhat
3093 * relaxed attitude when parsing a value list, especially since we want
3094 * to copy names and values into local buffers. If these would overflow,
3095 * the item should be skipped without terminating the parsing sequence.
3097 * Also, for empty values, there might be a '=' after the name or not;
3098 * we treat that equivalent.
3100 * Parsing an item definitely breaks on a CR/LF. If an item is not
3101 * followed by a comma (','), parsing stops. In the middle of a quoted
3102 * character sequence CR/LF terminates the parsing finally without
3103 * returning a value.
3105 * White space and other noise is ignored when parsing the data buffer;
3106 * only CR, LF, ',', '=' and '"' are characters with a special meaning.
3107 * White space is stripped from the names and values *after* working
3108 * through the buffer, before making the local copies. If whitespace
3109 * stripping results in an empty name, parsing resumes.
3113 * nextvar parsing helpers
3116 /* predicate: allowed chars inside a quoted string */
3117 static int/*BOOL*/ cp_qschar(int ch)
3119 return ch && (ch != '"' && ch != '\r' && ch != '\n');
3122 /* predicate: allowed chars inside an unquoted string */
3123 static int/*BOOL*/ cp_uqchar(int ch)
3125 return ch && (ch != ',' && ch != '"' && ch != '\r' && ch != '\n');
3128 /* predicate: allowed chars inside a value name */
3129 static int/*BOOL*/ cp_namechar(int ch)
3131 return ch && (ch != ',' && ch != '=' && ch != '\r' && ch != '\n');
3134 /* predicate: characters *between* list items. We're relaxed here. */
3135 static int/*BOOL*/ cp_ivspace(int ch)
3137 return (ch == ',' || (ch > 0 && ch <= ' '));
3140 /* get current character (or NUL when on end) */
3143 const char ** datap,
3147 return (*datap != endp)
3148 ? *(const unsigned char*)*datap
3152 /* get next character (or NUL when on end) */
3155 const char ** datap,
3159 return (*datap != endp && ++(*datap) != endp)
3160 ? *(const unsigned char*)*datap
3166 const char ** datap,
3170 static const char empty[] = "";
3172 if (*datap && len) {
3173 const char * cpl = *datap;
3174 const char * cpr = cpl + len;
3176 while (cpl != cpr && *(const unsigned char*)cpl <= ' ')
3178 while (cpl != cpr && *(const unsigned char*)(cpr - 1) <= ' ')
3181 len = (size_t)(cpr - cpl);
3196 # ifndef BUILD_AS_LIB
3198 FILE * ofp = (debug > 0) ? stdout : stderr;
3199 size_t len = (size_t)(whend - where);
3201 if (len > 50) /* *must* fit into an 'int'! */
3203 fprintf(ofp, "nextvar: %s: '%.*s'\n",
3204 what, (int)len, where);
3206 # else /*defined(BUILD_AS_LIB)*/
3212 # endif /*defined(BUILD_AS_LIB)*/
3216 * nextvar - find the next variable in the buffer
3226 enum PState { sDone, sInit, sName, sValU, sValQ };
3228 static char name[MAXVARLEN], value[MAXVALLEN];
3230 const char *cp, *cpend;
3231 const char *np, *vp;
3236 cpend = *datap + *datalen;
3243 ch = pf_getch(datap, cpend);
3245 while (st != sDone) {
3248 case sInit: /* handle inter-item chars */
3249 while (cp_ivspace(ch))
3250 ch = pf_nextch(datap, cpend);
3251 if (cp_namechar(ch)) {
3255 ch = pf_nextch(datap, cpend);
3261 case sName: /* collect name */
3262 while (cp_namechar(ch))
3263 ch = pf_nextch(datap, cpend);
3264 nlen = (size_t)(*datap - np);
3266 ch = pf_nextch(datap, cpend);
3276 case sValU: /* collect unquoted part(s) of value */
3277 while (cp_uqchar(ch))
3278 ch = pf_nextch(datap, cpend);
3280 ch = pf_nextch(datap, cpend);
3283 vlen = (size_t)(*datap - vp);
3290 case sValQ: /* collect quoted part(s) of value */
3291 while (cp_qschar(ch))
3292 ch = pf_nextch(datap, cpend);
3294 ch = pf_nextch(datap, cpend);
3297 pf_error("no closing quote, stop", cp, cpend);
3303 pf_error("state machine error, stop", *datap, cpend);
3308 /* If name or value do not fit their buffer, croak and start
3309 * over. If there's no name at all after whitespace stripping,
3312 nlen = str_strip(&np, nlen);
3313 vlen = str_strip(&vp, vlen);
3318 if (nlen >= sizeof(name)) {
3319 pf_error("runaway name", np, cpend);
3322 if (vlen >= sizeof(value)) {
3323 pf_error("runaway value", vp, cpend);
3327 /* copy name and value into NUL-terminated buffers */
3328 memcpy(name, np, nlen);
3332 memcpy(value, vp, vlen);
3336 /* check if there's more to do or if we are finshed */
3337 *datalen = (size_t)(cpend - *datap);
3348 varfmt(const char * varname)
3352 for (n = 0; n < COUNTOF(cookedvars); n++)
3353 if (!strcmp(varname, cookedvars[n].varname))
3354 return cookedvars[n].fmt;
3361 * printvars - print variables returned in response packet
3374 rawprint(sttype, length, data, status, quiet, fp);
3376 cookedprint(sttype, length, data, status, quiet, fp);
3381 * rawprint - do a printout of the data in raw mode
3397 * Essentially print the data as is. We reformat unprintables, though.
3400 cpend = data + length;
3403 (void) fprintf(fp, "status=0x%04x,\n", status);
3405 while (cp < cpend) {
3408 * If this is a \r and the next character is a
3409 * \n, supress this, else pretty print it. Otherwise
3410 * just output the character.
3412 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3413 makeascii(1, cp, fp);
3414 } else if (isspace(pgetc(cp)) || isprint(pgetc(cp)))
3417 makeascii(1, cp, fp);
3424 * Global data used by the cooked output routines
3426 int out_chars; /* number of characters output */
3427 int out_linecount; /* number of characters output on this line */
3431 * startoutput - get ready to do cooked output
3442 * output - output a variable=value combination
3453 /* strlen of "name=value" */
3454 len = size2int_sat(strlen(name) + 1 + strlen(value));
3456 if (out_chars != 0) {
3458 if ((out_linecount + len + 2) > MAXOUTLINE) {
3471 out_linecount += len;
3476 * endoutput - terminate a block of cooked output
3489 * outputarr - output an array of values
3507 * Hack to align delay and offset values
3509 for (i = (int)strlen(name); i < 11; i++)
3512 for (i = narr; i > 0; i--) {
3513 if (i != (size_t)narr)
3515 cp = lfptoms(lfp, 2);
3530 output(fp, name, buf);
3539 # error BLEN is too small -- increase!
3546 s = cp = circ_buf[nextcb];
3547 if (++nextcb >= NUMCB)
3549 cb = sizeof(circ_buf[0]);
3551 l = snprintf(cp, cb, "%02lx", val);
3552 if (l < 0 || (size_t)l >= cb)
3557 l = strlcat(cp, " ok", cb);
3558 if ((size_t)l >= cb)
3566 for (i = 0; i < COUNTOF(tstflagnames); i++) {
3568 l = snprintf(cp, cb, "%s%s", sep,
3572 if ((size_t)l >= cb) {
3575 l = strlcpy (cp, "...", cb);
3596 * cookedprint - output variables in cooked mode
3619 char bn[2 * MAXVARLEN];
3620 char bv[2 * MAXVALLEN];
3622 UNUSED_ARG(datatype);
3625 fprintf(fp, "status=%04x %s,\n", status,
3626 statustoa(datatype, status));
3629 while (nextvar(&length, &data, &name, &value)) {
3639 if (!value || !decodets(value, &lfp))
3642 output(fp, name, prettydate(&lfp));
3645 case HA: /* fallthru */
3647 if (!value || !decodenetnum(value, &hval)) {
3649 } else if (fmt == HA){
3650 output(fp, name, nntohost(&hval));
3652 output(fp, name, stoa(&hval));
3659 } else if (decodenetnum(value, &hval)) {
3660 if (ISREFCLOCKADR(&hval))
3664 output(fp, name, stoa(&hval));
3665 } else if (strlen(value) <= 4) {
3666 output(fp, name, value);
3673 if (!value || !decodeuint(value, &uval) || uval > 3) {
3683 output(fp, name, b);
3688 if (!value || !decodeuint(value, &uval)) {
3691 snprintf(b, sizeof(b), "%03lo", uval);
3692 output(fp, name, b);
3697 if (!value || !decodearr(value, &narr, lfparr, 8))
3700 outputarr(fp, name, narr, lfparr);
3704 if (!value || !decodeuint(value, &uval))
3707 output(fp, name, tstflags(uval));
3711 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3717 if (output_raw != 0) {
3718 /* TALOS-CAN-0063: avoid buffer overrun */
3719 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3720 if (output_raw != '*') {
3721 atoascii(value, MAXVALLEN,
3722 bv, sizeof(bv) - 1);
3724 bv[len] = output_raw;
3727 atoascii(value, MAXVALLEN,
3738 * sortassoc - sort associations in the cache into ascending order
3744 qsort(assoc_cache, (size_t)numassoc,
3745 sizeof(assoc_cache[0]), &assoccmp);
3750 * assoccmp - compare two associations
3758 const struct association *ass1 = t1;
3759 const struct association *ass2 = t2;
3761 if (ass1->assid < ass2->assid)
3763 if (ass1->assid > ass2->assid)
3770 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3772 * The strategy is to add an assumed 4k page size at a time, leaving
3773 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3776 grow_assoc_cache(void)
3778 static size_t prior_sz;
3781 new_sz = prior_sz + 4 * 1024;
3782 if (0 == prior_sz) {
3783 new_sz -= 4 * sizeof(void *);
3785 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3787 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3792 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3794 * By default, autoopts loses the relative order of -c and -p options
3795 * on the command line. This routine replaces the default handler for
3796 * those routines and builds a list of commands to execute preserving
3800 ntpq_custom_opt_handler(
3805 switch (pOptDesc->optValue) {
3809 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3810 pOptDesc->optValue, pOptDesc->optValue);
3814 ADDCMD(pOptDesc->pzLastArg);
3823 * Obtain list of digest names
3826 #if defined(OPENSSL) && !defined(HAVE_EVP_MD_DO_ALL_SORTED)
3827 # if defined(_MSC_VER) && OPENSSL_VERSION_NUMBER >= 0x10100000L
3828 # define HAVE_EVP_MD_DO_ALL_SORTED
3833 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3834 # define K_PER_LINE 8
3835 # define K_NL_PFX_STR "\n "
3836 # define K_DELIM_STR ", "
3845 # ifndef BUILD_AS_LIB
3847 list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg)
3850 const char *name, **seen;
3851 struct hstate *hstate = arg;
3854 /* m is MD obj, from is name or alias, to is base name for alias */
3855 if (!m || !from || to)
3856 return; /* Ignore aliases */
3858 /* Discard MACs that NTP won't accept. */
3859 /* Keep this consistent with keytype_from_text() in ssl_init.c. */
3860 if (EVP_MD_size(m) > (MAX_MAC_LEN - sizeof(keyid_t)))
3863 name = EVP_MD_name(m);
3865 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3867 for (cp = name; *cp; cp++)
3868 if (islower((unsigned char)*cp))
3871 len = (cp - name) + 1;
3873 /* There are duplicates. Discard if name has been seen. */
3875 for (seen = hstate->seen; *seen; seen++)
3876 if (!strcmp(*seen, name))
3879 n = (seen - hstate->seen) + 2;
3880 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3881 hstate->seen[n-2] = name;
3882 hstate->seen[n-1] = NULL;
3884 if (hstate->list != NULL)
3885 len += strlen(hstate->list);
3887 len += (hstate->idx >= K_PER_LINE)
3888 ? strlen(K_NL_PFX_STR)
3889 : strlen(K_DELIM_STR);
3891 if (hstate->list == NULL) {
3892 hstate->list = (char *)emalloc(len);
3893 hstate->list[0] = '\0';
3895 hstate->list = (char *)erealloc(hstate->list, len);
3898 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3899 ((hstate->idx >= K_PER_LINE) ? K_NL_PFX_STR : K_DELIM_STR),
3902 if (hstate->idx >= K_PER_LINE)
3907 # endif /* !defined(BUILD_AS_LIB) */
3909 # ifndef BUILD_AS_LIB
3910 /* Insert CMAC into SSL digests list */
3912 insert_cmac(char *list)
3919 /* If list empty, we need to insert CMAC on new line */
3920 insert = (!list || !*list);
3923 len = strlen(K_NL_PFX_STR) + strlen(CMAC);
3924 list = (char *)erealloc(list, len + 1);
3925 sprintf(list, "%s%s", K_NL_PFX_STR, CMAC);
3926 } else { /* List not empty */
3927 /* Check if CMAC already in list - future proofing */
3928 const char *cmac_sn;
3931 cmac_sn = OBJ_nid2sn(NID_cmac);
3933 insert = cmac_sn != NULL && *cmac_sn != '\0';
3935 /* CMAC in list if found, followed by nul char or ',' */
3936 while (insert && NULL != (cmac_p = strstr(cmac_p, cmac_sn))) {
3937 cmac_p += strlen(cmac_sn);
3938 /* Still need to insert if not nul and not ',' */
3939 insert = *cmac_p && ',' != *cmac_p;
3942 /* Find proper insertion point */
3949 /* Default to start if list empty */
3954 /* While new lines */
3955 while (delim < list + len && *delim &&
3956 !strncmp(K_NL_PFX_STR, delim, strlen(K_NL_PFX_STR))) {
3957 point = delim + strlen(K_NL_PFX_STR);
3959 /* While digest names on line */
3960 while (point < list + len && *point) {
3961 /* Another digest after on same or next line? */
3962 delim = strstr( point, K_DELIM_STR);
3963 last_nl = strstr( point, K_NL_PFX_STR);
3965 /* No - end of list */
3966 if (!delim && !last_nl) {
3969 /* New line and no delim or before delim? */
3970 if (last_nl && (!delim || last_nl < delim)) {
3974 /* Found insertion point where CMAC before entry? */
3975 if (strncmp(CMAC, point, delim - point) < 0) {
3980 if (delim < list + len && *delim &&
3981 !strncmp(K_DELIM_STR, delim, strlen(K_DELIM_STR))) {
3982 point += strlen(K_DELIM_STR);
3986 } /* While digest names on line */
3987 } /* While new lines */
3989 /* If found in list */
3991 /* insert cmac and delim */
3992 /* Space for list could move - save offset */
3993 ptrdiff_t p_offset = point - list;
3994 len += strlen(CMAC) + strlen(K_DELIM_STR);
3995 list = (char *)erealloc(list, len + 1);
3996 point = list + p_offset;
3997 /* move to handle src/dest overlap */
3998 memmove(point + strlen(CMAC) + strlen(K_DELIM_STR),
3999 point, strlen(point) + 1);
4000 strncpy(point, CMAC, strlen(CMAC));
4001 strncpy(point + strlen(CMAC), K_DELIM_STR, strlen(K_DELIM_STR));
4002 } else { /* End of list */
4003 /* append delim and cmac */
4004 len += strlen(K_DELIM_STR) + strlen(CMAC);
4005 list = (char *)erealloc(list, len + 1);
4006 strcpy(list + strlen(list), K_DELIM_STR);
4007 strcpy(list + strlen(list), CMAC);
4010 } /* List not empty */
4011 #endif /*ENABLE_CMAC*/
4014 # endif /* !defined(BUILD_AS_LIB) */
4019 #ifndef BUILD_AS_LIB
4021 list_digest_names(void)
4026 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
4027 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
4029 /* replace calloc(1, sizeof(const char *)) */
4030 hstate.seen = (const char **)emalloc_zero(sizeof(const char *));
4033 EVP_MD_do_all_sorted(list_md_fn, &hstate);
4037 list = insert_cmac(list); /* Insert CMAC into SSL digests list */
4040 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
4041 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
4044 list = (char *)emalloc(sizeof("md5"));
4045 strcpy(list, "md5");
4050 #endif /* !defined(BUILD_AS_LIB) */
4052 #define CTRLC_STACK_MAX 4
4053 static volatile size_t ctrlc_stack_len = 0;
4054 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
4059 push_ctrl_c_handler(
4063 size_t size = ctrlc_stack_len;
4064 if (func && (size < CTRLC_STACK_MAX)) {
4065 ctrlc_stack[size] = func;
4066 ctrlc_stack_len = size + 1;
4077 size_t size = ctrlc_stack_len;
4080 if (func == NULL || func == ctrlc_stack[size]) {
4081 ctrlc_stack_len = size;
4088 #ifndef BUILD_AS_LIB
4092 size_t size = ctrlc_stack_len;
4094 if ((*ctrlc_stack[--size])())
4097 #endif /* !defined(BUILD_AS_LIB) */
4099 #ifndef BUILD_AS_LIB
4110 char * buf = emalloc(len);
4113 /* Note: we expect the memory allocation to fail long before the
4114 * increment in buffer size actually overflows.
4116 buf = (buf) ? erealloc(buf, len) : emalloc(len);
4119 prc = vsnprintf(buf, len, fmt, va);
4123 /* might be very old vsnprintf. Or actually MSVC... */
4127 if ((size_t)prc >= len) {
4128 /* at least we have the proper size now... */
4129 len = (size_t)prc + 1;
4132 if ((size_t)prc < (len - 32))
4133 buf = erealloc(buf, (size_t)prc + 1);
4137 #endif /* !defined(BUILD_AS_LIB) */