1 /* $NetBSD: ntpdc.c,v 1.5 2012/02/01 22:48:15 kardel Exp $ */ 2 3 /* 4 * ntpdc - control and monitor your ntpd daemon 5 */ 6 7 #include <stdio.h> 8 #include <stddef.h> 9 #include <ctype.h> 10 #include <signal.h> 11 #include <setjmp.h> 12 13 #include "ntpdc.h" 14 #include "ntp_select.h" 15 #include "ntp_io.h" 16 #include "ntp_stdlib.h" 17 #include "ntp_assert.h" 18 #include "ntp_lineedit.h" 19 #include "isc/net.h" 20 #include "isc/result.h" 21 #include <ssl_applink.c> 22 23 #include "ntp_libopts.h" 24 #include "ntpdc-opts.h" 25 26 #ifdef SYS_WINNT 27 # include <Mswsock.h> 28 # include <io.h> 29 #endif /* SYS_WINNT */ 30 31 #ifdef SYS_VXWORKS 32 /* vxWorks needs mode flag -casey*/ 33 # define open(name, flags) open(name, flags, 0777) 34 # define SERVER_PORT_NUM 123 35 #endif 36 37 /* We use COMMAND as an autogen keyword */ 38 #ifdef COMMAND 39 # undef COMMAND 40 #endif 41 42 /* 43 * Because we now potentially understand a lot of commands (and 44 * it requires a lot of commands to talk to ntpd) we will run 45 * interactive if connected to a terminal. 46 */ 47 static int interactive = 0; /* set to 1 when we should prompt */ 48 static const char * prompt = "ntpdc> "; /* prompt to ask him about */ 49 50 /* 51 * Keyid used for authenticated requests. Obtained on the fly. 52 */ 53 static u_long info_auth_keyid; 54 static int keyid_entered = 0; 55 56 static int info_auth_keytype = NID_md5; /* MD5 */ 57 static size_t info_auth_hashlen = 16; /* MD5 */ 58 u_long current_time; /* needed by authkeys; not used */ 59 60 /* 61 * for get_systime() 62 */ 63 s_char sys_precision; /* local clock precision (log2 s) */ 64 65 int ntpdcmain (int, char **); 66 /* 67 * Built in command handler declarations 68 */ 69 static int openhost (const char *); 70 static int sendpkt (void *, size_t); 71 static void growpktdata (void); 72 static int getresponse (int, int, int *, int *, char **, int); 73 static int sendrequest (int, int, int, u_int, size_t, char *); 74 static void getcmds (void); 75 static RETSIGTYPE abortcmd (int); 76 static void docmd (const char *); 77 static void tokenize (const char *, char **, int *); 78 static int findcmd (char *, struct xcmd *, struct xcmd *, struct xcmd **); 79 static int getarg (char *, int, arg_v *); 80 static int getnetnum (const char *, sockaddr_u *, char *, int); 81 static void help (struct parse *, FILE *); 82 static int helpsort (const void *, const void *); 83 static void printusage (struct xcmd *, FILE *); 84 static void timeout (struct parse *, FILE *); 85 static void my_delay (struct parse *, FILE *); 86 static void host (struct parse *, FILE *); 87 static void keyid (struct parse *, FILE *); 88 static void keytype (struct parse *, FILE *); 89 static void passwd (struct parse *, FILE *); 90 static void hostnames (struct parse *, FILE *); 91 static void setdebug (struct parse *, FILE *); 92 static void quit (struct parse *, FILE *); 93 static void version (struct parse *, FILE *); 94 static void warning (const char *, ...) 95 __attribute__((__format__(__printf__, 1, 2))); 96 static void error (const char *, ...) 97 __attribute__((__format__(__printf__, 1, 2))); 98 static u_long getkeyid (const char *); 99 100 101 102 /* 103 * Built-in commands we understand 104 */ 105 static struct xcmd builtins[] = { 106 { "?", help, { OPT|NTP_STR, NO, NO, NO }, 107 { "command", "", "", "" }, 108 "tell the use and syntax of commands" }, 109 { "help", help, { OPT|NTP_STR, NO, NO, NO }, 110 { "command", "", "", "" }, 111 "tell the use and syntax of commands" }, 112 { "timeout", timeout, { OPT|NTP_UINT, NO, NO, NO }, 113 { "msec", "", "", "" }, 114 "set the primary receive time out" }, 115 { "delay", my_delay, { OPT|NTP_INT, NO, NO, NO }, 116 { "msec", "", "", "" }, 117 "set the delay added to encryption time stamps" }, 118 { "host", host, { OPT|NTP_STR, OPT|NTP_STR, NO, NO }, 119 { "-4|-6", "hostname", "", "" }, 120 "specify the host whose NTP server we talk to" }, 121 { "passwd", passwd, { OPT|NTP_STR, NO, NO, NO }, 122 { "", "", "", "" }, 123 "specify a password to use for authenticated requests"}, 124 { "hostnames", hostnames, { OPT|NTP_STR, NO, NO, NO }, 125 { "yes|no", "", "", "" }, 126 "specify whether hostnames or net numbers are printed"}, 127 { "debug", setdebug, { OPT|NTP_STR, NO, NO, NO }, 128 { "no|more|less", "", "", "" }, 129 "set/change debugging level" }, 130 { "quit", quit, { NO, NO, NO, NO }, 131 { "", "", "", "" }, 132 "exit ntpdc" }, 133 { "exit", quit, { NO, NO, NO, NO }, 134 { "", "", "", "" }, 135 "exit ntpdc" }, 136 { "keyid", keyid, { OPT|NTP_UINT, NO, NO, NO }, 137 { "key#", "", "", "" }, 138 "set/show keyid to use for authenticated requests" }, 139 { "keytype", keytype, { OPT|NTP_STR, NO, NO, NO }, 140 { "(md5|des)", "", "", "" }, 141 "set/show key authentication type for authenticated requests (des|md5)" }, 142 { "version", version, { NO, NO, NO, NO }, 143 { "", "", "", "" }, 144 "print version number" }, 145 { 0, 0, { NO, NO, NO, NO }, 146 { "", "", "", "" }, "" } 147 }; 148 149 150 /* 151 * Default values we use. 152 */ 153 #define DEFHOST "localhost" /* default host name */ 154 #define DEFTIMEOUT (5) /* 5 second time out */ 155 #define DEFSTIMEOUT (2) /* 2 second time out after first */ 156 #define DEFDELAY 0x51EB852 /* 20 milliseconds, l_fp fraction */ 157 #define LENHOSTNAME 256 /* host name is 256 characters long */ 158 #define MAXCMDS 100 /* maximum commands on cmd line */ 159 #define MAXHOSTS 200 /* maximum hosts on cmd line */ 160 #define MAXLINE 512 /* maximum line length */ 161 #define MAXTOKENS (1+1+MAXARGS+MOREARGS+2) /* maximum number of usable tokens */ 162 #define SCREENWIDTH 78 /* nominal screen width in columns */ 163 164 /* 165 * Some variables used and manipulated locally 166 */ 167 static struct sock_timeval tvout = { DEFTIMEOUT, 0 }; /* time out for reads */ 168 static struct sock_timeval tvsout = { DEFSTIMEOUT, 0 };/* secondary time out */ 169 static l_fp delay_time; /* delay time */ 170 static char currenthost[LENHOSTNAME]; /* current host name */ 171 int showhostnames = 1; /* show host names by default */ 172 173 static int ai_fam_templ; /* address family */ 174 static int ai_fam_default; /* default address family */ 175 static SOCKET sockfd; /* fd socket is opened on */ 176 static int havehost = 0; /* set to 1 when host open */ 177 int s_port = 0; 178 179 /* 180 * Holds data returned from queries. We allocate INITDATASIZE 181 * octets to begin with, increasing this as we need to. 182 */ 183 #define INITDATASIZE (sizeof(struct resp_pkt) * 16) 184 #define INCDATASIZE (sizeof(struct resp_pkt) * 8) 185 186 static char *pktdata; 187 static int pktdatasize; 188 189 /* 190 * These are used to help the magic with old and new versions of ntpd. 191 */ 192 int impl_ver = IMPL_XNTPD; 193 static int req_pkt_size = REQ_LEN_NOMAC; 194 195 /* 196 * For commands typed on the command line (with the -c option) 197 */ 198 static int numcmds = 0; 199 static const char *ccmds[MAXCMDS]; 200 #define ADDCMD(cp) if (numcmds < MAXCMDS) ccmds[numcmds++] = (cp) 201 202 /* 203 * When multiple hosts are specified. 204 */ 205 static int numhosts = 0; 206 static const char *chosts[MAXHOSTS]; 207 #define ADDHOST(cp) if (numhosts < MAXHOSTS) chosts[numhosts++] = (cp) 208 209 /* 210 * Error codes for internal use 211 */ 212 #define ERR_INCOMPLETE 16 213 #define ERR_TIMEOUT 17 214 215 /* 216 * Macro definitions we use 217 */ 218 #define ISSPACE(c) ((c) == ' ' || (c) == '\t') 219 #define ISEOL(c) ((c) == '\n' || (c) == '\r' || (c) == '\0') 220 #define STREQ(a, b) (*(a) == *(b) && strcmp((a), (b)) == 0) 221 222 /* 223 * For converting time stamps to dates 224 */ 225 #define JAN_1970 2208988800 /* 1970 - 1900 in seconds */ 226 227 /* 228 * Jump buffer for longjumping back to the command level 229 */ 230 static jmp_buf interrupt_buf; 231 static volatile int jump = 0; 232 233 /* 234 * Pointer to current output unit 235 */ 236 static FILE *current_output; 237 238 /* 239 * Command table imported from ntpdc_ops.c 240 */ 241 extern struct xcmd opcmds[]; 242 243 char *progname; 244 volatile int debug; 245 246 #ifdef NO_MAIN_ALLOWED 247 CALL(ntpdc,"ntpdc",ntpdcmain); 248 #else 249 int 250 main( 251 int argc, 252 char *argv[] 253 ) 254 { 255 return ntpdcmain(argc, argv); 256 } 257 #endif 258 259 #ifdef SYS_VXWORKS 260 void clear_globals(void) 261 { 262 showhostnames = 0; /* show host names by default */ 263 havehost = 0; /* set to 1 when host open */ 264 numcmds = 0; 265 numhosts = 0; 266 } 267 #endif 268 269 /* 270 * main - parse arguments and handle options 271 */ 272 int 273 ntpdcmain( 274 int argc, 275 char *argv[] 276 ) 277 { 278 extern int ntp_optind; 279 280 delay_time.l_ui = 0; 281 delay_time.l_uf = DEFDELAY; 282 283 #ifdef SYS_VXWORKS 284 clear_globals(); 285 taskPrioritySet(taskIdSelf(), 100 ); 286 #endif 287 288 init_lib(); /* sets up ipv4_works, ipv6_works */ 289 ssl_applink(); 290 291 /* Check to see if we have IPv6. Otherwise default to IPv4 */ 292 if (!ipv6_works) 293 ai_fam_default = AF_INET; 294 295 progname = argv[0]; 296 297 { 298 int optct = ntpOptionProcess(&ntpdcOptions, argc, argv); 299 argc -= optct; 300 argv += optct; 301 } 302 303 if (HAVE_OPT(IPV4)) 304 ai_fam_templ = AF_INET; 305 else if (HAVE_OPT(IPV6)) 306 ai_fam_templ = AF_INET6; 307 else 308 ai_fam_templ = ai_fam_default; 309 310 if (HAVE_OPT(COMMAND)) { 311 int cmdct = STACKCT_OPT( COMMAND ); 312 const char** cmds = STACKLST_OPT( COMMAND ); 313 314 while (cmdct-- > 0) { 315 ADDCMD(*cmds++); 316 } 317 } 318 319 debug = DESC(DEBUG_LEVEL).optOccCt; 320 321 if (HAVE_OPT(INTERACTIVE)) { 322 interactive = 1; 323 } 324 325 if (HAVE_OPT(NUMERIC)) { 326 showhostnames = 0; 327 } 328 329 if (HAVE_OPT(LISTPEERS)) { 330 ADDCMD("listpeers"); 331 } 332 333 if (HAVE_OPT(PEERS)) { 334 ADDCMD("peers"); 335 } 336 337 if (HAVE_OPT(SHOWPEERS)) { 338 ADDCMD("dmpeers"); 339 } 340 341 if (ntp_optind == argc) { 342 ADDHOST(DEFHOST); 343 } else { 344 for (; ntp_optind < argc; ntp_optind++) 345 ADDHOST(argv[ntp_optind]); 346 } 347 348 if (numcmds == 0 && interactive == 0 349 && isatty(fileno(stdin)) && isatty(fileno(stderr))) { 350 interactive = 1; 351 } 352 353 #if 0 354 ai_fam_templ = ai_fam_default; 355 while ((c = ntp_getopt(argc, argv, "46c:dilnps")) != EOF) 356 switch (c) { 357 case '4': 358 ai_fam_templ = AF_INET; 359 break; 360 case '6': 361 ai_fam_templ = AF_INET6; 362 break; 363 case 'c': 364 ADDCMD(ntp_optarg); 365 break; 366 case 'd': 367 ++debug; 368 break; 369 case 'i': 370 interactive = 1; 371 break; 372 case 'l': 373 ADDCMD("listpeers"); 374 break; 375 case 'n': 376 showhostnames = 0; 377 break; 378 case 'p': 379 ADDCMD("peers"); 380 break; 381 case 's': 382 ADDCMD("dmpeers"); 383 break; 384 default: 385 errflg++; 386 break; 387 } 388 389 if (errflg) { 390 (void) fprintf(stderr, 391 "usage: %s [-46dilnps] [-c cmd] host ...\n", 392 progname); 393 exit(2); 394 } 395 396 if (ntp_optind == argc) { 397 ADDHOST(DEFHOST); 398 } else { 399 for (; ntp_optind < argc; ntp_optind++) 400 ADDHOST(argv[ntp_optind]); 401 } 402 403 if (numcmds == 0 && interactive == 0 404 && isatty(fileno(stdin)) && isatty(fileno(stderr))) { 405 interactive = 1; 406 } 407 #endif 408 409 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */ 410 if (interactive) 411 (void) signal_no_reset(SIGINT, abortcmd); 412 #endif /* SYS_WINNT */ 413 414 /* 415 * Initialize the packet data buffer 416 */ 417 pktdatasize = INITDATASIZE; 418 pktdata = emalloc(INITDATASIZE); 419 420 if (numcmds == 0) { 421 (void) openhost(chosts[0]); 422 getcmds(); 423 } else { 424 int ihost; 425 int icmd; 426 427 for (ihost = 0; ihost < numhosts; ihost++) { 428 if (openhost(chosts[ihost])) 429 for (icmd = 0; icmd < numcmds; icmd++) { 430 if (numhosts > 1) 431 printf ("--- %s ---\n",chosts[ihost]); 432 docmd(ccmds[icmd]); 433 } 434 } 435 } 436 #ifdef SYS_WINNT 437 WSACleanup(); 438 #endif 439 return(0); 440 } /* main end */ 441 442 443 /* 444 * openhost - open a socket to a host 445 */ 446 static int 447 openhost( 448 const char *hname 449 ) 450 { 451 char temphost[LENHOSTNAME]; 452 int a_info, i; 453 struct addrinfo hints, *ai = NULL; 454 register const char *cp; 455 char name[LENHOSTNAME]; 456 char service[5]; 457 458 /* 459 * We need to get by the [] if they were entered 460 */ 461 462 cp = hname; 463 464 if (*cp == '[') { 465 cp++; 466 for (i = 0; *cp && *cp != ']'; cp++, i++) 467 name[i] = *cp; 468 if (*cp == ']') { 469 name[i] = '\0'; 470 hname = name; 471 } else { 472 return 0; 473 } 474 } 475 476 /* 477 * First try to resolve it as an ip address and if that fails, 478 * do a fullblown (dns) lookup. That way we only use the dns 479 * when it is needed and work around some implementations that 480 * will return an "IPv4-mapped IPv6 address" address if you 481 * give it an IPv4 address to lookup. 482 */ 483 strcpy(service, "ntp"); 484 memset((char *)&hints, 0, sizeof(struct addrinfo)); 485 hints.ai_family = ai_fam_templ; 486 hints.ai_protocol = IPPROTO_UDP; 487 hints.ai_socktype = SOCK_DGRAM; 488 hints.ai_flags = Z_AI_NUMERICHOST; 489 490 a_info = getaddrinfo(hname, service, &hints, &ai); 491 if (a_info == EAI_NONAME 492 #ifdef EAI_NODATA 493 || a_info == EAI_NODATA 494 #endif 495 ) { 496 hints.ai_flags = AI_CANONNAME; 497 #ifdef AI_ADDRCONFIG 498 hints.ai_flags |= AI_ADDRCONFIG; 499 #endif 500 a_info = getaddrinfo(hname, service, &hints, &ai); 501 } 502 /* Some older implementations don't like AI_ADDRCONFIG. */ 503 if (a_info == EAI_BADFLAGS) { 504 hints.ai_flags = AI_CANONNAME; 505 a_info = getaddrinfo(hname, service, &hints, &ai); 506 } 507 if (a_info != 0) { 508 (void) fprintf(stderr, "%s\n", gai_strerror(a_info)); 509 if (ai != NULL) 510 freeaddrinfo(ai); 511 return 0; 512 } 513 514 /* 515 * getaddrinfo() has returned without error so ai should not 516 * be NULL. 517 */ 518 NTP_INSIST(ai != NULL); 519 520 if (ai->ai_canonname == NULL) { 521 strncpy(temphost, stoa((sockaddr_u *)ai->ai_addr), 522 LENHOSTNAME); 523 temphost[LENHOSTNAME-1] = '\0'; 524 } else { 525 strncpy(temphost, ai->ai_canonname, LENHOSTNAME); 526 temphost[LENHOSTNAME-1] = '\0'; 527 } 528 529 if (debug > 2) 530 printf("Opening host %s\n", temphost); 531 532 if (havehost == 1) { 533 if (debug > 2) 534 printf("Closing old host %s\n", currenthost); 535 (void) closesocket(sockfd); 536 havehost = 0; 537 } 538 (void) strcpy(currenthost, temphost); 539 540 /* port maps to the same in both families */ 541 s_port = ((struct sockaddr_in6 *)ai->ai_addr)->sin6_port; 542 #ifdef SYS_VXWORKS 543 ((struct sockaddr_in6 *)&hostaddr)->sin6_port = htons(SERVER_PORT_NUM); 544 if (ai->ai_family == AF_INET) 545 *(struct sockaddr_in *)&hostaddr= 546 *((struct sockaddr_in *)ai->ai_addr); 547 else 548 *(struct sockaddr_in6 *)&hostaddr= 549 *((struct sockaddr_in6 *)ai->ai_addr); 550 #endif /* SYS_VXWORKS */ 551 552 #ifdef SYS_WINNT 553 { 554 int optionValue = SO_SYNCHRONOUS_NONALERT; 555 int err; 556 557 err = setsockopt(INVALID_SOCKET, SOL_SOCKET, SO_OPENTYPE, (char *)&optionValue, sizeof(optionValue)); 558 if (err != NO_ERROR) { 559 (void) fprintf(stderr, "cannot open nonoverlapped sockets\n"); 560 exit(1); 561 } 562 } 563 564 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0); 565 if (sockfd == INVALID_SOCKET) 566 error("socket"); 567 #else 568 sockfd = socket(ai->ai_family, SOCK_DGRAM, 0); 569 if (sockfd == -1) 570 error("socket"); 571 #endif /* SYS_WINNT */ 572 573 574 #ifdef NEED_RCVBUF_SLOP 575 # ifdef SO_RCVBUF 576 { 577 int rbufsize = INITDATASIZE + 2048; /* 2K for slop */ 578 579 if (setsockopt(sockfd, SOL_SOCKET, SO_RCVBUF, 580 &rbufsize, sizeof(int)) == -1) 581 error("setsockopt"); 582 } 583 # endif 584 #endif 585 586 #ifdef SYS_VXWORKS 587 if (connect(sockfd, (struct sockaddr *)&hostaddr, 588 sizeof(hostaddr)) == -1) 589 #else 590 if (connect(sockfd, (struct sockaddr *)ai->ai_addr, 591 ai->ai_addrlen) == -1) 592 #endif /* SYS_VXWORKS */ 593 error("connect"); 594 595 freeaddrinfo(ai); 596 havehost = 1; 597 req_pkt_size = REQ_LEN_NOMAC; 598 impl_ver = IMPL_XNTPD; 599 return 1; 600 } 601 602 603 /* XXX ELIMINATE sendpkt similar in ntpq.c, ntpdc.c, ntp_io.c, ntptrace.c */ 604 /* 605 * sendpkt - send a packet to the remote host 606 */ 607 static int 608 sendpkt( 609 void * xdata, 610 size_t xdatalen 611 ) 612 { 613 if (send(sockfd, xdata, xdatalen, 0) == -1) { 614 warning("write to %s failed", currenthost); 615 return -1; 616 } 617 618 return 0; 619 } 620 621 622 /* 623 * growpktdata - grow the packet data area 624 */ 625 static void 626 growpktdata(void) 627 { 628 pktdatasize += INCDATASIZE; 629 pktdata = erealloc(pktdata, (size_t)pktdatasize); 630 } 631 632 633 /* 634 * getresponse - get a (series of) response packet(s) and return the data 635 */ 636 static int 637 getresponse( 638 int implcode, 639 int reqcode, 640 int *ritems, 641 int *rsize, 642 char **rdata, 643 int esize 644 ) 645 { 646 struct resp_pkt rpkt; 647 struct sock_timeval tvo; 648 int items; 649 int i; 650 int size; 651 int datasize; 652 char *datap; 653 char *tmp_data; 654 char haveseq[MAXSEQ+1]; 655 int firstpkt; 656 int lastseq; 657 int numrecv; 658 int seq; 659 fd_set fds; 660 ssize_t n; 661 int pad; 662 663 /* 664 * This is pretty tricky. We may get between 1 and many packets 665 * back in response to the request. We peel the data out of 666 * each packet and collect it in one long block. When the last 667 * packet in the sequence is received we'll know how many we 668 * should have had. Note we use one long time out, should reconsider. 669 */ 670 *ritems = 0; 671 *rsize = 0; 672 firstpkt = 1; 673 numrecv = 0; 674 *rdata = datap = pktdata; 675 lastseq = 999; /* too big to be a sequence number */ 676 memset(haveseq, 0, sizeof(haveseq)); 677 FD_ZERO(&fds); 678 679 again: 680 if (firstpkt) 681 tvo = tvout; 682 else 683 tvo = tvsout; 684 685 FD_SET(sockfd, &fds); 686 n = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvo); 687 688 if (n == -1) { 689 warning("select fails"); 690 return -1; 691 } 692 if (n == 0) { 693 /* 694 * Timed out. Return what we have 695 */ 696 if (firstpkt) { 697 (void) fprintf(stderr, 698 "%s: timed out, nothing received\n", currenthost); 699 return ERR_TIMEOUT; 700 } else { 701 (void) fprintf(stderr, 702 "%s: timed out with incomplete data\n", 703 currenthost); 704 if (debug) { 705 printf("Received sequence numbers"); 706 for (n = 0; n <= MAXSEQ; n++) 707 if (haveseq[n]) 708 printf(" %zd,", n); 709 if (lastseq != 999) 710 printf(" last frame received\n"); 711 else 712 printf(" last frame not received\n"); 713 } 714 return ERR_INCOMPLETE; 715 } 716 } 717 718 n = recv(sockfd, (char *)&rpkt, sizeof(rpkt), 0); 719 if (n == -1) { 720 warning("read"); 721 return -1; 722 } 723 724 725 /* 726 * Check for format errors. Bug proofing. 727 */ 728 if (n < (ssize_t)RESP_HEADER_SIZE) { 729 if (debug) 730 printf("Short (%zd byte) packet received\n", n); 731 goto again; 732 } 733 if (INFO_VERSION(rpkt.rm_vn_mode) > NTP_VERSION || 734 INFO_VERSION(rpkt.rm_vn_mode) < NTP_OLDVERSION) { 735 if (debug) 736 printf("Packet received with version %d\n", 737 INFO_VERSION(rpkt.rm_vn_mode)); 738 goto again; 739 } 740 if (INFO_MODE(rpkt.rm_vn_mode) != MODE_PRIVATE) { 741 if (debug) 742 printf("Packet received with mode %d\n", 743 INFO_MODE(rpkt.rm_vn_mode)); 744 goto again; 745 } 746 if (INFO_IS_AUTH(rpkt.auth_seq)) { 747 if (debug) 748 printf("Encrypted packet received\n"); 749 goto again; 750 } 751 if (!ISRESPONSE(rpkt.rm_vn_mode)) { 752 if (debug) 753 printf("Received request packet, wanted response\n"); 754 goto again; 755 } 756 if (INFO_MBZ(rpkt.mbz_itemsize) != 0) { 757 if (debug) 758 printf("Received packet with nonzero MBZ field!\n"); 759 goto again; 760 } 761 762 /* 763 * Check implementation/request. Could be old data getting to us. 764 */ 765 if (rpkt.implementation != implcode || rpkt.request != reqcode) { 766 if (debug) 767 printf( 768 "Received implementation/request of %d/%d, wanted %d/%d", 769 rpkt.implementation, rpkt.request, 770 implcode, reqcode); 771 goto again; 772 } 773 774 /* 775 * Check the error code. If non-zero, return it. 776 */ 777 if (INFO_ERR(rpkt.err_nitems) != INFO_OKAY) { 778 if (debug && ISMORE(rpkt.rm_vn_mode)) { 779 printf("Error code %d received on not-final packet\n", 780 INFO_ERR(rpkt.err_nitems)); 781 } 782 return (int)INFO_ERR(rpkt.err_nitems); 783 } 784 785 /* 786 * Collect items and size. Make sure they make sense. 787 */ 788 items = INFO_NITEMS(rpkt.err_nitems); 789 size = INFO_ITEMSIZE(rpkt.mbz_itemsize); 790 if (esize > size) 791 pad = esize - size; 792 else 793 pad = 0; 794 datasize = items * size; 795 if ((size_t)datasize > (n-RESP_HEADER_SIZE)) { 796 if (debug) 797 printf( 798 "Received items %d, size %d (total %d), data in packet is %zu\n", 799 items, size, datasize, n-RESP_HEADER_SIZE); 800 goto again; 801 } 802 803 /* 804 * If this isn't our first packet, make sure the size matches 805 * the other ones. 806 */ 807 if (!firstpkt && esize != *rsize) { 808 if (debug) 809 printf("Received itemsize %d, previous %d\n", 810 size, *rsize); 811 goto again; 812 } 813 /* 814 * If we've received this before, +toss it 815 */ 816 seq = INFO_SEQ(rpkt.auth_seq); 817 if (haveseq[seq]) { 818 if (debug) 819 printf("Received duplicate sequence number %d\n", seq); 820 goto again; 821 } 822 haveseq[seq] = 1; 823 824 /* 825 * If this is the last in the sequence, record that. 826 */ 827 if (!ISMORE(rpkt.rm_vn_mode)) { 828 if (lastseq != 999) { 829 printf("Received second end sequence packet\n"); 830 goto again; 831 } 832 lastseq = seq; 833 } 834 835 /* 836 * So far, so good. Copy this data into the output array. 837 */ 838 if ((datap + datasize + (pad * items)) > (pktdata + pktdatasize)) { 839 int offset = datap - pktdata; 840 growpktdata(); 841 *rdata = pktdata; /* might have been realloced ! */ 842 datap = pktdata + offset; 843 } 844 /* 845 * We now move the pointer along according to size and number of 846 * items. This is so we can play nice with older implementations 847 */ 848 849 tmp_data = rpkt.data; 850 for (i = 0; i < items; i++) { 851 memcpy(datap, tmp_data, (unsigned)size); 852 tmp_data += size; 853 memset(datap + size, 0, pad); 854 datap += size + pad; 855 } 856 857 if (firstpkt) { 858 firstpkt = 0; 859 *rsize = size + pad; 860 } 861 *ritems += items; 862 863 /* 864 * Finally, check the count of received packets. If we've got them 865 * all, return 866 */ 867 ++numrecv; 868 if (numrecv <= lastseq) 869 goto again; 870 return INFO_OKAY; 871 } 872 873 874 /* 875 * sendrequest - format and send a request packet 876 * 877 * Historically, ntpdc has used a fixed-size request packet regardless 878 * of the actual payload size. When authenticating, the timestamp, key 879 * ID, and digest have been placed just before the end of the packet. 880 * With the introduction in late 2009 of support for authenticated 881 * ntpdc requests using larger 20-octet digests (vs. 16 for MD5), we 882 * come up four bytes short. 883 * 884 * To maintain interop while allowing for larger digests, the behavior 885 * is unchanged when using 16-octet digests. For larger digests, the 886 * timestamp, key ID, and digest are placed immediately following the 887 * request payload, with the overall packet size variable. ntpd can 888 * distinguish 16-octet digests by the overall request size being 889 * REQ_LEN_NOMAC + 4 + 16 with the auth bit enabled. When using a 890 * longer digest, that request size should be avoided. 891 * 892 * With the form used with 20-octet and larger digests, the timestamp, 893 * key ID, and digest are located by ntpd relative to the start of the 894 * packet, and the size of the digest is then implied by the packet 895 * size. 896 */ 897 static int 898 sendrequest( 899 int implcode, 900 int reqcode, 901 int auth, 902 u_int qitems, 903 size_t qsize, 904 char *qdata 905 ) 906 { 907 struct req_pkt qpkt; 908 size_t datasize; 909 size_t reqsize; 910 u_long key_id; 911 l_fp ts; 912 l_fp * ptstamp; 913 int maclen; 914 char * pass; 915 916 memset(&qpkt, 0, sizeof(qpkt)); 917 918 qpkt.rm_vn_mode = RM_VN_MODE(0, 0, 0); 919 qpkt.implementation = (u_char)implcode; 920 qpkt.request = (u_char)reqcode; 921 922 datasize = qitems * qsize; 923 if (datasize && qdata != NULL) { 924 memcpy(qpkt.data, qdata, datasize); 925 qpkt.err_nitems = ERR_NITEMS(0, qitems); 926 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize); 927 } else { 928 qpkt.err_nitems = ERR_NITEMS(0, 0); 929 qpkt.mbz_itemsize = MBZ_ITEMSIZE(qsize); /* allow for optional first item */ 930 } 931 932 if (!auth || (keyid_entered && info_auth_keyid == 0)) { 933 qpkt.auth_seq = AUTH_SEQ(0, 0); 934 return sendpkt(&qpkt, req_pkt_size); 935 } 936 937 if (info_auth_keyid == 0) { 938 key_id = getkeyid("Keyid: "); 939 if (!key_id) { 940 fprintf(stderr, "Invalid key identifier\n"); 941 return 1; 942 } 943 info_auth_keyid = key_id; 944 } 945 if (!authistrusted(info_auth_keyid)) { 946 pass = getpass_keytype(info_auth_keytype); 947 if ('\0' == pass[0]) { 948 fprintf(stderr, "Invalid password\n"); 949 return 1; 950 } 951 authusekey(info_auth_keyid, info_auth_keytype, 952 (u_char *)pass); 953 authtrust(info_auth_keyid, 1); 954 } 955 qpkt.auth_seq = AUTH_SEQ(1, 0); 956 if (info_auth_hashlen > 16) { 957 /* 958 * Only ntpd which expects REQ_LEN_NOMAC plus maclen 959 * octets in an authenticated request using a 16 octet 960 * digest (that is, a newer ntpd) will handle digests 961 * larger than 16 octets, so for longer digests, do 962 * not attempt to shorten the requests for downlevel 963 * ntpd compatibility. 964 */ 965 if (REQ_LEN_NOMAC != req_pkt_size) 966 return 1; 967 reqsize = REQ_LEN_HDR + datasize + sizeof(*ptstamp); 968 /* align to 32 bits */ 969 reqsize = (reqsize + 3) & ~3; 970 } else 971 reqsize = req_pkt_size; 972 ptstamp = (void *)((char *)&qpkt + reqsize); 973 ptstamp--; 974 get_systime(&ts); 975 L_ADD(&ts, &delay_time); 976 HTONL_FP(&ts, ptstamp); 977 maclen = authencrypt(info_auth_keyid, (void *)&qpkt, reqsize); 978 if (!maclen) { 979 fprintf(stderr, "Key not found\n"); 980 return 1; 981 } else if (maclen != (int)(info_auth_hashlen + sizeof(keyid_t))) { 982 fprintf(stderr, 983 "%d octet MAC, %zu expected with %zu octet digest\n", 984 maclen, (info_auth_hashlen + sizeof(keyid_t)), 985 info_auth_hashlen); 986 return 1; 987 } 988 return sendpkt(&qpkt, reqsize + maclen); 989 } 990 991 992 /* 993 * doquery - send a request and process the response 994 */ 995 int 996 doquery( 997 int implcode, 998 int reqcode, 999 int auth, 1000 int qitems, 1001 int qsize, 1002 char *qdata, 1003 int *ritems, 1004 int *rsize, 1005 char **rdata, 1006 int quiet_mask, 1007 int esize 1008 ) 1009 { 1010 int res; 1011 char junk[512]; 1012 fd_set fds; 1013 struct sock_timeval tvzero; 1014 1015 /* 1016 * Check to make sure host is open 1017 */ 1018 if (!havehost) { 1019 (void) fprintf(stderr, "***No host open, use `host' command\n"); 1020 return -1; 1021 } 1022 1023 /* 1024 * Poll the socket and clear out any pending data 1025 */ 1026 again: 1027 do { 1028 tvzero.tv_sec = tvzero.tv_usec = 0; 1029 FD_ZERO(&fds); 1030 FD_SET(sockfd, &fds); 1031 res = select(sockfd+1, &fds, (fd_set *)0, (fd_set *)0, &tvzero); 1032 1033 if (res == -1) { 1034 warning("polling select"); 1035 return -1; 1036 } else if (res > 0) 1037 1038 (void) recv(sockfd, junk, sizeof junk, 0); 1039 } while (res > 0); 1040 1041 1042 /* 1043 * send a request 1044 */ 1045 res = sendrequest(implcode, reqcode, auth, qitems, qsize, qdata); 1046 if (res != 0) 1047 return res; 1048 1049 /* 1050 * Get the response. If we got a standard error, print a message 1051 */ 1052 res = getresponse(implcode, reqcode, ritems, rsize, rdata, esize); 1053 1054 /* 1055 * Try to be compatible with older implementations of ntpd. 1056 */ 1057 if (res == INFO_ERR_FMT && req_pkt_size != 48) { 1058 int oldsize; 1059 1060 oldsize = req_pkt_size; 1061 1062 switch(req_pkt_size) { 1063 case REQ_LEN_NOMAC: 1064 req_pkt_size = 160; 1065 break; 1066 case 160: 1067 req_pkt_size = 48; 1068 break; 1069 } 1070 if (impl_ver == IMPL_XNTPD) { 1071 fprintf(stderr, 1072 "***Warning changing to older implementation\n"); 1073 return INFO_ERR_IMPL; 1074 } 1075 1076 fprintf(stderr, 1077 "***Warning changing the request packet size from %d to %d\n", 1078 oldsize, req_pkt_size); 1079 goto again; 1080 } 1081 1082 /* log error message if not told to be quiet */ 1083 if ((res > 0) && (((1 << res) & quiet_mask) == 0)) { 1084 switch(res) { 1085 case INFO_ERR_IMPL: 1086 /* Give us a chance to try the older implementation. */ 1087 if (implcode == IMPL_XNTPD) 1088 break; 1089 (void) fprintf(stderr, 1090 "***Server implementation incompatable with our own\n"); 1091 break; 1092 case INFO_ERR_REQ: 1093 (void) fprintf(stderr, 1094 "***Server doesn't implement this request\n"); 1095 break; 1096 case INFO_ERR_FMT: 1097 (void) fprintf(stderr, 1098 "***Server reports a format error in the received packet (shouldn't happen)\n"); 1099 break; 1100 case INFO_ERR_NODATA: 1101 (void) fprintf(stderr, 1102 "***Server reports data not found\n"); 1103 break; 1104 case INFO_ERR_AUTH: 1105 (void) fprintf(stderr, "***Permission denied\n"); 1106 break; 1107 case ERR_TIMEOUT: 1108 (void) fprintf(stderr, "***Request timed out\n"); 1109 break; 1110 case ERR_INCOMPLETE: 1111 (void) fprintf(stderr, 1112 "***Response from server was incomplete\n"); 1113 break; 1114 default: 1115 (void) fprintf(stderr, 1116 "***Server returns unknown error code %d\n", res); 1117 break; 1118 } 1119 } 1120 return res; 1121 } 1122 1123 1124 /* 1125 * getcmds - read commands from the standard input and execute them 1126 */ 1127 static void 1128 getcmds(void) 1129 { 1130 char * line; 1131 int count; 1132 1133 ntp_readline_init(interactive ? prompt : NULL); 1134 1135 for (;;) { 1136 line = ntp_readline(&count); 1137 if (NULL == line) 1138 break; 1139 docmd(line); 1140 free(line); 1141 } 1142 1143 ntp_readline_uninit(); 1144 } 1145 1146 1147 #ifndef SYS_WINNT /* Under NT cannot handle SIGINT, WIN32 spawns a handler */ 1148 /* 1149 * abortcmd - catch interrupts and abort the current command 1150 */ 1151 static RETSIGTYPE 1152 abortcmd( 1153 int sig 1154 ) 1155 { 1156 1157 if (current_output == stdout) 1158 (void) fflush(stdout); 1159 putc('\n', stderr); 1160 (void) fflush(stderr); 1161 if (jump) longjmp(interrupt_buf, 1); 1162 } 1163 #endif /* SYS_WINNT */ 1164 1165 /* 1166 * docmd - decode the command line and execute a command 1167 */ 1168 static void 1169 docmd( 1170 const char *cmdline 1171 ) 1172 { 1173 char *tokens[1+MAXARGS+MOREARGS+2]; 1174 struct parse pcmd; 1175 int ntok; 1176 int i, ti; 1177 int rval; 1178 struct xcmd *xcmd; 1179 1180 ai_fam_templ = ai_fam_default; 1181 /* 1182 * Tokenize the command line. If nothing on it, return. 1183 */ 1184 tokenize(cmdline, tokens, &ntok); 1185 if (ntok == 0) 1186 return; 1187 1188 /* 1189 * Find the appropriate command description. 1190 */ 1191 i = findcmd(tokens[0], builtins, opcmds, &xcmd); 1192 if (i == 0) { 1193 (void) fprintf(stderr, "***Command `%s' unknown\n", 1194 tokens[0]); 1195 return; 1196 } else if (i >= 2) { 1197 (void) fprintf(stderr, "***Command `%s' ambiguous\n", 1198 tokens[0]); 1199 return; 1200 } 1201 1202 /* 1203 * Save the keyword, then walk through the arguments, interpreting 1204 * as we go. 1205 */ 1206 pcmd.keyword = tokens[0]; 1207 pcmd.nargs = 0; 1208 ti = 1; 1209 for (i = 0; i < MAXARGS && xcmd->arg[i] != NO;) { 1210 if ((i+ti) >= ntok) { 1211 if (!(xcmd->arg[i] & OPT)) { 1212 printusage(xcmd, stderr); 1213 return; 1214 } 1215 break; 1216 } 1217 if ((xcmd->arg[i] & OPT) && (*tokens[i+ti] == '>')) 1218 break; 1219 rval = getarg(tokens[i+ti], (int)xcmd->arg[i], &pcmd.argval[i]); 1220 if (rval == -1) { 1221 ti++; 1222 continue; 1223 } 1224 if (rval == 0) 1225 return; 1226 pcmd.nargs++; 1227 i++; 1228 } 1229 1230 /* Any extra args are assumed to be "OPT|NTP_STR". */ 1231 for ( ; i < MAXARGS + MOREARGS;) { 1232 if ((i+ti) >= ntok) 1233 break; 1234 rval = getarg(tokens[i+ti], (int)(OPT|NTP_STR), &pcmd.argval[i]); 1235 if (rval == -1) { 1236 ti++; 1237 continue; 1238 } 1239 if (rval == 0) 1240 return; 1241 pcmd.nargs++; 1242 i++; 1243 } 1244 1245 i += ti; 1246 if (i < ntok && *tokens[i] == '>') { 1247 char *fname; 1248 1249 if (*(tokens[i]+1) != '\0') 1250 fname = tokens[i]+1; 1251 else if ((i+1) < ntok) 1252 fname = tokens[i+1]; 1253 else { 1254 (void) fprintf(stderr, "***No file for redirect\n"); 1255 return; 1256 } 1257 1258 current_output = fopen(fname, "w"); 1259 if (current_output == NULL) { 1260 (void) fprintf(stderr, "***Error opening %s: ", fname); 1261 perror(""); 1262 return; 1263 } 1264 } else { 1265 current_output = stdout; 1266 } 1267 1268 if (interactive && setjmp(interrupt_buf)) { 1269 return; 1270 } else { 1271 jump = 1; 1272 (xcmd->handler)(&pcmd, current_output); 1273 jump = 0; 1274 if (current_output != stdout) 1275 (void) fclose(current_output); 1276 current_output = NULL; 1277 } 1278 } 1279 1280 1281 /* 1282 * tokenize - turn a command line into tokens 1283 */ 1284 static void 1285 tokenize( 1286 const char *line, 1287 char **tokens, 1288 int *ntok 1289 ) 1290 { 1291 register const char *cp; 1292 register char *sp; 1293 static char tspace[MAXLINE]; 1294 1295 sp = tspace; 1296 cp = line; 1297 for (*ntok = 0; *ntok < MAXTOKENS; (*ntok)++) { 1298 tokens[*ntok] = sp; 1299 while (ISSPACE(*cp)) 1300 cp++; 1301 if (ISEOL(*cp)) 1302 break; 1303 do { 1304 *sp++ = *cp++; 1305 } while (!ISSPACE(*cp) && !ISEOL(*cp)); 1306 1307 *sp++ = '\0'; 1308 } 1309 } 1310 1311 1312 1313 /* 1314 * findcmd - find a command in a command description table 1315 */ 1316 static int 1317 findcmd( 1318 register char *str, 1319 struct xcmd *clist1, 1320 struct xcmd *clist2, 1321 struct xcmd **cmd 1322 ) 1323 { 1324 register struct xcmd *cl; 1325 register int clen; 1326 int nmatch; 1327 struct xcmd *nearmatch = NULL; 1328 struct xcmd *clist; 1329 1330 clen = strlen(str); 1331 nmatch = 0; 1332 if (clist1 != 0) 1333 clist = clist1; 1334 else if (clist2 != 0) 1335 clist = clist2; 1336 else 1337 return 0; 1338 1339 again: 1340 for (cl = clist; cl->keyword != 0; cl++) { 1341 /* do a first character check, for efficiency */ 1342 if (*str != *(cl->keyword)) 1343 continue; 1344 if (strncmp(str, cl->keyword, (unsigned)clen) == 0) { 1345 /* 1346 * Could be extact match, could be approximate. 1347 * Is exact if the length of the keyword is the 1348 * same as the str. 1349 */ 1350 if (*((cl->keyword) + clen) == '\0') { 1351 *cmd = cl; 1352 return 1; 1353 } 1354 nmatch++; 1355 nearmatch = cl; 1356 } 1357 } 1358 1359 /* 1360 * See if there is more to do. If so, go again. Sorry about the 1361 * goto, too much looking at BSD sources... 1362 */ 1363 if (clist == clist1 && clist2 != 0) { 1364 clist = clist2; 1365 goto again; 1366 } 1367 1368 /* 1369 * If we got extactly 1 near match, use it, else return number 1370 * of matches. 1371 */ 1372 if (nmatch == 1) { 1373 *cmd = nearmatch; 1374 return 1; 1375 } 1376 return nmatch; 1377 } 1378 1379 1380 /* 1381 * getarg - interpret an argument token 1382 * 1383 * string is always set. 1384 * type is set to the decoded type. 1385 * 1386 * return: 0 - failure 1387 * 1 - success 1388 * -1 - skip to next token 1389 */ 1390 static int 1391 getarg( 1392 char *str, 1393 int code, 1394 arg_v *argp 1395 ) 1396 { 1397 int isneg; 1398 char *cp, *np; 1399 static const char *digits = "0123456789"; 1400 1401 memset(argp, 0, sizeof(*argp)); 1402 1403 argp->string = str; 1404 argp->type = code & ~OPT; 1405 1406 switch (argp->type) { 1407 case NTP_STR: 1408 break; 1409 case NTP_ADD: 1410 if (!strcmp("-6", str)) { 1411 ai_fam_templ = AF_INET6; 1412 return -1; 1413 } else if (!strcmp("-4", str)) { 1414 ai_fam_templ = AF_INET; 1415 return -1; 1416 } 1417 if (!getnetnum(str, &(argp->netnum), (char *)0, 0)) { 1418 return 0; 1419 } 1420 break; 1421 case NTP_INT: 1422 case NTP_UINT: 1423 isneg = 0; 1424 np = str; 1425 if (*np == '-') { 1426 np++; 1427 isneg = 1; 1428 } 1429 1430 argp->uval = 0; 1431 do { 1432 cp = strchr(digits, *np); 1433 if (cp == NULL) { 1434 (void) fprintf(stderr, 1435 "***Illegal integer value %s\n", str); 1436 return 0; 1437 } 1438 argp->uval *= 10; 1439 argp->uval += (cp - digits); 1440 } while (*(++np) != '\0'); 1441 1442 if (isneg) { 1443 if ((code & ~OPT) == NTP_UINT) { 1444 (void) fprintf(stderr, 1445 "***Value %s should be unsigned\n", str); 1446 return 0; 1447 } 1448 argp->ival = -argp->ival; 1449 } 1450 break; 1451 case IP_VERSION: 1452 if (!strcmp("-6", str)) 1453 argp->ival = 6 ; 1454 else if (!strcmp("-4", str)) 1455 argp->ival = 4 ; 1456 else { 1457 (void) fprintf(stderr, 1458 "***Version must be either 4 or 6\n"); 1459 return 0; 1460 } 1461 break; 1462 } 1463 1464 return 1; 1465 } 1466 1467 1468 /* 1469 * getnetnum - given a host name, return its net number 1470 * and (optional) full name 1471 */ 1472 static int 1473 getnetnum( 1474 const char *hname, 1475 sockaddr_u *num, 1476 char *fullhost, 1477 int af 1478 ) 1479 { 1480 struct addrinfo hints, *ai = NULL; 1481 1482 ZERO(hints); 1483 hints.ai_flags = AI_CANONNAME; 1484 #ifdef AI_ADDRCONFIG 1485 hints.ai_flags |= AI_ADDRCONFIG; 1486 #endif 1487 1488 /* 1489 * decodenetnum only works with addresses, but handles syntax 1490 * that getaddrinfo doesn't: [2001::1]:1234 1491 */ 1492 if (decodenetnum(hname, num)) { 1493 if (fullhost != NULL) 1494 getnameinfo(&num->sa, SOCKLEN(num), fullhost, 1495 LENHOSTNAME, NULL, 0, 0); 1496 return 1; 1497 } else if (getaddrinfo(hname, "ntp", &hints, &ai) == 0) { 1498 NTP_INSIST(sizeof(*num) >= ai->ai_addrlen); 1499 memcpy(num, ai->ai_addr, ai->ai_addrlen); 1500 if (fullhost != NULL) { 1501 if (ai->ai_canonname != NULL) { 1502 strncpy(fullhost, ai->ai_canonname, 1503 LENHOSTNAME); 1504 fullhost[LENHOSTNAME - 1] = '\0'; 1505 } else { 1506 getnameinfo(&num->sa, SOCKLEN(num), 1507 fullhost, LENHOSTNAME, NULL, 1508 0, 0); 1509 } 1510 } 1511 return 1; 1512 } 1513 fprintf(stderr, "***Can't find host %s\n", hname); 1514 1515 return 0; 1516 } 1517 1518 /* 1519 * nntohost - convert network number to host name. This routine enforces 1520 * the showhostnames setting. 1521 */ 1522 char * 1523 nntohost( 1524 sockaddr_u *netnum 1525 ) 1526 { 1527 if (!showhostnames) 1528 return stoa(netnum); 1529 1530 if (ISREFCLOCKADR(netnum)) 1531 return refnumtoa(netnum); 1532 return socktohost(netnum); 1533 } 1534 1535 1536 /* 1537 * Finally, the built in command handlers 1538 */ 1539 1540 /* 1541 * help - tell about commands, or details of a particular command 1542 */ 1543 static void 1544 help( 1545 struct parse *pcmd, 1546 FILE *fp 1547 ) 1548 { 1549 struct xcmd *xcp; 1550 char *cmd; 1551 const char *list[100]; 1552 size_t word, words; 1553 size_t row, rows; 1554 size_t col, cols; 1555 size_t length; 1556 1557 if (pcmd->nargs == 0) { 1558 words = 0; 1559 for (xcp = builtins; xcp->keyword != 0; xcp++) { 1560 if (*(xcp->keyword) != '?') 1561 list[words++] = xcp->keyword; 1562 } 1563 for (xcp = opcmds; xcp->keyword != 0; xcp++) 1564 list[words++] = xcp->keyword; 1565 1566 qsort((void *)list, (size_t)words, sizeof(list[0]), 1567 helpsort); 1568 col = 0; 1569 for (word = 0; word < words; word++) { 1570 length = strlen(list[word]); 1571 col = max(col, length); 1572 } 1573 1574 cols = SCREENWIDTH / ++col; 1575 rows = (words + cols - 1) / cols; 1576 1577 fprintf(fp, "ntpdc commands:\n"); 1578 1579 for (row = 0; row < rows; row++) { 1580 for (word = row; word < words; word += rows) 1581 fprintf(fp, "%-*.*s", (int)col, (int)col-1, list[word]); 1582 fprintf(fp, "\n"); 1583 } 1584 } else { 1585 cmd = pcmd->argval[0].string; 1586 words = findcmd(cmd, builtins, opcmds, &xcp); 1587 if (words == 0) { 1588 fprintf(stderr, 1589 "Command `%s' is unknown\n", cmd); 1590 return; 1591 } else if (words >= 2) { 1592 fprintf(stderr, 1593 "Command `%s' is ambiguous\n", cmd); 1594 return; 1595 } 1596 fprintf(fp, "function: %s\n", xcp->comment); 1597 printusage(xcp, fp); 1598 } 1599 } 1600 1601 1602 /* 1603 * helpsort - do hostname qsort comparisons 1604 */ 1605 static int 1606 helpsort( 1607 const void *t1, 1608 const void *t2 1609 ) 1610 { 1611 const char * const * name1 = t1; 1612 const char * const * name2 = t2; 1613 1614 return strcmp(*name1, *name2); 1615 } 1616 1617 1618 /* 1619 * printusage - print usage information for a command 1620 */ 1621 static void 1622 printusage( 1623 struct xcmd *xcp, 1624 FILE *fp 1625 ) 1626 { 1627 int i, opt46; 1628 1629 opt46 = 0; 1630 (void) fprintf(fp, "usage: %s", xcp->keyword); 1631 for (i = 0; i < MAXARGS && xcp->arg[i] != NO; i++) { 1632 if (opt46 == 0 && (xcp->arg[i] & ~OPT) == NTP_ADD) { 1633 (void) fprintf(fp, " [ -4|-6 ]"); 1634 opt46 = 1; 1635 } 1636 if (xcp->arg[i] & OPT) 1637 (void) fprintf(fp, " [ %s ]", xcp->desc[i]); 1638 else 1639 (void) fprintf(fp, " %s", xcp->desc[i]); 1640 } 1641 (void) fprintf(fp, "\n"); 1642 } 1643 1644 1645 /* 1646 * timeout - set time out time 1647 */ 1648 static void 1649 timeout( 1650 struct parse *pcmd, 1651 FILE *fp 1652 ) 1653 { 1654 int val; 1655 1656 if (pcmd->nargs == 0) { 1657 val = tvout.tv_sec * 1000 + tvout.tv_usec / 1000; 1658 (void) fprintf(fp, "primary timeout %d ms\n", val); 1659 } else { 1660 tvout.tv_sec = pcmd->argval[0].uval / 1000; 1661 tvout.tv_usec = (pcmd->argval[0].uval - (tvout.tv_sec * 1000)) 1662 * 1000; 1663 } 1664 } 1665 1666 1667 /* 1668 * my_delay - set delay for auth requests 1669 */ 1670 static void 1671 my_delay( 1672 struct parse *pcmd, 1673 FILE *fp 1674 ) 1675 { 1676 int isneg; 1677 u_long val; 1678 1679 if (pcmd->nargs == 0) { 1680 val = delay_time.l_ui * 1000 + delay_time.l_uf / 4294967; 1681 (void) fprintf(fp, "delay %lu ms\n", val); 1682 } else { 1683 if (pcmd->argval[0].ival < 0) { 1684 isneg = 1; 1685 val = (u_long)(-pcmd->argval[0].ival); 1686 } else { 1687 isneg = 0; 1688 val = (u_long)pcmd->argval[0].ival; 1689 } 1690 1691 delay_time.l_ui = val / 1000; 1692 val %= 1000; 1693 delay_time.l_uf = val * 4294967; /* 2**32/1000 */ 1694 1695 if (isneg) 1696 L_NEG(&delay_time); 1697 } 1698 } 1699 1700 1701 /* 1702 * host - set the host we are dealing with. 1703 */ 1704 static void 1705 host( 1706 struct parse *pcmd, 1707 FILE *fp 1708 ) 1709 { 1710 int i; 1711 1712 if (pcmd->nargs == 0) { 1713 if (havehost) 1714 (void) fprintf(fp, "current host is %s\n", currenthost); 1715 else 1716 (void) fprintf(fp, "no current host\n"); 1717 return; 1718 } 1719 1720 i = 0; 1721 if (pcmd->nargs == 2) { 1722 if (!strcmp("-4", pcmd->argval[i].string)) 1723 ai_fam_templ = AF_INET; 1724 else if (!strcmp("-6", pcmd->argval[i].string)) 1725 ai_fam_templ = AF_INET6; 1726 else { 1727 if (havehost) 1728 (void) fprintf(fp, 1729 "current host remains %s\n", currenthost); 1730 else 1731 (void) fprintf(fp, "still no current host\n"); 1732 return; 1733 } 1734 i = 1; 1735 } 1736 if (openhost(pcmd->argval[i].string)) { 1737 (void) fprintf(fp, "current host set to %s\n", currenthost); 1738 } else { 1739 if (havehost) 1740 (void) fprintf(fp, 1741 "current host remains %s\n", currenthost); 1742 else 1743 (void) fprintf(fp, "still no current host\n"); 1744 } 1745 } 1746 1747 1748 /* 1749 * keyid - get a keyid to use for authenticating requests 1750 */ 1751 static void 1752 keyid( 1753 struct parse *pcmd, 1754 FILE *fp 1755 ) 1756 { 1757 if (pcmd->nargs == 0) { 1758 if (info_auth_keyid == 0 && !keyid_entered) 1759 (void) fprintf(fp, "no keyid defined\n"); 1760 else if (info_auth_keyid == 0 && keyid_entered) 1761 (void) fprintf(fp, "no keyid will be sent\n"); 1762 else 1763 (void) fprintf(fp, "keyid is %lu\n", (u_long)info_auth_keyid); 1764 } else { 1765 info_auth_keyid = pcmd->argval[0].uval; 1766 keyid_entered = 1; 1767 } 1768 } 1769 1770 1771 /* 1772 * keytype - get type of key to use for authenticating requests 1773 */ 1774 static void 1775 keytype( 1776 struct parse *pcmd, 1777 FILE *fp 1778 ) 1779 { 1780 const char * digest_name; 1781 size_t digest_len; 1782 int key_type; 1783 1784 if (!pcmd->nargs) { 1785 fprintf(fp, "keytype is %s with %lu octet digests\n", 1786 keytype_name(info_auth_keytype), 1787 (u_long)info_auth_hashlen); 1788 return; 1789 } 1790 1791 digest_name = pcmd->argval[0].string; 1792 digest_len = 0; 1793 key_type = keytype_from_text(digest_name, &digest_len); 1794 1795 if (!key_type) { 1796 fprintf(fp, "keytype must be 'md5'%s\n", 1797 #ifdef OPENSSL 1798 " or a digest type provided by OpenSSL"); 1799 #else 1800 ""); 1801 #endif 1802 return; 1803 } 1804 1805 info_auth_keytype = key_type; 1806 info_auth_hashlen = digest_len; 1807 } 1808 1809 1810 /* 1811 * passwd - get an authentication key 1812 */ 1813 /*ARGSUSED*/ 1814 static void 1815 passwd( 1816 struct parse *pcmd, 1817 FILE *fp 1818 ) 1819 { 1820 char *pass; 1821 1822 if (info_auth_keyid == 0) { 1823 info_auth_keyid = getkeyid("Keyid: "); 1824 if (info_auth_keyid == 0) { 1825 (void)fprintf(fp, "Keyid must be defined\n"); 1826 return; 1827 } 1828 } 1829 if (!interactive) { 1830 authusekey(info_auth_keyid, info_auth_keytype, 1831 (u_char *)pcmd->argval[0].string); 1832 authtrust(info_auth_keyid, 1); 1833 } else { 1834 pass = getpass_keytype(info_auth_keytype); 1835 if (*pass == '\0') 1836 (void) fprintf(fp, "Password unchanged\n"); 1837 else { 1838 authusekey(info_auth_keyid, info_auth_keytype, 1839 (u_char *)pass); 1840 authtrust(info_auth_keyid, 1); 1841 } 1842 } 1843 } 1844 1845 1846 /* 1847 * hostnames - set the showhostnames flag 1848 */ 1849 static void 1850 hostnames( 1851 struct parse *pcmd, 1852 FILE *fp 1853 ) 1854 { 1855 if (pcmd->nargs == 0) { 1856 if (showhostnames) 1857 (void) fprintf(fp, "hostnames being shown\n"); 1858 else 1859 (void) fprintf(fp, "hostnames not being shown\n"); 1860 } else { 1861 if (STREQ(pcmd->argval[0].string, "yes")) 1862 showhostnames = 1; 1863 else if (STREQ(pcmd->argval[0].string, "no")) 1864 showhostnames = 0; 1865 else 1866 (void)fprintf(stderr, "What?\n"); 1867 } 1868 } 1869 1870 1871 /* 1872 * setdebug - set/change debugging level 1873 */ 1874 static void 1875 setdebug( 1876 struct parse *pcmd, 1877 FILE *fp 1878 ) 1879 { 1880 if (pcmd->nargs == 0) { 1881 (void) fprintf(fp, "debug level is %d\n", debug); 1882 return; 1883 } else if (STREQ(pcmd->argval[0].string, "no")) { 1884 debug = 0; 1885 } else if (STREQ(pcmd->argval[0].string, "more")) { 1886 debug++; 1887 } else if (STREQ(pcmd->argval[0].string, "less")) { 1888 debug--; 1889 } else { 1890 (void) fprintf(fp, "What?\n"); 1891 return; 1892 } 1893 (void) fprintf(fp, "debug level set to %d\n", debug); 1894 } 1895 1896 1897 /* 1898 * quit - stop this nonsense 1899 */ 1900 /*ARGSUSED*/ 1901 static void 1902 quit( 1903 struct parse *pcmd, 1904 FILE *fp 1905 ) 1906 { 1907 if (havehost) 1908 closesocket(sockfd); 1909 exit(0); 1910 } 1911 1912 1913 /* 1914 * version - print the current version number 1915 */ 1916 /*ARGSUSED*/ 1917 static void 1918 version( 1919 struct parse *pcmd, 1920 FILE *fp 1921 ) 1922 { 1923 1924 (void) fprintf(fp, "%s\n", Version); 1925 return; 1926 } 1927 1928 1929 static void __attribute__((__format__(__printf__, 1, 0))) 1930 vwarning(const char *fmt, va_list ap) 1931 { 1932 int serrno = errno; 1933 (void) fprintf(stderr, "%s: ", progname); 1934 vfprintf(stderr, fmt, ap); 1935 (void) fprintf(stderr, ": %s", strerror(serrno)); 1936 } 1937 1938 /* 1939 * warning - print a warning message 1940 */ 1941 static void __attribute__((__format__(__printf__, 1, 2))) 1942 warning( 1943 const char *fmt, 1944 ... 1945 ) 1946 { 1947 va_list ap; 1948 va_start(ap, fmt); 1949 vwarning(fmt, ap); 1950 va_end(ap); 1951 } 1952 1953 1954 /* 1955 * error - print a message and exit 1956 */ 1957 static void __attribute__((__format__(__printf__, 1, 2))) 1958 error( 1959 const char *fmt, 1960 ... 1961 ) 1962 { 1963 va_list ap; 1964 va_start(ap, fmt); 1965 vwarning(fmt, ap); 1966 va_end(ap); 1967 exit(1); 1968 } 1969 1970 /* 1971 * getkeyid - prompt the user for a keyid to use 1972 */ 1973 static u_long 1974 getkeyid( 1975 const char *keyprompt 1976 ) 1977 { 1978 int c; 1979 FILE *fi; 1980 char pbuf[20]; 1981 size_t i; 1982 size_t ilim; 1983 1984 #ifndef SYS_WINNT 1985 if ((fi = fdopen(open("/dev/tty", 2), "r")) == NULL) 1986 #else 1987 if ((fi = _fdopen(open("CONIN$", _O_TEXT), "r")) == NULL) 1988 #endif /* SYS_WINNT */ 1989 fi = stdin; 1990 else 1991 setbuf(fi, (char *)NULL); 1992 fprintf(stderr, "%s", keyprompt); fflush(stderr); 1993 for (i = 0, ilim = COUNTOF(pbuf) - 1; 1994 i < ilim && (c = getc(fi)) != '\n' && c != EOF; 1995 ) 1996 pbuf[i++] = (char)c; 1997 pbuf[i] = '\0'; 1998 if (fi != stdin) 1999 fclose(fi); 2000 2001 return (u_long) atoi(pbuf); 2002 } 2003