ntpq.c revision 1.14 1 /* $NetBSD: ntpq.c,v 1.14 2016/01/08 21:35:40 christos Exp $ */
2
3 /*
4 * ntpq - query an NTP server using mode 6 commands
5 */
6 #include <config.h>
7 #include <stdio.h>
8 #include <ctype.h>
9 #include <signal.h>
10 #include <setjmp.h>
11 #include <sys/types.h>
12 #include <sys/time.h>
13 #ifdef HAVE_UNISTD_H
14 # include <unistd.h>
15 #endif
16 #ifdef HAVE_FCNTL_H
17 # include <fcntl.h>
18 #endif
19 #ifdef SYS_WINNT
20 # include <mswsock.h>
21 #endif
22 #include <isc/net.h>
23 #include <isc/result.h>
24
25 #include "ntpq.h"
26 #include "ntp_assert.h"
27 #include "ntp_stdlib.h"
28 #include "ntp_unixtime.h"
29 #include "ntp_calendar.h"
30 #include "ntp_select.h"
31 #include "ntp_assert.h"
32 #include "lib_strbuf.h"
33 #include "ntp_lineedit.h"
34 #include "ntp_debug.h"
35 #ifdef OPENSSL
36 #include "openssl/evp.h"
37 #include "openssl/objects.h"
38 #include "openssl/err.h"
39 #endif
40 #include <ssl_applink.c>
41
42 #include "ntp_libopts.h"
43 #include "ntpq-opts.h"
44 #include "safecast.h"
45
46 #ifdef SYS_VXWORKS /* vxWorks needs mode flag -casey*/
47 # define open(name, flags) open(name, flags, 0777)
48 # define SERVER_PORT_NUM 123
49 #endif
50
51 /* we use COMMAND as an autogen keyword */
52 #ifdef COMMAND
53 # undef COMMAND
54 #endif
55
56 /*
57 * Because we potentially understand a lot of commands we will run
58 * interactive if connected to a terminal.
59 */
60 int interactive = 0; /* set to 1 when we should prompt */
61 const char *prompt = "ntpq> "; /* prompt to ask him about */
62
63 /*
64 * use old readvars behavior? --old-rv processing in ntpq resets
65 * this value based on the presence or absence of --old-rv. It is
66 * initialized to 1 here to maintain backward compatibility with
67 * libntpq clients such as ntpsnmpd, which are free to reset it as
68 * desired.
69 */
70 int old_rv = 1;
71
72
73 /*
74 * for get_systime()
75 */
76 s_char sys_precision; /* local clock precision (log2 s) */
77
78 /*
79 * Keyid used for authenticated requests. Obtained on the fly.
80 */
81 u_long info_auth_keyid = 0;
82
83 static int info_auth_keytype = NID_md5; /* MD5 */
84 static size_t info_auth_hashlen = 16; /* MD5 */
85 u_long current_time; /* needed by authkeys; not used */
86
87 /*
88 * Flag which indicates we should always send authenticated requests
89 */
90 int always_auth = 0;
91
92 /*
93 * Flag which indicates raw mode output.
94 */
95 int rawmode = 0;
96
97 /*
98 * Packet version number we use
99 */
100 u_char pktversion = NTP_OLDVERSION + 1;
101
102 /*
103 * Don't jump if no set jmp.
104 */
105 volatile int jump = 0;
106
107 /*
108 * Format values
109 */
110 #define PADDING 0
111 #define HA 1 /* host address */
112 #define NA 2 /* network address */
113 #define LP 3 /* leap (print in binary) */
114 #define RF 4 /* refid (sometimes string, sometimes not) */
115 #define AR 5 /* array of times */
116 #define FX 6 /* test flags */
117 #define TS 7 /* l_fp timestamp in hex */
118 #define OC 8 /* integer, print in octal */
119 #define EOV 255 /* end of table */
120
121 /*
122 * For the most part ntpq simply displays what ntpd provides in the
123 * mostly plain-text mode 6 responses. A few variable names are by
124 * default "cooked" to provide more human-friendly output.
125 */
126 const var_format cookedvars[] = {
127 { "leap", LP },
128 { "reach", OC },
129 { "refid", RF },
130 { "reftime", TS },
131 { "clock", TS },
132 { "org", TS },
133 { "rec", TS },
134 { "xmt", TS },
135 { "flash", FX },
136 { "srcadr", HA },
137 { "peeradr", HA }, /* compat with others */
138 { "dstadr", NA },
139 { "filtdelay", AR },
140 { "filtoffset", AR },
141 { "filtdisp", AR },
142 { "filterror", AR }, /* compat with others */
143 };
144
145
146
147 /*
148 * flasher bits
149 */
150 static const char *tstflagnames[] = {
151 "pkt_dup", /* TEST1 */
152 "pkt_bogus", /* TEST2 */
153 "pkt_unsync", /* TEST3 */
154 "pkt_denied", /* TEST4 */
155 "pkt_auth", /* TEST5 */
156 "pkt_stratum", /* TEST6 */
157 "pkt_header", /* TEST7 */
158 "pkt_autokey", /* TEST8 */
159 "pkt_crypto", /* TEST9 */
160 "peer_stratum", /* TEST10 */
161 "peer_dist", /* TEST11 */
162 "peer_loop", /* TEST12 */
163 "peer_unreach" /* TEST13 */
164 };
165
166
167 int ntpqmain (int, char **);
168 /*
169 * Built in command handler declarations
170 */
171 static int openhost (const char *, int);
172 static void dump_hex_printable(const void *, size_t);
173 static int sendpkt (void *, size_t);
174 static int getresponse (int, int, u_short *, size_t *, const char **, int);
175 static int sendrequest (int, associd_t, int, size_t, const char *);
176 static char * tstflags (u_long);
177 #ifndef BUILD_AS_LIB
178 static void getcmds (void);
179 #ifndef SYS_WINNT
180 static int abortcmd (void);
181 #endif /* SYS_WINNT */
182 static void docmd (const char *);
183 static void tokenize (const char *, char **, int *);
184 static int getarg (const char *, int, arg_v *);
185 #endif /* BUILD_AS_LIB */
186 static int findcmd (const char *, struct xcmd *,
187 struct xcmd *, struct xcmd **);
188 static int rtdatetolfp (char *, l_fp *);
189 static int decodearr (char *, int *, l_fp *);
190 static void help (struct parse *, FILE *);
191 static int helpsort (const void *, const void *);
192 static void printusage (struct xcmd *, FILE *);
193 static void timeout (struct parse *, FILE *);
194 static void auth_delay (struct parse *, FILE *);
195 static void host (struct parse *, FILE *);
196 static void ntp_poll (struct parse *, FILE *);
197 static void keyid (struct parse *, FILE *);
198 static void keytype (struct parse *, FILE *);
199 static void passwd (struct parse *, FILE *);
200 static void hostnames (struct parse *, FILE *);
201 static void setdebug (struct parse *, FILE *);
202 static void quit (struct parse *, FILE *);
203 static void version (struct parse *, FILE *);
204 static void raw (struct parse *, FILE *);
205 static void cooked (struct parse *, FILE *);
206 static void authenticate (struct parse *, FILE *);
207 static void ntpversion (struct parse *, FILE *);
208 static void warning (const char *, ...)
209 __attribute__((__format__(__printf__, 1, 2)));
210 static void error (const char *, ...)
211 __attribute__((__format__(__printf__, 1, 2)));
212 static u_long getkeyid (const char *);
213 static void atoascii (const char *, size_t, char *, size_t);
214 static void cookedprint (int, size_t, const char *, int, int, FILE *);
215 static void rawprint (int, size_t, const char *, int, int, FILE *);
216 static void startoutput (void);
217 static void output (FILE *, const char *, const char *);
218 static void endoutput (FILE *);
219 static void outputarr (FILE *, char *, int, l_fp *);
220 static int assoccmp (const void *, const void *);
221 static void on_ctrlc (void);
222 u_short varfmt (const char *);
223
224 void ntpq_custom_opt_handler (tOptions *, tOptDesc *);
225
226 #ifdef OPENSSL
227 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
228 static void list_md_fn(const EVP_MD *m, const char *from,
229 const char *to, void *arg );
230 # endif
231 #endif
232 static char *list_digest_names(void);
233
234 /*
235 * Built-in commands we understand
236 */
237 struct xcmd builtins[] = {
238 { "?", help, { OPT|NTP_STR, NO, NO, NO },
239 { "command", "", "", "" },
240 "tell the use and syntax of commands" },
241 { "help", help, { OPT|NTP_STR, NO, NO, NO },
242 { "command", "", "", "" },
243 "tell the use and syntax of commands" },
244 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO },
245 { "msec", "", "", "" },
246 "set the primary receive time out" },
247 { "delay", auth_delay, { OPT|NTP_INT, NO, NO, NO },
248 { "msec", "", "", "" },
249 "set the delay added to encryption time stamps" },
250 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO },
251 { "-4|-6", "hostname", "", "" },
252 "specify the host whose NTP server we talk to" },
253 { "poll", ntp_poll, { OPT|NTP_UINT, OPT|NTP_STR, NO, NO },
254 { "n", "verbose", "", "" },
255 "poll an NTP server in client mode `n' times" },
256 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO },
257 { "", "", "", "" },
258 "specify a password to use for authenticated requests"},
259 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO },
260 { "yes|no", "", "", "" },
261 "specify whether hostnames or net numbers are printed"},
262 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO },
263 { "no|more|less", "", "", "" },
264 "set/change debugging level" },
265 { "quit", quit, { NO, NO, NO, NO },
266 { "", "", "", "" },
267 "exit ntpq" },
268 { "exit", quit, { NO, NO, NO, NO },
269 { "", "", "", "" },
270 "exit ntpq" },
271 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO },
272 { "key#", "", "", "" },
273 "set keyid to use for authenticated requests" },
274 { "version", version, { NO, NO, NO, NO },
275 { "", "", "", "" },
276 "print version number" },
277 { "raw", raw, { NO, NO, NO, NO },
278 { "", "", "", "" },
279 "do raw mode variable output" },
280 { "cooked", cooked, { NO, NO, NO, NO },
281 { "", "", "", "" },
282 "do cooked mode variable output" },
283 { "authenticate", authenticate, { OPT|NTP_STR, NO, NO, NO },
284 { "yes|no", "", "", "" },
285 "always authenticate requests to this server" },
286 { "ntpversion", ntpversion, { OPT|NTP_UINT, NO, NO, NO },
287 { "version number", "", "", "" },
288 "set the NTP version number to use for requests" },
289 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO },
290 { "key type %s", "", "", "" },
291 NULL },
292 { 0, 0, { NO, NO, NO, NO },
293 { "", "", "", "" }, "" }
294 };
295
296
297 /*
298 * Default values we use.
299 */
300 #define DEFHOST "localhost" /* default host name */
301 #define DEFTIMEOUT 5 /* wait 5 seconds for 1st pkt */
302 #define DEFSTIMEOUT 3 /* and 3 more for each additional */
303 /*
304 * Requests are automatically retried once, so total timeout with no
305 * response is a bit over 2 * DEFTIMEOUT, or 10 seconds. At the other
306 * extreme, a request eliciting 32 packets of responses each for some
307 * reason nearly DEFSTIMEOUT seconds after the prior in that series,
308 * with a single packet dropped, would take around 32 * DEFSTIMEOUT, or
309 * 93 seconds to fail each of two times, or 186 seconds.
310 * Some commands involve a series of requests, such as "peers" and
311 * "mrulist", so the cumulative timeouts are even longer for those.
312 */
313 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */
314 #define LENHOSTNAME 256 /* host name is 256 characters long */
315 #define MAXCMDS 100 /* maximum commands on cmd line */
316 #define MAXHOSTS 200 /* maximum hosts on cmd line */
317 #define MAXLINE 512 /* maximum line length */
318 #define MAXTOKENS (1+MAXARGS+2) /* maximum number of usable tokens */
319 #define MAXVARLEN 256 /* maximum length of a variable name */
320 #define MAXVALLEN 2048 /* maximum length of a variable value */
321 #define MAXOUTLINE 72 /* maximum length of an output line */
322 #define SCREENWIDTH 76 /* nominal screen width in columns */
323
324 /*
325 * Some variables used and manipulated locally
326 */
327 struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */
328 struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */
329 l_fp delay_time; /* delay time */
330 char currenthost[LENHOSTNAME]; /* current host name */
331 int currenthostisnum; /* is prior text from IP? */
332 struct sockaddr_in hostaddr; /* host address */
333 int showhostnames = 1; /* show host names by default */
334 int wideremote = 0; /* show wide remote names? */
335
336 int ai_fam_templ; /* address family */
337 int ai_fam_default; /* default address family */
338 SOCKET sockfd; /* fd socket is opened on */
339 int havehost = 0; /* set to 1 when host open */
340 int s_port = 0;
341 struct servent *server_entry = NULL; /* server entry for ntp */
342
343
344 /*
345 * Sequence number used for requests. It is incremented before
346 * it is used.
347 */
348 u_short sequence;
349
350 /*
351 * Holds data returned from queries. Declare buffer long to be sure of
352 * alignment.
353 */
354 #define DATASIZE (MAXFRAGS*480) /* maximum amount of data */
355 long pktdata[DATASIZE/sizeof(long)];
356
357 /*
358 * assoc_cache[] is a dynamic array which allows references to
359 * associations using &1 ... &N for n associations, avoiding manual
360 * lookup of the current association IDs for a given ntpd. It also
361 * caches the status word for each association, retrieved incidentally.
362 */
363 struct association * assoc_cache;
364 u_int assoc_cache_slots;/* count of allocated array entries */
365 u_int numassoc; /* number of cached associations */
366
367 /*
368 * For commands typed on the command line (with the -c option)
369 */
370 size_t numcmds = 0;
371 const char *ccmds[MAXCMDS];
372 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp)
373
374 /*
375 * When multiple hosts are specified.
376 */
377
378 u_int numhosts;
379
380 chost chosts[MAXHOSTS];
381 #define ADDHOST(cp) \
382 do { \
383 if (numhosts < MAXHOSTS) { \
384 chosts[numhosts].name = (cp); \
385 chosts[numhosts].fam = ai_fam_templ; \
386 numhosts++; \
387 } \
388 } while (0)
389
390 /*
391 * Macro definitions we use
392 */
393 #define ISSPACE(c) ((c) == ' ' || (c) == '\t')
394 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0')
395 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0)
396
397 /*
398 * Jump buffer for longjumping back to the command level
399 */
400 jmp_buf interrupt_buf;
401
402 /*
403 * Points at file being currently printed into
404 */
405 FILE *current_output;
406
407 /*
408 * Command table imported from ntpdc_ops.c
409 */
410 extern struct xcmd opcmds[];
411
412 char const *progname;
413
414 #ifdef NO_MAIN_ALLOWED
415 #ifndef BUILD_AS_LIB
416 CALL(ntpq,"ntpq",ntpqmain);
417
418 void clear_globals(void)
419 {
420 extern int ntp_optind;
421 showhostnames = 0; /* don'tshow host names by default */
422 ntp_optind = 0;
423 server_entry = NULL; /* server entry for ntp */
424 havehost = 0; /* set to 1 when host open */
425 numassoc = 0; /* number of cached associations */
426 numcmds = 0;
427 numhosts = 0;
428 }
429 #endif /* !BUILD_AS_LIB */
430 #endif /* NO_MAIN_ALLOWED */
431
432 /*
433 * main - parse arguments and handle options
434 */
435 #ifndef NO_MAIN_ALLOWED
436 int
437 main(
438 int argc,
439 char *argv[]
440 )
441 {
442 return ntpqmain(argc, argv);
443 }
444 #endif
445
446 #ifndef BUILD_AS_LIB
447 int
448 ntpqmain(
449 int argc,
450 char *argv[]
451 )
452 {
453 u_int ihost;
454 size_t icmd;
455
456
457 #ifdef SYS_VXWORKS
458 clear_globals();
459 taskPrioritySet(taskIdSelf(), 100 );
460 #endif
461
462 delay_time.l_ui = 0;
463 delay_time.l_uf = DEFDELAY;
464
465 init_lib(); /* sets up ipv4_works, ipv6_works */
466 ssl_applink();
467 init_auth();
468
469 /* Check to see if we have IPv6. Otherwise default to IPv4 */
470 if (!ipv6_works)
471 ai_fam_default = AF_INET;
472
473 /* Fixup keytype's help based on available digest names */
474
475 {
476 char *list;
477 char *msg;
478 const char *fmt;
479
480 list = list_digest_names();
481 for (icmd = 0; icmd < sizeof(builtins)/sizeof(builtins[0]); icmd++) {
482 if (strcmp("keytype", builtins[icmd].keyword) == 0)
483 break;
484 }
485
486 /* CID: 1295478 */
487 /* This should only "trip" if "keytype" is removed from builtins */
488 INSIST(icmd < sizeof(builtins)/sizeof(builtins[0]));
489
490 #ifdef OPENSSL
491 builtins[icmd].desc[0] = "digest-name";
492 fmt = ", one of:";
493 #else
494 builtins[icmd].desc[0] = "md5";
495 fmt = ":";
496 #endif
497 asprintf(&msg,
498 "set key type to use for authenticated requests%s %s", fmt,
499 list);
500 builtins[icmd].comment = msg;
501 free(list);
502 }
503
504 progname = argv[0];
505
506 {
507 int optct = ntpOptionProcess(&ntpqOptions, argc, argv);
508 argc -= optct;
509 argv += optct;
510 }
511
512 /*
513 * Process options other than -c and -p, which are specially
514 * handled by ntpq_custom_opt_handler().
515 */
516
517 debug = OPT_VALUE_SET_DEBUG_LEVEL;
518
519 if (HAVE_OPT(IPV4))
520 ai_fam_templ = AF_INET;
521 else if (HAVE_OPT(IPV6))
522 ai_fam_templ = AF_INET6;
523 else
524 ai_fam_templ = ai_fam_default;
525
526 if (HAVE_OPT(INTERACTIVE))
527 interactive = 1;
528
529 if (HAVE_OPT(NUMERIC))
530 showhostnames = 0;
531
532 if (HAVE_OPT(WIDE))
533 wideremote = 1;
534
535 old_rv = HAVE_OPT(OLD_RV);
536
537 if (0 == argc) {
538 ADDHOST(DEFHOST);
539 } else {
540 for (ihost = 0; ihost < (u_int)argc; ihost++) {
541 if ('-' == *argv[ihost]) {
542 //
543 // If I really cared I'd also check:
544 // 0 == argv[ihost][2]
545 //
546 // and there are other cases as well...
547 //
548 if ('4' == argv[ihost][1]) {
549 ai_fam_templ = AF_INET;
550 continue;
551 } else if ('6' == argv[ihost][1]) {
552 ai_fam_templ = AF_INET6;
553 continue;
554 } else {
555 // XXX Throw a usage error
556 }
557 }
558 ADDHOST(argv[ihost]);
559 }
560 }
561
562 if (numcmds == 0 && interactive == 0
563 && isatty(fileno(stdin)) && isatty(fileno(stderr))) {
564 interactive = 1;
565 }
566
567 set_ctrl_c_hook(on_ctrlc);
568 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */
569 if (interactive)
570 push_ctrl_c_handler(abortcmd);
571 #endif /* SYS_WINNT */
572
573 if (numcmds == 0) {
574 (void) openhost(chosts[0].name, chosts[0].fam);
575 getcmds();
576 } else {
577 for (ihost = 0; ihost < numhosts; ihost++) {
578 if (openhost(chosts[ihost].name, chosts[ihost].fam))
579 for (icmd = 0; icmd < numcmds; icmd++)
580 docmd(ccmds[icmd]);
581 }
582 }
583 #ifdef SYS_WINNT
584 WSACleanup();
585 #endif /* SYS_WINNT */
586 return 0;
587 }
588 #endif /* !BUILD_AS_LIB */
589
590 /*
591 * openhost - open a socket to a host
592 */
593 static int
594 openhost(
595 const char *hname,
596 int fam
597 )
598 {
599 const char svc[] = "ntp";
600 char temphost[LENHOSTNAME];
601 int a_info, i;
602 struct addrinfo hints, *ai;
603 sockaddr_u addr;
604 size_t octets;
605 register const char *cp;
606 char name[LENHOSTNAME];
607
608 /*
609 * We need to get by the [] if they were entered
610 */
611
612 cp = hname;
613
614 if (*cp == '[') {
615 cp++;
616 for (i = 0; *cp && *cp != ']'; cp++, i++)
617 name[i] = *cp;
618 if (*cp == ']') {
619 name[i] = '\0';
620 hname = name;
621 } else {
622 return 0;
623 }
624 }
625
626 /*
627 * First try to resolve it as an ip address and if that fails,
628 * do a fullblown (dns) lookup. That way we only use the dns
629 * when it is needed and work around some implementations that
630 * will return an "IPv4-mapped IPv6 address" address if you
631 * give it an IPv4 address to lookup.
632 */
633 ZERO(hints);
634 hints.ai_family = fam;
635 hints.ai_protocol = IPPROTO_UDP;
636 hints.ai_socktype = SOCK_DGRAM;
637 hints.ai_flags = Z_AI_NUMERICHOST;
638 ai = NULL;
639
640 a_info = getaddrinfo(hname, svc, &hints, &ai);
641 if (a_info == EAI_NONAME
642 #ifdef EAI_NODATA
643 || a_info == EAI_NODATA
644 #endif
645 ) {
646 hints.ai_flags = AI_CANONNAME;
647 #ifdef AI_ADDRCONFIG
648 hints.ai_flags |= AI_ADDRCONFIG;
649 #endif
650 a_info = getaddrinfo(hname, svc, &hints, &ai);
651 }
652 #ifdef AI_ADDRCONFIG
653 /* Some older implementations don't like AI_ADDRCONFIG. */
654 if (a_info == EAI_BADFLAGS) {
655 hints.ai_flags &= ~AI_ADDRCONFIG;
656 a_info = getaddrinfo(hname, svc, &hints, &ai);
657 }
658 #endif
659 if (a_info != 0) {
660 fprintf(stderr, "%s\n", gai_strerror(a_info));
661 return 0;
662 }
663
664 INSIST(ai != NULL);
665 ZERO(addr);
666 octets = min(sizeof(addr), ai->ai_addrlen);
667 memcpy(&addr, ai->ai_addr, octets);
668
669 if (ai->ai_canonname == NULL) {
670 strlcpy(temphost, stoa(&addr), sizeof(temphost));
671 currenthostisnum = TRUE;
672 } else {
673 strlcpy(temphost, ai->ai_canonname, sizeof(temphost));
674 currenthostisnum = FALSE;
675 }
676
677 if (debug > 2)
678 printf("Opening host %s (%s)\n",
679 temphost,
680 (ai->ai_family == AF_INET)
681 ? "AF_INET"
682 : (ai->ai_family == AF_INET6)
683 ? "AF_INET6"
684 : "AF-???"
685 );
686
687 if (havehost == 1) {
688 if (debug > 2)
689 printf("Closing old host %s\n", currenthost);
690 closesocket(sockfd);
691 havehost = 0;
692 }
693 strlcpy(currenthost, temphost, sizeof(currenthost));
694
695 /* port maps to the same location in both families */
696 s_port = NSRCPORT(&addr);
697 #ifdef SYS_VXWORKS
698 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM);
699 if (ai->ai_family == AF_INET)
700 *(struct sockaddr_in *)&hostaddr=
701 *((struct sockaddr_in *)ai->ai_addr);
702 else
703 *(struct sockaddr_in6 *)&hostaddr=
704 *((struct sockaddr_in6 *)ai->ai_addr);
705 #endif /* SYS_VXWORKS */
706
707 #ifdef SYS_WINNT
708 {
709 int optionValue = SO_SYNCHRONOUS_NONALERT;
710 int err;
711
712 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE,
713 (char *)&optionValue, sizeof(optionValue));
714 if (err) {
715 mfprintf(stderr,
716 "setsockopt(SO_SYNCHRONOUS_NONALERT)"
717 " error: %m\n");
718 freeaddrinfo(ai);
719 exit(1);
720 }
721 }
722 #endif /* SYS_WINNT */
723
724 sockfd = socket(ai->ai_family, ai->ai_socktype,
725 ai->ai_protocol);
726 if (sockfd == INVALID_SOCKET) {
727 error("socket");
728 freeaddrinfo(ai);
729 return 0;
730 }
731
732
733 #ifdef NEED_RCVBUF_SLOP
734 # ifdef SO_RCVBUF
735 { int rbufsize = DATASIZE + 2048; /* 2K for slop */
736 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF,
737 &rbufsize, sizeof(int)) == -1)
738 error("setsockopt");
739 }
740 # endif
741 #endif
742
743 if
744 #ifdef SYS_VXWORKS
745 (connect(sockfd, (struct sockaddr *)&hostaddr,
746 sizeof(hostaddr)) == -1)
747 #else
748 (connect(sockfd, (struct sockaddr *)ai->ai_addr,
749 ai->ai_addrlen) == -1)
750 #endif /* SYS_VXWORKS */
751 {
752 error("connect");
753 freeaddrinfo(ai);
754 return 0;
755 }
756 freeaddrinfo(ai);
757 havehost = 1;
758 numassoc = 0;
759
760 return 1;
761 }
762
763
764 static void
765 dump_hex_printable(
766 const void * data,
767 size_t len
768 )
769 {
770 const char * cdata;
771 const char * rowstart;
772 size_t idx;
773 size_t rowlen;
774 u_char uch;
775
776 cdata = data;
777 while (len > 0) {
778 rowstart = cdata;
779 rowlen = min(16, len);
780 for (idx = 0; idx < rowlen; idx++) {
781 uch = *(cdata++);
782 printf("%02x ", uch);
783 }
784 for ( ; idx < 16 ; idx++)
785 printf(" ");
786 cdata = rowstart;
787 for (idx = 0; idx < rowlen; idx++) {
788 uch = *(cdata++);
789 printf("%c", (isprint(uch))
790 ? uch
791 : '.');
792 }
793 printf("\n");
794 len -= rowlen;
795 }
796 }
797
798
799 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */
800 /*
801 * sendpkt - send a packet to the remote host
802 */
803 static int
804 sendpkt(
805 void * xdata,
806 size_t xdatalen
807 )
808 {
809 if (debug >= 3)
810 printf("Sending %zu octets\n", xdatalen);
811
812 if (send(sockfd, xdata, xdatalen, 0) == -1) {
813 warning("write to %s failed", currenthost);
814 return -1;
815 }
816
817 if (debug >= 4) {
818 printf("Request packet:\n");
819 dump_hex_printable(xdata, xdatalen);
820 }
821 return 0;
822 }
823
824 /*
825 * getresponse - get a (series of) response packet(s) and return the data
826 */
827 static int
828 getresponse(
829 int opcode,
830 int associd,
831 u_short *rstatus,
832 size_t *rsize,
833 const char **rdata,
834 int timeo
835 )
836 {
837 struct ntp_control rpkt;
838 struct sock_timeval tvo;
839 u_short offsets[MAXFRAGS+1];
840 u_short counts[MAXFRAGS+1];
841 u_short offset;
842 u_short count;
843 size_t numfrags;
844 size_t f;
845 size_t ff;
846 int seenlastfrag;
847 int shouldbesize;
848 fd_set fds;
849 int n;
850 int errcode;
851
852 /*
853 * This is pretty tricky. We may get between 1 and MAXFRAG packets
854 * back in response to the request. We peel the data out of
855 * each packet and collect it in one long block. When the last
856 * packet in the sequence is received we'll know how much data we
857 * should have had. Note we use one long time out, should reconsider.
858 */
859 *rsize = 0;
860 if (rstatus)
861 *rstatus = 0;
862 *rdata = (char *)pktdata;
863
864 numfrags = 0;
865 seenlastfrag = 0;
866
867 FD_ZERO(&fds);
868
869 /*
870 * Loop until we have an error or a complete response. Nearly all
871 * code paths to loop again use continue.
872 */
873 for (;;) {
874
875 if (numfrags == 0)
876 tvo = tvout;
877 else
878 tvo = tvsout;
879
880 FD_SET(sockfd, &fds);
881 n = select(sockfd+1, &fds, NULL, NULL, &tvo);
882 if (n == -1) {
883 warning("select fails");
884 return -1;
885 }
886 if (n == 0) {
887 /*
888 * Timed out. Return what we have
889 */
890 if (numfrags == 0) {
891 if (timeo)
892 fprintf(stderr,
893 "%s: timed out, nothing received\n",
894 currenthost);
895 return ERR_TIMEOUT;
896 }
897 if (timeo)
898 fprintf(stderr,
899 "%s: timed out with incomplete data\n",
900 currenthost);
901 if (debug) {
902 fprintf(stderr,
903 "ERR_INCOMPLETE: Received fragments:\n");
904 for (f = 0; f < numfrags; f++)
905 fprintf(stderr,
906 "%2u: %5d %5d\t%3d octets\n",
907 (u_int)f, offsets[f],
908 offsets[f] +
909 counts[f],
910 counts[f]);
911 fprintf(stderr,
912 "last fragment %sreceived\n",
913 (seenlastfrag)
914 ? ""
915 : "not ");
916 }
917 return ERR_INCOMPLETE;
918 }
919
920 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0);
921 if (n == -1) {
922 warning("read");
923 return -1;
924 }
925
926 if (debug >= 4) {
927 printf("Response packet:\n");
928 dump_hex_printable(&rpkt, n);
929 }
930
931 /*
932 * Check for format errors. Bug proofing.
933 */
934 if (n < (int)CTL_HEADER_LEN) {
935 if (debug)
936 printf("Short (%d byte) packet received\n", n);
937 continue;
938 }
939 if (PKT_VERSION(rpkt.li_vn_mode) > NTP_VERSION
940 || PKT_VERSION(rpkt.li_vn_mode) < NTP_OLDVERSION) {
941 if (debug)
942 printf("Packet received with version %d\n",
943 PKT_VERSION(rpkt.li_vn_mode));
944 continue;
945 }
946 if (PKT_MODE(rpkt.li_vn_mode) != MODE_CONTROL) {
947 if (debug)
948 printf("Packet received with mode %d\n",
949 PKT_MODE(rpkt.li_vn_mode));
950 continue;
951 }
952 if (!CTL_ISRESPONSE(rpkt.r_m_e_op)) {
953 if (debug)
954 printf("Received request packet, wanted response\n");
955 continue;
956 }
957
958 /*
959 * Check opcode and sequence number for a match.
960 * Could be old data getting to us.
961 */
962 if (ntohs(rpkt.sequence) != sequence) {
963 if (debug)
964 printf("Received sequnce number %d, wanted %d\n",
965 ntohs(rpkt.sequence), sequence);
966 continue;
967 }
968 if (CTL_OP(rpkt.r_m_e_op) != opcode) {
969 if (debug)
970 printf(
971 "Received opcode %d, wanted %d (sequence number okay)\n",
972 CTL_OP(rpkt.r_m_e_op), opcode);
973 continue;
974 }
975
976 /*
977 * Check the error code. If non-zero, return it.
978 */
979 if (CTL_ISERROR(rpkt.r_m_e_op)) {
980 errcode = (ntohs(rpkt.status) >> 8) & 0xff;
981 if (CTL_ISMORE(rpkt.r_m_e_op))
982 TRACE(1, ("Error code %d received on not-final packet\n",
983 errcode));
984 if (errcode == CERR_UNSPEC)
985 return ERR_UNSPEC;
986 return errcode;
987 }
988
989 /*
990 * Check the association ID to make sure it matches what
991 * we sent.
992 */
993 if (ntohs(rpkt.associd) != associd) {
994 TRACE(1, ("Association ID %d doesn't match expected %d\n",
995 ntohs(rpkt.associd), associd));
996 /*
997 * Hack for silly fuzzballs which, at the time of writing,
998 * return an assID of sys.peer when queried for system variables.
999 */
1000 #ifdef notdef
1001 continue;
1002 #endif
1003 }
1004
1005 /*
1006 * Collect offset and count. Make sure they make sense.
1007 */
1008 offset = ntohs(rpkt.offset);
1009 count = ntohs(rpkt.count);
1010
1011 /*
1012 * validate received payload size is padded to next 32-bit
1013 * boundary and no smaller than claimed by rpkt.count
1014 */
1015 if (n & 0x3) {
1016 TRACE(1, ("Response packet not padded, size = %d\n",
1017 n));
1018 continue;
1019 }
1020
1021 shouldbesize = (CTL_HEADER_LEN + count + 3) & ~3;
1022
1023 if (n < shouldbesize) {
1024 printf("Response packet claims %u octets payload, above %ld received\n",
1025 count, (long)n - CTL_HEADER_LEN);
1026 return ERR_INCOMPLETE;
1027 }
1028
1029 if (debug >= 3 && shouldbesize > n) {
1030 u_int32 key;
1031 u_int32 *lpkt;
1032 int maclen;
1033
1034 /*
1035 * Usually we ignore authentication, but for debugging purposes
1036 * we watch it here.
1037 */
1038 /* round to 8 octet boundary */
1039 shouldbesize = (shouldbesize + 7) & ~7;
1040
1041 maclen = n - shouldbesize;
1042 if (maclen >= (int)MIN_MAC_LEN) {
1043 printf(
1044 "Packet shows signs of authentication (total %d, data %d, mac %d)\n",
1045 n, shouldbesize, maclen);
1046 lpkt = (u_int32 *)&rpkt;
1047 printf("%08lx %08lx %08lx %08lx %08lx %08lx\n",
1048 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 3]),
1049 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 2]),
1050 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) - 1]),
1051 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32)]),
1052 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 1]),
1053 (u_long)ntohl(lpkt[(n - maclen)/sizeof(u_int32) + 2]));
1054 key = ntohl(lpkt[(n - maclen) / sizeof(u_int32)]);
1055 printf("Authenticated with keyid %lu\n", (u_long)key);
1056 if (key != 0 && key != info_auth_keyid) {
1057 printf("We don't know that key\n");
1058 } else {
1059 if (authdecrypt(key, (u_int32 *)&rpkt,
1060 n - maclen, maclen)) {
1061 printf("Auth okay!\n");
1062 } else {
1063 printf("Auth failed!\n");
1064 }
1065 }
1066 }
1067 }
1068
1069 TRACE(2, ("Got packet, size = %d\n", n));
1070 if (count > (n - CTL_HEADER_LEN)) {
1071 TRACE(1, ("Received count of %u octets, data in packet is %ld\n",
1072 count, (long)n - CTL_HEADER_LEN));
1073 continue;
1074 }
1075 if (count == 0 && CTL_ISMORE(rpkt.r_m_e_op)) {
1076 TRACE(1, ("Received count of 0 in non-final fragment\n"));
1077 continue;
1078 }
1079 if (offset + count > sizeof(pktdata)) {
1080 TRACE(1, ("Offset %u, count %u, too big for buffer\n",
1081 offset, count));
1082 return ERR_TOOMUCH;
1083 }
1084 if (seenlastfrag && !CTL_ISMORE(rpkt.r_m_e_op)) {
1085 TRACE(1, ("Received second last fragment packet\n"));
1086 continue;
1087 }
1088
1089 /*
1090 * So far, so good. Record this fragment, making sure it doesn't
1091 * overlap anything.
1092 */
1093 TRACE(2, ("Packet okay\n"));
1094
1095 if (numfrags > (MAXFRAGS - 1)) {
1096 TRACE(2, ("Number of fragments exceeds maximum %d\n",
1097 MAXFRAGS - 1));
1098 return ERR_TOOMUCH;
1099 }
1100
1101 /*
1102 * Find the position for the fragment relative to any
1103 * previously received.
1104 */
1105 for (f = 0;
1106 f < numfrags && offsets[f] < offset;
1107 f++) {
1108 /* empty body */ ;
1109 }
1110
1111 if (f < numfrags && offset == offsets[f]) {
1112 TRACE(1, ("duplicate %u octets at %u ignored, prior %u at %u\n",
1113 count, offset, counts[f], offsets[f]));
1114 continue;
1115 }
1116
1117 if (f > 0 && (offsets[f-1] + counts[f-1]) > offset) {
1118 TRACE(1, ("received frag at %u overlaps with %u octet frag at %u\n",
1119 offset, counts[f-1], offsets[f-1]));
1120 continue;
1121 }
1122
1123 if (f < numfrags && (offset + count) > offsets[f]) {
1124 TRACE(1, ("received %u octet frag at %u overlaps with frag at %u\n",
1125 count, offset, offsets[f]));
1126 continue;
1127 }
1128
1129 for (ff = numfrags; ff > f; ff--) {
1130 offsets[ff] = offsets[ff-1];
1131 counts[ff] = counts[ff-1];
1132 }
1133 offsets[f] = offset;
1134 counts[f] = count;
1135 numfrags++;
1136
1137 /*
1138 * Got that stuffed in right. Figure out if this was the last.
1139 * Record status info out of the last packet.
1140 */
1141 if (!CTL_ISMORE(rpkt.r_m_e_op)) {
1142 seenlastfrag = 1;
1143 if (rstatus != 0)
1144 *rstatus = ntohs(rpkt.status);
1145 }
1146
1147 /*
1148 * Copy the data into the data buffer.
1149 */
1150 memcpy((char *)pktdata + offset, &rpkt.u, count);
1151
1152 /*
1153 * If we've seen the last fragment, look for holes in the sequence.
1154 * If there aren't any, we're done.
1155 */
1156 if (seenlastfrag && offsets[0] == 0) {
1157 for (f = 1; f < numfrags; f++)
1158 if (offsets[f-1] + counts[f-1] !=
1159 offsets[f])
1160 break;
1161 if (f == numfrags) {
1162 *rsize = offsets[f-1] + counts[f-1];
1163 TRACE(1, ("%lu packets reassembled into response\n",
1164 (u_long)numfrags));
1165 return 0;
1166 }
1167 }
1168 } /* giant for (;;) collecting response packets */
1169 } /* getresponse() */
1170
1171
1172 /*
1173 * sendrequest - format and send a request packet
1174 */
1175 static int
1176 sendrequest(
1177 int opcode,
1178 associd_t associd,
1179 int auth,
1180 size_t qsize,
1181 const char *qdata
1182 )
1183 {
1184 struct ntp_control qpkt;
1185 size_t pktsize;
1186 u_long key_id;
1187 char * pass;
1188 size_t maclen;
1189
1190 /*
1191 * Check to make sure the data will fit in one packet
1192 */
1193 if (qsize > CTL_MAX_DATA_LEN) {
1194 fprintf(stderr,
1195 "***Internal error! qsize (%zu) too large\n",
1196 qsize);
1197 return 1;
1198 }
1199
1200 /*
1201 * Fill in the packet
1202 */
1203 qpkt.li_vn_mode = PKT_LI_VN_MODE(0, pktversion, MODE_CONTROL);
1204 qpkt.r_m_e_op = (u_char)(opcode & CTL_OP_MASK);
1205 qpkt.sequence = htons(sequence);
1206 qpkt.status = 0;
1207 qpkt.associd = htons((u_short)associd);
1208 qpkt.offset = 0;
1209 qpkt.count = htons((u_short)qsize);
1210
1211 pktsize = CTL_HEADER_LEN;
1212
1213 /*
1214 * If we have data, copy and pad it out to a 32-bit boundary.
1215 */
1216 if (qsize > 0) {
1217 memcpy(&qpkt.u, qdata, (size_t)qsize);
1218 pktsize += qsize;
1219 while (pktsize & (sizeof(u_int32) - 1)) {
1220 qpkt.u.data[qsize++] = 0;
1221 pktsize++;
1222 }
1223 }
1224
1225 /*
1226 * If it isn't authenticated we can just send it. Otherwise
1227 * we're going to have to think about it a little.
1228 */
1229 if (!auth && !always_auth) {
1230 return sendpkt(&qpkt, pktsize);
1231 }
1232
1233 /*
1234 * Pad out packet to a multiple of 8 octets to be sure
1235 * receiver can handle it.
1236 */
1237 while (pktsize & 7) {
1238 qpkt.u.data[qsize++] = 0;
1239 pktsize++;
1240 }
1241
1242 /*
1243 * Get the keyid and the password if we don't have one.
1244 */
1245 if (info_auth_keyid == 0) {
1246 key_id = getkeyid("Keyid: ");
1247 if (key_id == 0 || key_id > NTP_MAXKEY) {
1248 fprintf(stderr,
1249 "Invalid key identifier\n");
1250 return 1;
1251 }
1252 info_auth_keyid = key_id;
1253 }
1254 if (!authistrusted(info_auth_keyid)) {
1255 pass = getpass_keytype(info_auth_keytype);
1256 if ('\0' == pass[0]) {
1257 fprintf(stderr, "Invalid password\n");
1258 return 1;
1259 }
1260 authusekey(info_auth_keyid, info_auth_keytype,
1261 (u_char *)pass);
1262 authtrust(info_auth_keyid, 1);
1263 }
1264
1265 /*
1266 * Do the encryption.
1267 */
1268 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, pktsize);
1269 if (!maclen) {
1270 fprintf(stderr, "Key not found\n");
1271 return 1;
1272 } else if ((size_t)maclen != (info_auth_hashlen + sizeof(keyid_t))) {
1273 fprintf(stderr,
1274 "%zu octet MAC, %zu expected with %zu octet digest\n",
1275 maclen, (info_auth_hashlen + sizeof(keyid_t)),
1276 info_auth_hashlen);
1277 return 1;
1278 }
1279
1280 return sendpkt((char *)&qpkt, pktsize + maclen);
1281 }
1282
1283
1284 /*
1285 * show_error_msg - display the error text for a mode 6 error response.
1286 */
1287 void
1288 show_error_msg(
1289 int m6resp,
1290 associd_t associd
1291 )
1292 {
1293 if (numhosts > 1)
1294 fprintf(stderr, "server=%s ", currenthost);
1295
1296 switch(m6resp) {
1297
1298 case CERR_BADFMT:
1299 fprintf(stderr,
1300 "***Server reports a bad format request packet\n");
1301 break;
1302
1303 case CERR_PERMISSION:
1304 fprintf(stderr,
1305 "***Server disallowed request (authentication?)\n");
1306 break;
1307
1308 case CERR_BADOP:
1309 fprintf(stderr,
1310 "***Server reports a bad opcode in request\n");
1311 break;
1312
1313 case CERR_BADASSOC:
1314 fprintf(stderr,
1315 "***Association ID %d unknown to server\n",
1316 associd);
1317 break;
1318
1319 case CERR_UNKNOWNVAR:
1320 fprintf(stderr,
1321 "***A request variable unknown to the server\n");
1322 break;
1323
1324 case CERR_BADVALUE:
1325 fprintf(stderr,
1326 "***Server indicates a request variable was bad\n");
1327 break;
1328
1329 case ERR_UNSPEC:
1330 fprintf(stderr,
1331 "***Server returned an unspecified error\n");
1332 break;
1333
1334 case ERR_TIMEOUT:
1335 fprintf(stderr, "***Request timed out\n");
1336 break;
1337
1338 case ERR_INCOMPLETE:
1339 fprintf(stderr,
1340 "***Response from server was incomplete\n");
1341 break;
1342
1343 case ERR_TOOMUCH:
1344 fprintf(stderr,
1345 "***Buffer size exceeded for returned data\n");
1346 break;
1347
1348 default:
1349 fprintf(stderr,
1350 "***Server returns unknown error code %d\n",
1351 m6resp);
1352 }
1353 }
1354
1355 /*
1356 * doquery - send a request and process the response, displaying
1357 * error messages for any error responses.
1358 */
1359 int
1360 doquery(
1361 int opcode,
1362 associd_t associd,
1363 int auth,
1364 size_t qsize,
1365 const char *qdata,
1366 u_short *rstatus,
1367 size_t *rsize,
1368 const char **rdata
1369 )
1370 {
1371 return doqueryex(opcode, associd, auth, qsize, qdata, rstatus,
1372 rsize, rdata, FALSE);
1373 }
1374
1375
1376 /*
1377 * doqueryex - send a request and process the response, optionally
1378 * displaying error messages for any error responses.
1379 */
1380 int
1381 doqueryex(
1382 int opcode,
1383 associd_t associd,
1384 int auth,
1385 size_t qsize,
1386 const char *qdata,
1387 u_short *rstatus,
1388 size_t *rsize,
1389 const char **rdata,
1390 int quiet
1391 )
1392 {
1393 int res;
1394 int done;
1395
1396 /*
1397 * Check to make sure host is open
1398 */
1399 if (!havehost) {
1400 fprintf(stderr, "***No host open, use `host' command\n");
1401 return -1;
1402 }
1403
1404 done = 0;
1405 sequence++;
1406
1407 again:
1408 /*
1409 * send a request
1410 */
1411 res = sendrequest(opcode, associd, auth, qsize, qdata);
1412 if (res != 0)
1413 return res;
1414
1415 /*
1416 * Get the response. If we got a standard error, print a message
1417 */
1418 res = getresponse(opcode, associd, rstatus, rsize, rdata, done);
1419
1420 if (res > 0) {
1421 if (!done && (res == ERR_TIMEOUT || res == ERR_INCOMPLETE)) {
1422 if (res == ERR_INCOMPLETE) {
1423 /*
1424 * better bump the sequence so we don't
1425 * get confused about differing fragments.
1426 */
1427 sequence++;
1428 }
1429 done = 1;
1430 goto again;
1431 }
1432 if (!quiet)
1433 show_error_msg(res, associd);
1434
1435 }
1436 return res;
1437 }
1438
1439
1440 #ifndef BUILD_AS_LIB
1441 /*
1442 * getcmds - read commands from the standard input and execute them
1443 */
1444 static void
1445 getcmds(void)
1446 {
1447 char * line;
1448 int count;
1449
1450 ntp_readline_init(interactive ? prompt : NULL);
1451
1452 for (;;) {
1453 line = ntp_readline(&count);
1454 if (NULL == line)
1455 break;
1456 docmd(line);
1457 free(line);
1458 }
1459
1460 ntp_readline_uninit();
1461 }
1462 #endif /* !BUILD_AS_LIB */
1463
1464
1465 #if !defined(SYS_WINNT) && !defined(BUILD_AS_LIB)
1466 /*
1467 * abortcmd - catch interrupts and abort the current command
1468 */
1469 static int
1470 abortcmd(void)
1471 {
1472 if (current_output == stdout)
1473 (void) fflush(stdout);
1474 putc('\n', stderr);
1475 (void) fflush(stderr);
1476 if (jump) {
1477 jump = 0;
1478 longjmp(interrupt_buf, 1);
1479 }
1480 return TRUE;
1481 }
1482 #endif /* !SYS_WINNT && !BUILD_AS_LIB */
1483
1484
1485 #ifndef BUILD_AS_LIB
1486 /*
1487 * docmd - decode the command line and execute a command
1488 */
1489 static void
1490 docmd(
1491 const char *cmdline
1492 )
1493 {
1494 char *tokens[1+MAXARGS+2];
1495 struct parse pcmd;
1496 int ntok;
1497 static int i;
1498 struct xcmd *xcmd;
1499
1500 /*
1501 * Tokenize the command line. If nothing on it, return.
1502 */
1503 tokenize(cmdline, tokens, &ntok);
1504 if (ntok == 0)
1505 return;
1506
1507 /*
1508 * Find the appropriate command description.
1509 */
1510 i = findcmd(tokens[0], builtins, opcmds, &xcmd);
1511 if (i == 0) {
1512 (void) fprintf(stderr, "***Command `%s' unknown\n",
1513 tokens[0]);
1514 return;
1515 } else if (i >= 2) {
1516 (void) fprintf(stderr, "***Command `%s' ambiguous\n",
1517 tokens[0]);
1518 return;
1519 }
1520
1521 /* Warn about ignored extra args */
1522 for (i = MAXARGS + 1; i < ntok ; ++i) {
1523 fprintf(stderr, "***Extra arg `%s' ignored\n", tokens[i]);
1524 }
1525
1526 /*
1527 * Save the keyword, then walk through the arguments, interpreting
1528 * as we go.
1529 */
1530 pcmd.keyword = tokens[0];
1531 pcmd.nargs = 0;
1532 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO; i++) {
1533 if ((i+1) >= ntok) {
1534 if (!(xcmd->arg[i] & OPT)) {
1535 printusage(xcmd, stderr);
1536 return;
1537 }
1538 break;
1539 }
1540 if ((xcmd->arg[i] & OPT) && (*tokens[i+1] == '>'))
1541 break;
1542 if (!getarg(tokens[i+1], (int)xcmd->arg[i], &pcmd.argval[i]))
1543 return;
1544 pcmd.nargs++;
1545 }
1546
1547 i++;
1548 if (i < ntok && *tokens[i] == '>') {
1549 char *fname;
1550
1551 if (*(tokens[i]+1) != '\0')
1552 fname = tokens[i]+1;
1553 else if ((i+1) < ntok)
1554 fname = tokens[i+1];
1555 else {
1556 (void) fprintf(stderr, "***No file for redirect\n");
1557 return;
1558 }
1559
1560 current_output = fopen(fname, "w");
1561 if (current_output == NULL) {
1562 (void) fprintf(stderr, "***Error opening %s: ", fname);
1563 perror("");
1564 return;
1565 }
1566 i = 1; /* flag we need a close */
1567 } else {
1568 current_output = stdout;
1569 i = 0; /* flag no close */
1570 }
1571
1572 if (interactive && setjmp(interrupt_buf)) {
1573 jump = 0;
1574 return;
1575 } else {
1576 jump++;
1577 (xcmd->handler)(&pcmd, current_output);
1578 jump = 0; /* HMS: 961106: was after fclose() */
1579 if (i) (void) fclose(current_output);
1580 }
1581
1582 return;
1583 }
1584
1585
1586 /*
1587 * tokenize - turn a command line into tokens
1588 *
1589 * SK: Modified to allow a quoted string
1590 *
1591 * HMS: If the first character of the first token is a ':' then (after
1592 * eating inter-token whitespace) the 2nd token is the rest of the line.
1593 */
1594
1595 static void
1596 tokenize(
1597 const char *line,
1598 char **tokens,
1599 int *ntok
1600 )
1601 {
1602 register const char *cp;
1603 register char *sp;
1604 static char tspace[MAXLINE];
1605
1606 sp = tspace;
1607 cp = line;
1608 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) {
1609 tokens[*ntok] = sp;
1610
1611 /* Skip inter-token whitespace */
1612 while (ISSPACE(*cp))
1613 cp++;
1614
1615 /* If we're at EOL we're done */
1616 if (ISEOL(*cp))
1617 break;
1618
1619 /* If this is the 2nd token and the first token begins
1620 * with a ':', then just grab to EOL.
1621 */
1622
1623 if (*ntok == 1 && tokens[0][0] == ':') {
1624 do {
1625 if (sp - tspace >= MAXLINE)
1626 goto toobig;
1627 *sp++ = *cp++;
1628 } while (!ISEOL(*cp));
1629 }
1630
1631 /* Check if this token begins with a double quote.
1632 * If yes, continue reading till the next double quote
1633 */
1634 else if (*cp == '\"') {
1635 ++cp;
1636 do {
1637 if (sp - tspace >= MAXLINE)
1638 goto toobig;
1639 *sp++ = *cp++;
1640 } while ((*cp != '\"') && !ISEOL(*cp));
1641 /* HMS: a missing closing " should be an error */
1642 }
1643 else {
1644 do {
1645 if (sp - tspace >= MAXLINE)
1646 goto toobig;
1647 *sp++ = *cp++;
1648 } while ((*cp != '\"') && !ISSPACE(*cp) && !ISEOL(*cp));
1649 /* HMS: Why check for a " in the previous line? */
1650 }
1651
1652 if (sp - tspace >= MAXLINE)
1653 goto toobig;
1654 *sp++ = '\0';
1655 }
1656 return;
1657
1658 toobig:
1659 *ntok = 0;
1660 fprintf(stderr,
1661 "***Line `%s' is too big\n",
1662 line);
1663 return;
1664 }
1665
1666
1667 /*
1668 * getarg - interpret an argument token
1669 */
1670 static int
1671 getarg(
1672 const char *str,
1673 int code,
1674 arg_v *argp
1675 )
1676 {
1677 u_long ul;
1678
1679 switch (code & ~OPT) {
1680 case NTP_STR:
1681 argp->string = str;
1682 break;
1683
1684 case NTP_ADD:
1685 if (!getnetnum(str, &argp->netnum, NULL, 0))
1686 return 0;
1687 break;
1688
1689 case NTP_UINT:
1690 if ('&' == str[0]) {
1691 if (!atouint(&str[1], &ul)) {
1692 fprintf(stderr,
1693 "***Association index `%s' invalid/undecodable\n",
1694 str);
1695 return 0;
1696 }
1697 if (0 == numassoc) {
1698 dogetassoc(stdout);
1699 if (0 == numassoc) {
1700 fprintf(stderr,
1701 "***No associations found, `%s' unknown\n",
1702 str);
1703 return 0;
1704 }
1705 }
1706 ul = min(ul, numassoc);
1707 argp->uval = assoc_cache[ul - 1].assid;
1708 break;
1709 }
1710 if (!atouint(str, &argp->uval)) {
1711 fprintf(stderr, "***Illegal unsigned value %s\n",
1712 str);
1713 return 0;
1714 }
1715 break;
1716
1717 case NTP_INT:
1718 if (!atoint(str, &argp->ival)) {
1719 fprintf(stderr, "***Illegal integer value %s\n",
1720 str);
1721 return 0;
1722 }
1723 break;
1724
1725 case IP_VERSION:
1726 if (!strcmp("-6", str)) {
1727 argp->ival = 6;
1728 } else if (!strcmp("-4", str)) {
1729 argp->ival = 4;
1730 } else {
1731 fprintf(stderr, "***Version must be either 4 or 6\n");
1732 return 0;
1733 }
1734 break;
1735 }
1736
1737 return 1;
1738 }
1739 #endif /* !BUILD_AS_LIB */
1740
1741
1742 /*
1743 * findcmd - find a command in a command description table
1744 */
1745 static int
1746 findcmd(
1747 const char * str,
1748 struct xcmd * clist1,
1749 struct xcmd * clist2,
1750 struct xcmd ** cmd
1751 )
1752 {
1753 struct xcmd *cl;
1754 size_t clen;
1755 int nmatch;
1756 struct xcmd *nearmatch = NULL;
1757 struct xcmd *clist;
1758
1759 clen = strlen(str);
1760 nmatch = 0;
1761 if (clist1 != 0)
1762 clist = clist1;
1763 else if (clist2 != 0)
1764 clist = clist2;
1765 else
1766 return 0;
1767
1768 again:
1769 for (cl = clist; cl->keyword != 0; cl++) {
1770 /* do a first character check, for efficiency */
1771 if (*str != *(cl->keyword))
1772 continue;
1773 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) {
1774 /*
1775 * Could be extact match, could be approximate.
1776 * Is exact if the length of the keyword is the
1777 * same as the str.
1778 */
1779 if (*((cl->keyword) + clen) == '\0') {
1780 *cmd = cl;
1781 return 1;
1782 }
1783 nmatch++;
1784 nearmatch = cl;
1785 }
1786 }
1787
1788 /*
1789 * See if there is more to do. If so, go again. Sorry about the
1790 * goto, too much looking at BSD sources...
1791 */
1792 if (clist == clist1 && clist2 != 0) {
1793 clist = clist2;
1794 goto again;
1795 }
1796
1797 /*
1798 * If we got extactly 1 near match, use it, else return number
1799 * of matches.
1800 */
1801 if (nmatch == 1) {
1802 *cmd = nearmatch;
1803 return 1;
1804 }
1805 return nmatch;
1806 }
1807
1808
1809 /*
1810 * getnetnum - given a host name, return its net number
1811 * and (optional) full name
1812 */
1813 int
1814 getnetnum(
1815 const char *hname,
1816 sockaddr_u *num,
1817 char *fullhost,
1818 int af
1819 )
1820 {
1821 struct addrinfo hints, *ai = NULL;
1822
1823 ZERO(hints);
1824 hints.ai_flags = AI_CANONNAME;
1825 #ifdef AI_ADDRCONFIG
1826 hints.ai_flags |= AI_ADDRCONFIG;
1827 #endif
1828
1829 /*
1830 * decodenetnum only works with addresses, but handles syntax
1831 * that getaddrinfo doesn't: [2001::1]:1234
1832 */
1833 if (decodenetnum(hname, num)) {
1834 if (fullhost != NULL)
1835 getnameinfo(&num->sa, SOCKLEN(num), fullhost,
1836 LENHOSTNAME, NULL, 0, 0);
1837 return 1;
1838 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) {
1839 INSIST(sizeof(*num) >= ai->ai_addrlen);
1840 memcpy(num, ai->ai_addr, ai->ai_addrlen);
1841 if (fullhost != NULL) {
1842 if (ai->ai_canonname != NULL)
1843 strlcpy(fullhost, ai->ai_canonname,
1844 LENHOSTNAME);
1845 else
1846 getnameinfo(&num->sa, SOCKLEN(num),
1847 fullhost, LENHOSTNAME, NULL,
1848 0, 0);
1849 }
1850 freeaddrinfo(ai);
1851 return 1;
1852 }
1853 fprintf(stderr, "***Can't find host %s\n", hname);
1854
1855 return 0;
1856 }
1857
1858
1859 /*
1860 * nntohost - convert network number to host name. This routine enforces
1861 * the showhostnames setting.
1862 */
1863 const char *
1864 nntohost(
1865 sockaddr_u *netnum
1866 )
1867 {
1868 return nntohost_col(netnum, LIB_BUFLENGTH - 1, FALSE);
1869 }
1870
1871
1872 /*
1873 * nntohost_col - convert network number to host name in fixed width.
1874 * This routine enforces the showhostnames setting.
1875 * When displaying hostnames longer than the width,
1876 * the first part of the hostname is displayed. When
1877 * displaying numeric addresses longer than the width,
1878 * Such as IPv6 addresses, the caller decides whether
1879 * the first or last of the numeric address is used.
1880 */
1881 const char *
1882 nntohost_col(
1883 sockaddr_u * addr,
1884 size_t width,
1885 int preserve_lowaddrbits
1886 )
1887 {
1888 const char * out;
1889
1890 if (!showhostnames || SOCK_UNSPEC(addr)) {
1891 if (preserve_lowaddrbits)
1892 out = trunc_left(stoa(addr), width);
1893 else
1894 out = trunc_right(stoa(addr), width);
1895 } else if (ISREFCLOCKADR(addr)) {
1896 out = refnumtoa(addr);
1897 } else {
1898 out = trunc_right(socktohost(addr), width);
1899 }
1900 return out;
1901 }
1902
1903
1904 /*
1905 * nntohostp() is the same as nntohost() plus a :port suffix
1906 */
1907 const char *
1908 nntohostp(
1909 sockaddr_u *netnum
1910 )
1911 {
1912 const char * hostn;
1913 char * buf;
1914
1915 if (!showhostnames || SOCK_UNSPEC(netnum))
1916 return sptoa(netnum);
1917 else if (ISREFCLOCKADR(netnum))
1918 return refnumtoa(netnum);
1919
1920 hostn = socktohost(netnum);
1921 LIB_GETBUF(buf);
1922 snprintf(buf, LIB_BUFLENGTH, "%s:%u", hostn, SRCPORT(netnum));
1923
1924 return buf;
1925 }
1926
1927 /*
1928 * rtdatetolfp - decode an RT-11 date into an l_fp
1929 */
1930 static int
1931 rtdatetolfp(
1932 char *str,
1933 l_fp *lfp
1934 )
1935 {
1936 register char *cp;
1937 register int i;
1938 struct calendar cal;
1939 char buf[4];
1940
1941 cal.yearday = 0;
1942
1943 /*
1944 * An RT-11 date looks like:
1945 *
1946 * d[d]-Mth-y[y] hh:mm:ss
1947 *
1948 * (No docs, but assume 4-digit years are also legal...)
1949 *
1950 * d[d]-Mth-y[y[y[y]]] hh:mm:ss
1951 */
1952 cp = str;
1953 if (!isdigit((int)*cp)) {
1954 if (*cp == '-') {
1955 /*
1956 * Catch special case
1957 */
1958 L_CLR(lfp);
1959 return 1;
1960 }
1961 return 0;
1962 }
1963
1964 cal.monthday = (u_char) (*cp++ - '0'); /* ascii dependent */
1965 if (isdigit((int)*cp)) {
1966 cal.monthday = (u_char)((cal.monthday << 3) + (cal.monthday << 1));
1967 cal.monthday = (u_char)(cal.monthday + *cp++ - '0');
1968 }
1969
1970 if (*cp++ != '-')
1971 return 0;
1972
1973 for (i = 0; i < 3; i++)
1974 buf[i] = *cp++;
1975 buf[3] = '\0';
1976
1977 for (i = 0; i < 12; i++)
1978 if (STREQ(buf, months[i]))
1979 break;
1980 if (i == 12)
1981 return 0;
1982 cal.month = (u_char)(i + 1);
1983
1984 if (*cp++ != '-')
1985 return 0;
1986
1987 if (!isdigit((int)*cp))
1988 return 0;
1989 cal.year = (u_short)(*cp++ - '0');
1990 if (isdigit((int)*cp)) {
1991 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1992 cal.year = (u_short)(*cp++ - '0');
1993 }
1994 if (isdigit((int)*cp)) {
1995 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
1996 cal.year = (u_short)(cal.year + *cp++ - '0');
1997 }
1998 if (isdigit((int)*cp)) {
1999 cal.year = (u_short)((cal.year << 3) + (cal.year << 1));
2000 cal.year = (u_short)(cal.year + *cp++ - '0');
2001 }
2002
2003 /*
2004 * Catch special case. If cal.year == 0 this is a zero timestamp.
2005 */
2006 if (cal.year == 0) {
2007 L_CLR(lfp);
2008 return 1;
2009 }
2010
2011 if (*cp++ != ' ' || !isdigit((int)*cp))
2012 return 0;
2013 cal.hour = (u_char)(*cp++ - '0');
2014 if (isdigit((int)*cp)) {
2015 cal.hour = (u_char)((cal.hour << 3) + (cal.hour << 1));
2016 cal.hour = (u_char)(cal.hour + *cp++ - '0');
2017 }
2018
2019 if (*cp++ != ':' || !isdigit((int)*cp))
2020 return 0;
2021 cal.minute = (u_char)(*cp++ - '0');
2022 if (isdigit((int)*cp)) {
2023 cal.minute = (u_char)((cal.minute << 3) + (cal.minute << 1));
2024 cal.minute = (u_char)(cal.minute + *cp++ - '0');
2025 }
2026
2027 if (*cp++ != ':' || !isdigit((int)*cp))
2028 return 0;
2029 cal.second = (u_char)(*cp++ - '0');
2030 if (isdigit((int)*cp)) {
2031 cal.second = (u_char)((cal.second << 3) + (cal.second << 1));
2032 cal.second = (u_char)(cal.second + *cp++ - '0');
2033 }
2034
2035 /*
2036 * For RT-11, 1972 seems to be the pivot year
2037 */
2038 if (cal.year < 72)
2039 cal.year += 2000;
2040 if (cal.year < 100)
2041 cal.year += 1900;
2042
2043 lfp->l_ui = caltontp(&cal);
2044 lfp->l_uf = 0;
2045 return 1;
2046 }
2047
2048
2049 /*
2050 * decodets - decode a timestamp into an l_fp format number, with
2051 * consideration of fuzzball formats.
2052 */
2053 int
2054 decodets(
2055 char *str,
2056 l_fp *lfp
2057 )
2058 {
2059 char *cp;
2060 char buf[30];
2061 size_t b;
2062
2063 /*
2064 * If it starts with a 0x, decode as hex.
2065 */
2066 if (*str == '0' && (*(str+1) == 'x' || *(str+1) == 'X'))
2067 return hextolfp(str+2, lfp);
2068
2069 /*
2070 * If it starts with a '"', try it as an RT-11 date.
2071 */
2072 if (*str == '"') {
2073 cp = str + 1;
2074 b = 0;
2075 while ('"' != *cp && '\0' != *cp &&
2076 b < COUNTOF(buf) - 1)
2077 buf[b++] = *cp++;
2078 buf[b] = '\0';
2079 return rtdatetolfp(buf, lfp);
2080 }
2081
2082 /*
2083 * Might still be hex. Check out the first character. Talk
2084 * about heuristics!
2085 */
2086 if ((*str >= 'A' && *str <= 'F') || (*str >= 'a' && *str <= 'f'))
2087 return hextolfp(str, lfp);
2088
2089 /*
2090 * Try it as a decimal. If this fails, try as an unquoted
2091 * RT-11 date. This code should go away eventually.
2092 */
2093 if (atolfp(str, lfp))
2094 return 1;
2095
2096 return rtdatetolfp(str, lfp);
2097 }
2098
2099
2100 /*
2101 * decodetime - decode a time value. It should be in milliseconds
2102 */
2103 int
2104 decodetime(
2105 char *str,
2106 l_fp *lfp
2107 )
2108 {
2109 return mstolfp(str, lfp);
2110 }
2111
2112
2113 /*
2114 * decodeint - decode an integer
2115 */
2116 int
2117 decodeint(
2118 char *str,
2119 long *val
2120 )
2121 {
2122 if (*str == '0') {
2123 if (*(str+1) == 'x' || *(str+1) == 'X')
2124 return hextoint(str+2, (u_long *)val);
2125 return octtoint(str, (u_long *)val);
2126 }
2127 return atoint(str, val);
2128 }
2129
2130
2131 /*
2132 * decodeuint - decode an unsigned integer
2133 */
2134 int
2135 decodeuint(
2136 char *str,
2137 u_long *val
2138 )
2139 {
2140 if (*str == '0') {
2141 if (*(str + 1) == 'x' || *(str + 1) == 'X')
2142 return (hextoint(str + 2, val));
2143 return (octtoint(str, val));
2144 }
2145 return (atouint(str, val));
2146 }
2147
2148
2149 /*
2150 * decodearr - decode an array of time values
2151 */
2152 static int
2153 decodearr(
2154 char *str,
2155 int *narr,
2156 l_fp *lfparr
2157 )
2158 {
2159 register char *cp, *bp;
2160 register l_fp *lfp;
2161 char buf[60];
2162
2163 lfp = lfparr;
2164 cp = str;
2165 *narr = 0;
2166
2167 while (*narr < 8) {
2168 while (isspace((int)*cp))
2169 cp++;
2170 if (*cp == '\0')
2171 break;
2172
2173 bp = buf;
2174 while (!isspace((int)*cp) && *cp != '\0')
2175 *bp++ = *cp++;
2176 *bp++ = '\0';
2177
2178 if (!decodetime(buf, lfp))
2179 return 0;
2180 (*narr)++;
2181 lfp++;
2182 }
2183 return 1;
2184 }
2185
2186
2187 /*
2188 * Finally, the built in command handlers
2189 */
2190
2191 /*
2192 * help - tell about commands, or details of a particular command
2193 */
2194 static void
2195 help(
2196 struct parse *pcmd,
2197 FILE *fp
2198 )
2199 {
2200 struct xcmd *xcp = NULL; /* quiet warning */
2201 const char *cmd;
2202 const char *list[100];
2203 size_t word, words;
2204 size_t row, rows;
2205 size_t col, cols;
2206 size_t length;
2207
2208 if (pcmd->nargs == 0) {
2209 words = 0;
2210 for (xcp = builtins; xcp->keyword != NULL; xcp++) {
2211 if (*(xcp->keyword) != '?' &&
2212 words < COUNTOF(list))
2213 list[words++] = xcp->keyword;
2214 }
2215 for (xcp = opcmds; xcp->keyword != NULL; xcp++)
2216 if (words < COUNTOF(list))
2217 list[words++] = xcp->keyword;
2218
2219 qsort((void *)list, words, sizeof(list[0]), helpsort);
2220 col = 0;
2221 for (word = 0; word < words; word++) {
2222 length = strlen(list[word]);
2223 col = max(col, length);
2224 }
2225
2226 cols = SCREENWIDTH / ++col;
2227 rows = (words + cols - 1) / cols;
2228
2229 fprintf(fp, "ntpq commands:\n");
2230
2231 for (row = 0; row < rows; row++) {
2232 for (word = row; word < words; word += rows)
2233 fprintf(fp, "%-*.*s", (int)col,
2234 (int)col - 1, list[word]);
2235 fprintf(fp, "\n");
2236 }
2237 } else {
2238 cmd = pcmd->argval[0].string;
2239 words = findcmd(cmd, builtins, opcmds, &xcp);
2240 if (words == 0) {
2241 fprintf(stderr,
2242 "Command `%s' is unknown\n", cmd);
2243 return;
2244 } else if (words >= 2) {
2245 fprintf(stderr,
2246 "Command `%s' is ambiguous\n", cmd);
2247 return;
2248 }
2249 fprintf(fp, "function: %s\n", xcp->comment);
2250 printusage(xcp, fp);
2251 }
2252 }
2253
2254
2255 /*
2256 * helpsort - do hostname qsort comparisons
2257 */
2258 static int
2259 helpsort(
2260 const void *t1,
2261 const void *t2
2262 )
2263 {
2264 const char * const * name1 = t1;
2265 const char * const * name2 = t2;
2266
2267 return strcmp(*name1, *name2);
2268 }
2269
2270
2271 /*
2272 * printusage - print usage information for a command
2273 */
2274 static void
2275 printusage(
2276 struct xcmd *xcp,
2277 FILE *fp
2278 )
2279 {
2280 register int i;
2281
2282 /* XXX: Do we need to warn about extra args here too? */
2283
2284 (void) fprintf(fp, "usage: %s", xcp->keyword);
2285 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) {
2286 if (xcp->arg[i] & OPT)
2287 (void) fprintf(fp, " [ %s ]", xcp->desc[i]);
2288 else
2289 (void) fprintf(fp, " %s", xcp->desc[i]);
2290 }
2291 (void) fprintf(fp, "\n");
2292 }
2293
2294
2295 /*
2296 * timeout - set time out time
2297 */
2298 static void
2299 timeout(
2300 struct parse *pcmd,
2301 FILE *fp
2302 )
2303 {
2304 int val;
2305
2306 if (pcmd->nargs == 0) {
2307 val = (int)tvout.tv_sec * 1000 + tvout.tv_usec / 1000;
2308 (void) fprintf(fp, "primary timeout %d ms\n", val);
2309 } else {
2310 tvout.tv_sec = pcmd->argval[0].uval / 1000;
2311 tvout.tv_usec = (pcmd->argval[0].uval - ((long)tvout.tv_sec * 1000))
2312 * 1000;
2313 }
2314 }
2315
2316
2317 /*
2318 * auth_delay - set delay for auth requests
2319 */
2320 static void
2321 auth_delay(
2322 struct parse *pcmd,
2323 FILE *fp
2324 )
2325 {
2326 int isneg;
2327 u_long val;
2328
2329 if (pcmd->nargs == 0) {
2330 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967;
2331 (void) fprintf(fp, "delay %lu ms\n", val);
2332 } else {
2333 if (pcmd->argval[0].ival < 0) {
2334 isneg = 1;
2335 val = (u_long)(-pcmd->argval[0].ival);
2336 } else {
2337 isneg = 0;
2338 val = (u_long)pcmd->argval[0].ival;
2339 }
2340
2341 delay_time.l_ui = val / 1000;
2342 val %= 1000;
2343 delay_time.l_uf = val * 4294967; /* 2**32/1000 */
2344
2345 if (isneg)
2346 L_NEG(&delay_time);
2347 }
2348 }
2349
2350
2351 /*
2352 * host - set the host we are dealing with.
2353 */
2354 static void
2355 host(
2356 struct parse *pcmd,
2357 FILE *fp
2358 )
2359 {
2360 int i;
2361
2362 if (pcmd->nargs == 0) {
2363 if (havehost)
2364 (void) fprintf(fp, "current host is %s\n",
2365 currenthost);
2366 else
2367 (void) fprintf(fp, "no current host\n");
2368 return;
2369 }
2370
2371 i = 0;
2372 ai_fam_templ = ai_fam_default;
2373 if (pcmd->nargs == 2) {
2374 if (!strcmp("-4", pcmd->argval[i].string))
2375 ai_fam_templ = AF_INET;
2376 else if (!strcmp("-6", pcmd->argval[i].string))
2377 ai_fam_templ = AF_INET6;
2378 else
2379 goto no_change;
2380 i = 1;
2381 }
2382 if (openhost(pcmd->argval[i].string, ai_fam_templ)) {
2383 fprintf(fp, "current host set to %s\n", currenthost);
2384 } else {
2385 no_change:
2386 if (havehost)
2387 fprintf(fp, "current host remains %s\n",
2388 currenthost);
2389 else
2390 fprintf(fp, "still no current host\n");
2391 }
2392 }
2393
2394
2395 /*
2396 * poll - do one (or more) polls of the host via NTP
2397 */
2398 /*ARGSUSED*/
2399 static void
2400 ntp_poll(
2401 struct parse *pcmd,
2402 FILE *fp
2403 )
2404 {
2405 (void) fprintf(fp, "poll not implemented yet\n");
2406 }
2407
2408
2409 /*
2410 * keyid - get a keyid to use for authenticating requests
2411 */
2412 static void
2413 keyid(
2414 struct parse *pcmd,
2415 FILE *fp
2416 )
2417 {
2418 if (pcmd->nargs == 0) {
2419 if (info_auth_keyid == 0)
2420 (void) fprintf(fp, "no keyid defined\n");
2421 else
2422 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid);
2423 } else {
2424 /* allow zero so that keyid can be cleared. */
2425 if(pcmd->argval[0].uval > NTP_MAXKEY)
2426 (void) fprintf(fp, "Invalid key identifier\n");
2427 info_auth_keyid = pcmd->argval[0].uval;
2428 }
2429 }
2430
2431 /*
2432 * keytype - get type of key to use for authenticating requests
2433 */
2434 static void
2435 keytype(
2436 struct parse *pcmd,
2437 FILE *fp
2438 )
2439 {
2440 const char * digest_name;
2441 size_t digest_len;
2442 int key_type;
2443
2444 if (!pcmd->nargs) {
2445 fprintf(fp, "keytype is %s with %lu octet digests\n",
2446 keytype_name(info_auth_keytype),
2447 (u_long)info_auth_hashlen);
2448 return;
2449 }
2450
2451 digest_name = pcmd->argval[0].string;
2452 digest_len = 0;
2453 key_type = keytype_from_text(digest_name, &digest_len);
2454
2455 if (!key_type) {
2456 fprintf(fp, "keytype is not valid. "
2457 #ifdef OPENSSL
2458 "Type \"help keytype\" for the available digest types.\n");
2459 #else
2460 "Only \"md5\" is available.\n");
2461 #endif
2462 return;
2463 }
2464
2465 info_auth_keytype = key_type;
2466 info_auth_hashlen = digest_len;
2467 }
2468
2469
2470 /*
2471 * passwd - get an authentication key
2472 */
2473 /*ARGSUSED*/
2474 static void
2475 passwd(
2476 struct parse *pcmd,
2477 FILE *fp
2478 )
2479 {
2480 const char *pass;
2481
2482 if (info_auth_keyid == 0) {
2483 info_auth_keyid = getkeyid("Keyid: ");
2484 if (info_auth_keyid == 0) {
2485 (void)fprintf(fp, "Keyid must be defined\n");
2486 return;
2487 }
2488 }
2489 if (pcmd->nargs >= 1)
2490 pass = pcmd->argval[0].string;
2491 else {
2492 pass = getpass_keytype(info_auth_keytype);
2493 if ('\0' == pass[0]) {
2494 fprintf(fp, "Password unchanged\n");
2495 return;
2496 }
2497 }
2498 authusekey(info_auth_keyid, info_auth_keytype,
2499 (const u_char *)pass);
2500 authtrust(info_auth_keyid, 1);
2501 }
2502
2503
2504 /*
2505 * hostnames - set the showhostnames flag
2506 */
2507 static void
2508 hostnames(
2509 struct parse *pcmd,
2510 FILE *fp
2511 )
2512 {
2513 if (pcmd->nargs == 0) {
2514 if (showhostnames)
2515 (void) fprintf(fp, "hostnames being shown\n");
2516 else
2517 (void) fprintf(fp, "hostnames not being shown\n");
2518 } else {
2519 if (STREQ(pcmd->argval[0].string, "yes"))
2520 showhostnames = 1;
2521 else if (STREQ(pcmd->argval[0].string, "no"))
2522 showhostnames = 0;
2523 else
2524 (void)fprintf(stderr, "What?\n");
2525 }
2526 }
2527
2528
2529
2530 /*
2531 * setdebug - set/change debugging level
2532 */
2533 static void
2534 setdebug(
2535 struct parse *pcmd,
2536 FILE *fp
2537 )
2538 {
2539 if (pcmd->nargs == 0) {
2540 (void) fprintf(fp, "debug level is %d\n", debug);
2541 return;
2542 } else if (STREQ(pcmd->argval[0].string, "no")) {
2543 debug = 0;
2544 } else if (STREQ(pcmd->argval[0].string, "more")) {
2545 debug++;
2546 } else if (STREQ(pcmd->argval[0].string, "less")) {
2547 debug--;
2548 } else {
2549 (void) fprintf(fp, "What?\n");
2550 return;
2551 }
2552 (void) fprintf(fp, "debug level set to %d\n", debug);
2553 }
2554
2555
2556 /*
2557 * quit - stop this nonsense
2558 */
2559 /*ARGSUSED*/
2560 static void
2561 quit(
2562 struct parse *pcmd,
2563 FILE *fp
2564 )
2565 {
2566 if (havehost)
2567 closesocket(sockfd); /* cleanliness next to godliness */
2568 exit(0);
2569 }
2570
2571
2572 /*
2573 * version - print the current version number
2574 */
2575 /*ARGSUSED*/
2576 static void
2577 version(
2578 struct parse *pcmd,
2579 FILE *fp
2580 )
2581 {
2582
2583 (void) fprintf(fp, "%s\n", Version);
2584 return;
2585 }
2586
2587
2588 /*
2589 * raw - set raw mode output
2590 */
2591 /*ARGSUSED*/
2592 static void
2593 raw(
2594 struct parse *pcmd,
2595 FILE *fp
2596 )
2597 {
2598 rawmode = 1;
2599 (void) fprintf(fp, "Output set to raw\n");
2600 }
2601
2602
2603 /*
2604 * cooked - set cooked mode output
2605 */
2606 /*ARGSUSED*/
2607 static void
2608 cooked(
2609 struct parse *pcmd,
2610 FILE *fp
2611 )
2612 {
2613 rawmode = 0;
2614 (void) fprintf(fp, "Output set to cooked\n");
2615 return;
2616 }
2617
2618
2619 /*
2620 * authenticate - always authenticate requests to this host
2621 */
2622 static void
2623 authenticate(
2624 struct parse *pcmd,
2625 FILE *fp
2626 )
2627 {
2628 if (pcmd->nargs == 0) {
2629 if (always_auth) {
2630 (void) fprintf(fp,
2631 "authenticated requests being sent\n");
2632 } else
2633 (void) fprintf(fp,
2634 "unauthenticated requests being sent\n");
2635 } else {
2636 if (STREQ(pcmd->argval[0].string, "yes")) {
2637 always_auth = 1;
2638 } else if (STREQ(pcmd->argval[0].string, "no")) {
2639 always_auth = 0;
2640 } else
2641 (void)fprintf(stderr, "What?\n");
2642 }
2643 }
2644
2645
2646 /*
2647 * ntpversion - choose the NTP version to use
2648 */
2649 static void
2650 ntpversion(
2651 struct parse *pcmd,
2652 FILE *fp
2653 )
2654 {
2655 if (pcmd->nargs == 0) {
2656 (void) fprintf(fp,
2657 "NTP version being claimed is %d\n", pktversion);
2658 } else {
2659 if (pcmd->argval[0].uval < NTP_OLDVERSION
2660 || pcmd->argval[0].uval > NTP_VERSION) {
2661 (void) fprintf(stderr, "versions %d to %d, please\n",
2662 NTP_OLDVERSION, NTP_VERSION);
2663 } else {
2664 pktversion = (u_char) pcmd->argval[0].uval;
2665 }
2666 }
2667 }
2668
2669
2670 static void __attribute__((__format__(__printf__, 1, 0)))
2671 vwarning(const char *fmt, va_list ap)
2672 {
2673 int serrno = errno;
2674 (void) fprintf(stderr, "%s: ", progname);
2675 vfprintf(stderr, fmt, ap);
2676 (void) fprintf(stderr, ": %s\n", strerror(serrno));
2677 }
2678
2679 /*
2680 * warning - print a warning message
2681 */
2682 static void __attribute__((__format__(__printf__, 1, 2)))
2683 warning(
2684 const char *fmt,
2685 ...
2686 )
2687 {
2688 va_list ap;
2689 va_start(ap, fmt);
2690 vwarning(fmt, ap);
2691 va_end(ap);
2692 }
2693
2694
2695 /*
2696 * error - print a message and exit
2697 */
2698 static void __attribute__((__format__(__printf__, 1, 2)))
2699 error(
2700 const char *fmt,
2701 ...
2702 )
2703 {
2704 va_list ap;
2705 va_start(ap, fmt);
2706 vwarning(fmt, ap);
2707 va_end(ap);
2708 exit(1);
2709 }
2710 /*
2711 * getkeyid - prompt the user for a keyid to use
2712 */
2713 static u_long
2714 getkeyid(
2715 const char *keyprompt
2716 )
2717 {
2718 int c;
2719 FILE *fi;
2720 char pbuf[20];
2721 size_t i;
2722 size_t ilim;
2723
2724 #ifndef SYS_WINNT
2725 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL)
2726 #else
2727 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL)
2728 #endif /* SYS_WINNT */
2729 fi = stdin;
2730 else
2731 setbuf(fi, (char *)NULL);
2732 fprintf(stderr, "%s", keyprompt); fflush(stderr);
2733 for (i = 0, ilim = COUNTOF(pbuf) - 1;
2734 i < ilim && (c = getc(fi)) != '\n' && c != EOF;
2735 )
2736 pbuf[i++] = (char)c;
2737 pbuf[i] = '\0';
2738 if (fi != stdin)
2739 fclose(fi);
2740
2741 return (u_long) atoi(pbuf);
2742 }
2743
2744
2745 /*
2746 * atoascii - printable-ize possibly ascii data using the character
2747 * transformations cat -v uses.
2748 */
2749 static void
2750 atoascii(
2751 const char *in,
2752 size_t in_octets,
2753 char *out,
2754 size_t out_octets
2755 )
2756 {
2757 const u_char * pchIn;
2758 const u_char * pchInLimit;
2759 u_char * pchOut;
2760 u_char c;
2761
2762 pchIn = (const u_char *)in;
2763 pchInLimit = pchIn + in_octets;
2764 pchOut = (u_char *)out;
2765
2766 if (NULL == pchIn) {
2767 if (0 < out_octets)
2768 *pchOut = '\0';
2769 return;
2770 }
2771
2772 #define ONEOUT(c) \
2773 do { \
2774 if (0 == --out_octets) { \
2775 *pchOut = '\0'; \
2776 return; \
2777 } \
2778 *pchOut++ = (c); \
2779 } while (0)
2780
2781 for ( ; pchIn < pchInLimit; pchIn++) {
2782 c = *pchIn;
2783 if ('\0' == c)
2784 break;
2785 if (c & 0x80) {
2786 ONEOUT('M');
2787 ONEOUT('-');
2788 c &= 0x7f;
2789 }
2790 if (c < ' ') {
2791 ONEOUT('^');
2792 ONEOUT((u_char)(c + '@'));
2793 } else if (0x7f == c) {
2794 ONEOUT('^');
2795 ONEOUT('?');
2796 } else
2797 ONEOUT(c);
2798 }
2799 ONEOUT('\0');
2800
2801 #undef ONEOUT
2802 }
2803
2804
2805 /*
2806 * makeascii - print possibly ascii data using the character
2807 * transformations that cat -v uses.
2808 */
2809 void
2810 makeascii(
2811 size_t length,
2812 const char *data,
2813 FILE *fp
2814 )
2815 {
2816 const u_char *data_u_char;
2817 const u_char *cp;
2818 int c;
2819
2820 data_u_char = (const u_char *)data;
2821
2822 for (cp = data_u_char; cp < data_u_char + length; cp++) {
2823 c = (int)*cp;
2824 if (c & 0x80) {
2825 putc('M', fp);
2826 putc('-', fp);
2827 c &= 0x7f;
2828 }
2829
2830 if (c < ' ') {
2831 putc('^', fp);
2832 putc(c + '@', fp);
2833 } else if (0x7f == c) {
2834 putc('^', fp);
2835 putc('?', fp);
2836 } else
2837 putc(c, fp);
2838 }
2839 }
2840
2841
2842 /*
2843 * asciize - same thing as makeascii except add a newline
2844 */
2845 void
2846 asciize(
2847 int length,
2848 char *data,
2849 FILE *fp
2850 )
2851 {
2852 makeascii(length, data, fp);
2853 putc('\n', fp);
2854 }
2855
2856
2857 /*
2858 * truncate string to fit clipping excess at end.
2859 * "too long" -> "too l"
2860 * Used for hostnames.
2861 */
2862 const char *
2863 trunc_right(
2864 const char * src,
2865 size_t width
2866 )
2867 {
2868 size_t sl;
2869 char * out;
2870
2871
2872 sl = strlen(src);
2873 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 0) {
2874 LIB_GETBUF(out);
2875 memcpy(out, src, width);
2876 out[width] = '\0';
2877
2878 return out;
2879 }
2880
2881 return src;
2882 }
2883
2884
2885 /*
2886 * truncate string to fit by preserving right side and using '_' to hint
2887 * "too long" -> "_long"
2888 * Used for local IPv6 addresses, where low bits differentiate.
2889 */
2890 const char *
2891 trunc_left(
2892 const char * src,
2893 size_t width
2894 )
2895 {
2896 size_t sl;
2897 char * out;
2898
2899
2900 sl = strlen(src);
2901 if (sl > width && LIB_BUFLENGTH - 1 > width && width > 1) {
2902 LIB_GETBUF(out);
2903 out[0] = '_';
2904 memcpy(&out[1], &src[sl + 1 - width], width);
2905
2906 return out;
2907 }
2908
2909 return src;
2910 }
2911
2912
2913 /*
2914 * Some circular buffer space
2915 */
2916 #define CBLEN 80
2917 #define NUMCB 6
2918
2919 char circ_buf[NUMCB][CBLEN];
2920 int nextcb = 0;
2921
2922 /*
2923 * nextvar - find the next variable in the buffer
2924 */
2925 int
2926 nextvar(
2927 size_t *datalen,
2928 const char **datap,
2929 char **vname,
2930 char **vvalue
2931 )
2932 {
2933 const char *cp;
2934 const char *np;
2935 const char *cpend;
2936 size_t srclen;
2937 size_t len;
2938 static char name[MAXVARLEN];
2939 static char value[MAXVALLEN];
2940
2941 cp = *datap;
2942 cpend = cp + *datalen;
2943
2944 /*
2945 * Space past commas and white space
2946 */
2947 while (cp < cpend && (*cp == ',' || isspace((int)*cp)))
2948 cp++;
2949 if (cp >= cpend)
2950 return 0;
2951
2952 /*
2953 * Copy name until we hit a ',', an '=', a '\r' or a '\n'. Backspace
2954 * over any white space and terminate it.
2955 */
2956 srclen = strcspn(cp, ",=\r\n");
2957 srclen = min(srclen, (size_t)(cpend - cp));
2958 len = srclen;
2959 while (len > 0 && isspace((unsigned char)cp[len - 1]))
2960 len--;
2961 if (len > 0)
2962 memcpy(name, cp, len);
2963 name[len] = '\0';
2964 *vname = name;
2965 cp += srclen;
2966
2967 /*
2968 * Check if we hit the end of the buffer or a ','. If so we are done.
2969 */
2970 if (cp >= cpend || *cp == ',' || *cp == '\r' || *cp == '\n') {
2971 if (cp < cpend)
2972 cp++;
2973 *datap = cp;
2974 *datalen = size2int_sat(cpend - cp);
2975 *vvalue = NULL;
2976 return 1;
2977 }
2978
2979 /*
2980 * So far, so good. Copy out the value
2981 */
2982 cp++; /* past '=' */
2983 while (cp < cpend && (isspace((unsigned char)*cp) && *cp != '\r' && *cp != '\n'))
2984 cp++;
2985 np = cp;
2986 if ('"' == *np) {
2987 do {
2988 np++;
2989 } while (np < cpend && '"' != *np);
2990 if (np < cpend && '"' == *np)
2991 np++;
2992 } else {
2993 while (np < cpend && ',' != *np && '\r' != *np)
2994 np++;
2995 }
2996 len = np - cp;
2997 if (np > cpend || len >= sizeof(value) ||
2998 (np < cpend && ',' != *np && '\r' != *np))
2999 return 0;
3000 memcpy(value, cp, len);
3001 /*
3002 * Trim off any trailing whitespace
3003 */
3004 while (len > 0 && isspace((unsigned char)value[len - 1]))
3005 len--;
3006 value[len] = '\0';
3007
3008 /*
3009 * Return this. All done.
3010 */
3011 if (np < cpend && ',' == *np)
3012 np++;
3013 *datap = np;
3014 *datalen = size2int_sat(cpend - np);
3015 *vvalue = value;
3016 return 1;
3017 }
3018
3019
3020 u_short
3021 varfmt(const char * varname)
3022 {
3023 u_int n;
3024
3025 for (n = 0; n < COUNTOF(cookedvars); n++)
3026 if (!strcmp(varname, cookedvars[n].varname))
3027 return cookedvars[n].fmt;
3028
3029 return PADDING;
3030 }
3031
3032
3033 /*
3034 * printvars - print variables returned in response packet
3035 */
3036 void
3037 printvars(
3038 size_t length,
3039 const char *data,
3040 int status,
3041 int sttype,
3042 int quiet,
3043 FILE *fp
3044 )
3045 {
3046 if (rawmode)
3047 rawprint(sttype, length, data, status, quiet, fp);
3048 else
3049 cookedprint(sttype, length, data, status, quiet, fp);
3050 }
3051
3052
3053 /*
3054 * rawprint - do a printout of the data in raw mode
3055 */
3056 static void
3057 rawprint(
3058 int datatype,
3059 size_t length,
3060 const char *data,
3061 int status,
3062 int quiet,
3063 FILE *fp
3064 )
3065 {
3066 const char *cp;
3067 const char *cpend;
3068
3069 /*
3070 * Essentially print the data as is. We reformat unprintables, though.
3071 */
3072 cp = data;
3073 cpend = data + length;
3074
3075 if (!quiet)
3076 (void) fprintf(fp, "status=0x%04x,\n", status);
3077
3078 while (cp < cpend) {
3079 if (*cp == '\r') {
3080 /*
3081 * If this is a \r and the next character is a
3082 * \n, supress this, else pretty print it. Otherwise
3083 * just output the character.
3084 */
3085 if (cp == (cpend - 1) || *(cp + 1) != '\n')
3086 makeascii(1, cp, fp);
3087 } else if (isspace((unsigned char)*cp) || isprint((unsigned char)*cp))
3088 putc(*cp, fp);
3089 else
3090 makeascii(1, cp, fp);
3091 cp++;
3092 }
3093 }
3094
3095
3096 /*
3097 * Global data used by the cooked output routines
3098 */
3099 int out_chars; /* number of characters output */
3100 int out_linecount; /* number of characters output on this line */
3101
3102
3103 /*
3104 * startoutput - get ready to do cooked output
3105 */
3106 static void
3107 startoutput(void)
3108 {
3109 out_chars = 0;
3110 out_linecount = 0;
3111 }
3112
3113
3114 /*
3115 * output - output a variable=value combination
3116 */
3117 static void
3118 output(
3119 FILE *fp,
3120 const char *name,
3121 const char *value
3122 )
3123 {
3124 int len;
3125
3126 /* strlen of "name=value" */
3127 len = size2int_sat(strlen(name) + 1 + strlen(value));
3128
3129 if (out_chars != 0) {
3130 out_chars += 2;
3131 if ((out_linecount + len + 2) > MAXOUTLINE) {
3132 fputs(",\n", fp);
3133 out_linecount = 0;
3134 } else {
3135 fputs(", ", fp);
3136 out_linecount += 2;
3137 }
3138 }
3139
3140 fputs(name, fp);
3141 putc('=', fp);
3142 fputs(value, fp);
3143 out_chars += len;
3144 out_linecount += len;
3145 }
3146
3147
3148 /*
3149 * endoutput - terminate a block of cooked output
3150 */
3151 static void
3152 endoutput(
3153 FILE *fp
3154 )
3155 {
3156 if (out_chars != 0)
3157 putc('\n', fp);
3158 }
3159
3160
3161 /*
3162 * outputarr - output an array of values
3163 */
3164 static void
3165 outputarr(
3166 FILE *fp,
3167 char *name,
3168 int narr,
3169 l_fp *lfp
3170 )
3171 {
3172 char *bp;
3173 char *cp;
3174 size_t i;
3175 size_t len;
3176 char buf[256];
3177
3178 bp = buf;
3179 /*
3180 * Hack to align delay and offset values
3181 */
3182 for (i = (int)strlen(name); i < 11; i++)
3183 *bp++ = ' ';
3184
3185 for (i = narr; i > 0; i--) {
3186 if (i != (size_t)narr)
3187 *bp++ = ' ';
3188 cp = lfptoms(lfp, 2);
3189 len = strlen(cp);
3190 if (len > 7) {
3191 cp[7] = '\0';
3192 len = 7;
3193 }
3194 while (len < 7) {
3195 *bp++ = ' ';
3196 len++;
3197 }
3198 while (*cp != '\0')
3199 *bp++ = *cp++;
3200 lfp++;
3201 }
3202 *bp = '\0';
3203 output(fp, name, buf);
3204 }
3205
3206 static char *
3207 tstflags(
3208 u_long val
3209 )
3210 {
3211 register char *cp, *s;
3212 size_t cb;
3213 register int i;
3214 register const char *sep;
3215
3216 sep = "";
3217 s = cp = circ_buf[nextcb];
3218 if (++nextcb >= NUMCB)
3219 nextcb = 0;
3220 cb = sizeof(circ_buf[0]);
3221
3222 snprintf(cp, cb, "%02lx", val);
3223 cp += strlen(cp);
3224 cb -= strlen(cp);
3225 if (!val) {
3226 strlcat(cp, " ok", cb);
3227 cp += strlen(cp);
3228 cb -= strlen(cp);
3229 } else {
3230 if (cb) {
3231 *cp++ = ' ';
3232 cb--;
3233 }
3234 for (i = 0; i < (int)COUNTOF(tstflagnames); i++) {
3235 if (val & 0x1) {
3236 snprintf(cp, cb, "%s%s", sep,
3237 tstflagnames[i]);
3238 sep = ", ";
3239 cp += strlen(cp);
3240 cb -= strlen(cp);
3241 }
3242 val >>= 1;
3243 }
3244 }
3245 if (cb)
3246 *cp = '\0';
3247
3248 return s;
3249 }
3250
3251 /*
3252 * cookedprint - output variables in cooked mode
3253 */
3254 static void
3255 cookedprint(
3256 int datatype,
3257 size_t length,
3258 const char *data,
3259 int status,
3260 int quiet,
3261 FILE *fp
3262 )
3263 {
3264 char *name;
3265 char *value;
3266 char output_raw;
3267 int fmt;
3268 l_fp lfp;
3269 sockaddr_u hval;
3270 u_long uval;
3271 int narr;
3272 size_t len;
3273 l_fp lfparr[8];
3274 char b[12];
3275 char bn[2 * MAXVARLEN];
3276 char bv[2 * MAXVALLEN];
3277
3278 UNUSED_ARG(datatype);
3279
3280 if (!quiet)
3281 fprintf(fp, "status=%04x %s,\n", status,
3282 statustoa(datatype, status));
3283
3284 startoutput();
3285 while (nextvar(&length, &data, &name, &value)) {
3286 fmt = varfmt(name);
3287 output_raw = 0;
3288 switch (fmt) {
3289
3290 case PADDING:
3291 output_raw = '*';
3292 break;
3293
3294 case TS:
3295 if (!decodets(value, &lfp))
3296 output_raw = '?';
3297 else
3298 output(fp, name, prettydate(&lfp));
3299 break;
3300
3301 case HA: /* fallthru */
3302 case NA:
3303 if (!decodenetnum(value, &hval)) {
3304 output_raw = '?';
3305 } else if (fmt == HA){
3306 output(fp, name, nntohost(&hval));
3307 } else {
3308 output(fp, name, stoa(&hval));
3309 }
3310 break;
3311
3312 case RF:
3313 if (decodenetnum(value, &hval)) {
3314 if (ISREFCLOCKADR(&hval))
3315 output(fp, name,
3316 refnumtoa(&hval));
3317 else
3318 output(fp, name, stoa(&hval));
3319 } else if (strlen(value) <= 4) {
3320 output(fp, name, value);
3321 } else {
3322 output_raw = '?';
3323 }
3324 break;
3325
3326 case LP:
3327 if (!decodeuint(value, &uval) || uval > 3) {
3328 output_raw = '?';
3329 } else {
3330 b[0] = (0x2 & uval)
3331 ? '1'
3332 : '0';
3333 b[1] = (0x1 & uval)
3334 ? '1'
3335 : '0';
3336 b[2] = '\0';
3337 output(fp, name, b);
3338 }
3339 break;
3340
3341 case OC:
3342 if (!decodeuint(value, &uval)) {
3343 output_raw = '?';
3344 } else {
3345 snprintf(b, sizeof(b), "%03lo", uval);
3346 output(fp, name, b);
3347 }
3348 break;
3349
3350 case AR:
3351 if (!decodearr(value, &narr, lfparr))
3352 output_raw = '?';
3353 else
3354 outputarr(fp, name, narr, lfparr);
3355 break;
3356
3357 case FX:
3358 if (!decodeuint(value, &uval))
3359 output_raw = '?';
3360 else
3361 output(fp, name, tstflags(uval));
3362 break;
3363
3364 default:
3365 fprintf(stderr, "Internal error in cookedprint, %s=%s, fmt %d\n",
3366 name, value, fmt);
3367 output_raw = '?';
3368 break;
3369 }
3370
3371 if (output_raw != 0) {
3372 /* TALOS-CAN-0063: avoid buffer overrun */
3373 atoascii(name, MAXVARLEN, bn, sizeof(bn));
3374 if (output_raw != '*') {
3375 atoascii(value, MAXVALLEN,
3376 bv, sizeof(bv) - 1);
3377 len = strlen(bv);
3378 bv[len] = output_raw;
3379 bv[len+1] = '\0';
3380 } else {
3381 atoascii(value, MAXVALLEN,
3382 bv, sizeof(bv));
3383 }
3384 output(fp, bn, bv);
3385 }
3386 }
3387 endoutput(fp);
3388 }
3389
3390
3391 /*
3392 * sortassoc - sort associations in the cache into ascending order
3393 */
3394 void
3395 sortassoc(void)
3396 {
3397 if (numassoc > 1)
3398 qsort(assoc_cache, (size_t)numassoc,
3399 sizeof(assoc_cache[0]), &assoccmp);
3400 }
3401
3402
3403 /*
3404 * assoccmp - compare two associations
3405 */
3406 static int
3407 assoccmp(
3408 const void *t1,
3409 const void *t2
3410 )
3411 {
3412 const struct association *ass1 = t1;
3413 const struct association *ass2 = t2;
3414
3415 if (ass1->assid < ass2->assid)
3416 return -1;
3417 if (ass1->assid > ass2->assid)
3418 return 1;
3419 return 0;
3420 }
3421
3422
3423 /*
3424 * grow_assoc_cache() - enlarge dynamic assoc_cache array
3425 *
3426 * The strategy is to add an assumed 4k page size at a time, leaving
3427 * room for malloc() bookkeeping overhead equivalent to 4 pointers.
3428 */
3429 void
3430 grow_assoc_cache(void)
3431 {
3432 static size_t prior_sz;
3433 size_t new_sz;
3434
3435 new_sz = prior_sz + 4 * 1024;
3436 if (0 == prior_sz) {
3437 new_sz -= 4 * sizeof(void *);
3438 }
3439 assoc_cache = erealloc_zero(assoc_cache, new_sz, prior_sz);
3440 prior_sz = new_sz;
3441 assoc_cache_slots = (u_int)(new_sz / sizeof(assoc_cache[0]));
3442 }
3443
3444
3445 /*
3446 * ntpq_custom_opt_handler - autoopts handler for -c and -p
3447 *
3448 * By default, autoopts loses the relative order of -c and -p options
3449 * on the command line. This routine replaces the default handler for
3450 * those routines and builds a list of commands to execute preserving
3451 * the order.
3452 */
3453 void
3454 ntpq_custom_opt_handler(
3455 tOptions *pOptions,
3456 tOptDesc *pOptDesc
3457 )
3458 {
3459 switch (pOptDesc->optValue) {
3460
3461 default:
3462 fprintf(stderr,
3463 "ntpq_custom_opt_handler unexpected option '%c' (%d)\n",
3464 pOptDesc->optValue, pOptDesc->optValue);
3465 exit(1);
3466
3467 case 'c':
3468 ADDCMD(pOptDesc->pzLastArg);
3469 break;
3470
3471 case 'p':
3472 ADDCMD("peers");
3473 break;
3474 }
3475 }
3476 /*
3477 * Obtain list of digest names
3478 */
3479
3480 #ifdef OPENSSL
3481 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3482 struct hstate {
3483 char *list;
3484 const char **seen;
3485 int idx;
3486 };
3487 #define K_PER_LINE 8
3488 #define K_NL_PFX_STR "\n "
3489 #define K_DELIM_STR ", "
3490 static void list_md_fn(const EVP_MD *m, const char *from, const char *to, void *arg )
3491 {
3492 size_t len, n;
3493 const char *name, *cp, **seen;
3494 struct hstate *hstate = arg;
3495 EVP_MD_CTX ctx;
3496 u_int digest_len;
3497 u_char digest[EVP_MAX_MD_SIZE];
3498
3499 if (!m)
3500 return; /* Ignore aliases */
3501
3502 name = EVP_MD_name(m);
3503
3504 /* Lowercase names aren't accepted by keytype_from_text in ssl_init.c */
3505
3506 for( cp = name; *cp; cp++ ) {
3507 if( islower((unsigned char)*cp) )
3508 return;
3509 }
3510 len = (cp - name) + 1;
3511
3512 /* There are duplicates. Discard if name has been seen. */
3513
3514 for (seen = hstate->seen; *seen; seen++)
3515 if (!strcmp(*seen, name))
3516 return;
3517 n = (seen - hstate->seen) + 2;
3518 hstate->seen = erealloc(hstate->seen, n * sizeof(*seen));
3519 hstate->seen[n-2] = name;
3520 hstate->seen[n-1] = NULL;
3521
3522 /* Discard MACs that NTP won't accept.
3523 * Keep this consistent with keytype_from_text() in ssl_init.c.
3524 */
3525
3526 EVP_DigestInit(&ctx, EVP_get_digestbyname(name));
3527 EVP_DigestFinal(&ctx, digest, &digest_len);
3528 if (digest_len > (MAX_MAC_LEN - sizeof(keyid_t)))
3529 return;
3530
3531 if (hstate->list != NULL)
3532 len += strlen(hstate->list);
3533 len += (hstate->idx >= K_PER_LINE)? strlen(K_NL_PFX_STR): strlen(K_DELIM_STR);
3534
3535 if (hstate->list == NULL) {
3536 hstate->list = (char *)emalloc(len);
3537 hstate->list[0] = '\0';
3538 } else
3539 hstate->list = (char *)erealloc(hstate->list, len);
3540
3541 sprintf(hstate->list + strlen(hstate->list), "%s%s",
3542 ((hstate->idx >= K_PER_LINE)? K_NL_PFX_STR : K_DELIM_STR),
3543 name);
3544 if (hstate->idx >= K_PER_LINE)
3545 hstate->idx = 1;
3546 else
3547 hstate->idx++;
3548 }
3549 # endif
3550 #endif
3551
3552 static char *list_digest_names(void)
3553 {
3554 char *list = NULL;
3555
3556 #ifdef OPENSSL
3557 # ifdef HAVE_EVP_MD_DO_ALL_SORTED
3558 struct hstate hstate = { NULL, NULL, K_PER_LINE+1 };
3559
3560 hstate.seen = (const char **) emalloc_zero(1*sizeof( const char * )); // replaces -> calloc(1, sizeof( const char * ));
3561
3562 INIT_SSL();
3563 EVP_MD_do_all_sorted(list_md_fn, &hstate);
3564 list = hstate.list;
3565 free(hstate.seen);
3566 # else
3567 list = (char *)emalloc(sizeof("md5, others (upgrade to OpenSSL-1.0 for full list)"));
3568 strcpy(list, "md5, others (upgrade to OpenSSL-1.0 for full list)");
3569 # endif
3570 #else
3571 list = (char *)emalloc(sizeof("md5"));
3572 strcpy(list, "md5");
3573 #endif
3574
3575 return list;
3576 }
3577
3578 #define CTRLC_STACK_MAX 4
3579 static volatile size_t ctrlc_stack_len = 0;
3580 static volatile Ctrl_C_Handler ctrlc_stack[CTRLC_STACK_MAX];
3581
3582
3583
3584 int/*BOOL*/
3585 push_ctrl_c_handler(
3586 Ctrl_C_Handler func
3587 )
3588 {
3589 size_t size = ctrlc_stack_len;
3590 if (func && (size < CTRLC_STACK_MAX)) {
3591 ctrlc_stack[size] = func;
3592 ctrlc_stack_len = size + 1;
3593 return TRUE;
3594 }
3595 return FALSE;
3596 }
3597
3598 int/*BOOL*/
3599 pop_ctrl_c_handler(
3600 Ctrl_C_Handler func
3601 )
3602 {
3603 size_t size = ctrlc_stack_len;
3604 if (size) {
3605 --size;
3606 if (func == NULL || func == ctrlc_stack[size]) {
3607 ctrlc_stack_len = size;
3608 return TRUE;
3609 }
3610 }
3611 return FALSE;
3612 }
3613
3614 static void
3615 on_ctrlc(void)
3616 {
3617 size_t size = ctrlc_stack_len;
3618 while (size)
3619 if ((*ctrlc_stack[--size])())
3620 break;
3621 }
3622