1 /* $NetBSD: run.c,v 1.17 2026/06/28 11:03:14 gson Exp $ */ 2 3 /* 4 * Copyright 1997 Piermont Information Systems Inc. 5 * All rights reserved. 6 * 7 * Written by Philip A. Nelson for Piermont Information Systems Inc. 8 * 9 * Redistribution and use in source and binary forms, with or without 10 * modification, are permitted provided that the following conditions 11 * are met: 12 * 1. Redistributions of source code must retain the above copyright 13 * notice, this list of conditions and the following disclaimer. 14 * 2. Redistributions in binary form must reproduce the above copyright 15 * notice, this list of conditions and the following disclaimer in the 16 * documentation and/or other materials provided with the distribution. 17 * 3. The name of Piermont Information Systems Inc. may not be used to endorse 18 * or promote products derived from this software without specific prior 19 * written permission. 20 * 21 * THIS SOFTWARE IS PROVIDED BY PIERMONT INFORMATION SYSTEMS INC. ``AS IS'' 22 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 24 * ARE DISCLAIMED. IN NO EVENT SHALL PIERMONT INFORMATION SYSTEMS INC. BE 25 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 31 * THE POSSIBILITY OF SUCH DAMAGE. 32 * 33 */ 34 35 /* run.c -- routines to interact with other programs. */ 36 37 /* XXX write return codes ignored. XXX */ 38 39 #include <errno.h> 40 #include <stdio.h> 41 #include <stdarg.h> 42 #include <stdlib.h> 43 #include <unistd.h> 44 #include <fcntl.h> 45 #include <curses.h> 46 #include <termios.h> 47 #include <dirent.h> 48 #include <util.h> 49 #include <signal.h> 50 #include <err.h> 51 #include <sys/ioctl.h> 52 #include <sys/types.h> 53 #include <sys/wait.h> 54 #include <sys/stat.h> 55 #include "defs.h" 56 57 #include "menu_defs.h" 58 #include "msg_defs.h" 59 60 #define MAXBUF 256 61 62 #if defined(DEBUG) && defined(DEBUG_SYSTEM) 63 static inline int 64 Xsystem(const char *y) 65 { 66 printf ("%s\n", y); 67 return 0; 68 } 69 #else 70 #define Xsystem(y) system(y) 71 #endif 72 73 /* 74 * local prototypes 75 */ 76 int log_flip (menudesc *, void *); 77 static int script_flip (menudesc *, void *); 78 79 #define BUFSIZE 4096 80 81 menu_ent logmenu [2] = { 82 { .opt_action=log_flip}, 83 { .opt_action=script_flip} 84 }; 85 86 static void 87 log_menu_label(menudesc *m, int opt, void *arg) 88 { 89 wprintw(m->mw, "%s: %s", 90 msg_string(opt ? MSG_Scripting : MSG_Logging), 91 msg_string((opt ? script != NULL : logfp != NULL) ? 92 MSG_On : MSG_Off)); 93 } 94 95 void 96 do_logging(void) 97 { 98 int menu_no; 99 100 menu_no = new_menu(MSG_Logging_functions, logmenu, 2, -1, 12, 101 0, 20, MC_SCROLL, NULL, log_menu_label, NULL, 102 MSG_Pick_an_option, MSG_exit_menu_generic); 103 104 if (menu_no < 0) { 105 (void)fprintf(stderr, "Dynamic menu creation failed.\n"); 106 if (logfp) 107 (void)fprintf(logfp, "Dynamic menu creation failed.\n"); 108 exit(EXIT_FAILURE); 109 } 110 process_menu(menu_no, NULL); 111 free_menu(menu_no); 112 } 113 114 int 115 /*ARGSUSED*/ 116 log_flip(menudesc *m, void *arg) 117 { 118 time_t tloc; 119 120 (void)time(&tloc); 121 if (logfp) { 122 fprintf(logfp, "Log ended at: %s\n", safectime(&tloc)); 123 fflush(logfp); 124 fclose(logfp); 125 logfp = NULL; 126 } else { 127 logfp = fopen("/tmp/sysinst.log", "a"); 128 if (logfp != NULL) { 129 fprintf(logfp, 130 "Log started at: %s\n", safectime(&tloc)); 131 fflush(logfp); 132 } else { 133 if (mainwin) { 134 msg_fmt_display(MSG_openfail, "%s%s", 135 "log file", strerror(errno)); 136 } else { 137 fprintf(stderr, "could not open /tmp/sysinst.log: %s\n", 138 strerror(errno)); 139 exit(1); 140 } 141 } 142 } 143 return(0); 144 } 145 146 static int 147 /*ARGSUSED*/ 148 script_flip(menudesc *m, void *arg) 149 { 150 time_t tloc; 151 152 (void)time(&tloc); 153 if (script) { 154 scripting_fprintf(NULL, "# Script ended at: %s\n", 155 safectime(&tloc)); 156 fflush(script); 157 fclose(script); 158 script = NULL; 159 } else { 160 script = fopen("/tmp/sysinst.sh", "w"); 161 if (script != NULL) { 162 scripting_fprintf(NULL, "#!/bin/sh\n"); 163 scripting_fprintf(NULL, "# Script started at: %s\n", 164 safectime(&tloc)); 165 fflush(script); 166 } else { 167 msg_fmt_display(MSG_openfail, "%s%s", "script file", 168 strerror(errno)); 169 } 170 } 171 return(0); 172 } 173 174 int 175 collect(int kind, char **buffer, const char *name, ...) 176 { 177 size_t nbytes; /* Number of bytes in buffer. */ 178 size_t fbytes; /* Number of bytes in file. */ 179 size_t abytes; /* allocated size of buffer */ 180 struct stat st; /* stat information. */ 181 int ch; 182 FILE *f; 183 char fileorcmd[STRSIZE]; 184 va_list ap; 185 char *cp; 186 187 va_start(ap, name); 188 vsnprintf(fileorcmd, sizeof fileorcmd, name, ap); 189 va_end(ap); 190 191 if (kind == T_FILE) { 192 /* Get the file information. */ 193 if (stat(fileorcmd, &st)) { 194 *buffer = NULL; 195 return -1; 196 } 197 fbytes = (size_t)st.st_size; 198 199 /* Open the file. */ 200 f = fopen(fileorcmd, "r"); 201 if (f == NULL) { 202 if (logfp) 203 fprintf(logfp, "%s: failed to open %s\n", 204 __func__, fileorcmd); 205 *buffer = NULL; 206 return -1; 207 } 208 } else { 209 /* Open the program. */ 210 f = popen(fileorcmd, "r"); 211 if (f == NULL) { 212 if (logfp) 213 fprintf(logfp, "%s: failed to open %s\n", 214 __func__, fileorcmd); 215 *buffer = NULL; 216 return -1; 217 } 218 fbytes = 0; 219 } 220 221 if (fbytes == 0) 222 abytes = BUFSIZE; 223 else 224 abytes = fbytes+1; 225 226 /* Allocate the buffer size. */ 227 *buffer = cp = malloc(abytes); 228 if (!cp) 229 nbytes = -1; 230 else { 231 /* Read the buffer. */ 232 nbytes = 0; 233 while ((ch = fgetc(f)) != EOF) { 234 if (nbytes >= abytes-1) { 235 if (fbytes > 0 || abytes >= 512*BUFSIZE) { 236 free(cp); 237 *buffer = cp = NULL; 238 nbytes = -1; 239 break; 240 } 241 abytes *= 2; 242 *buffer = cp = realloc(cp, abytes); 243 if (!cp) { 244 nbytes = -1; 245 break; 246 } 247 248 } 249 cp[nbytes++] = ch; 250 } 251 if (cp) 252 cp[nbytes] = 0; 253 } 254 255 if (kind == T_FILE) 256 fclose(f); 257 else 258 pclose(f); 259 260 if (nbytes <= 0 && logfp) 261 fprintf(logfp, "%s: failed for %s\n", __func__, fileorcmd); 262 263 return nbytes; 264 } 265 266 267 /* 268 * system(3), but with a debug wrapper. 269 * use only for curses sub-applications. 270 */ 271 int 272 do_system(const char *execstr) 273 { 274 register int ret; 275 276 /* 277 * The following may be more than one function call. Can't just 278 * "return Xsystem (command);" 279 */ 280 281 ret = Xsystem(execstr); 282 return (ret); 283 284 } 285 286 static char ** 287 make_argv(char *cmd) 288 { 289 char **argv = 0; 290 int argc = 0; 291 char *cp, *dp, *fn; 292 DIR *dir; 293 struct dirent *dirent; 294 int l; 295 296 for (; *cmd != 0; cmd = cp + strspn(cp, " "), argc++) { 297 if (*cmd == '\'') 298 cp = strchr(++cmd, '\''); 299 else 300 cp = strchr(cmd, ' '); 301 if (cp == NULL) 302 cp = strchr(cmd, 0); 303 argv = realloc(argv, (argc + 2) * sizeof *argv); 304 if (argv == NULL) 305 err(1, "realloc(argv) for %s", cmd); 306 asprintf(argv + argc, "%.*s", (int)(cp - cmd), cmd); 307 /* Hack to remove %xx encoded ftp password */ 308 dp = strstr(cmd, ":%"); 309 if (dp != NULL && dp < cp) { 310 for (fn = dp + 4; *fn == '%'; fn += 3) 311 continue; 312 if (*fn == '@') 313 memset(dp + 1, '*', fn - dp - 1); 314 } 315 if (*cp == '\'') 316 cp++; 317 if (cp[-1] != '*') 318 continue; 319 /* do limited filename globbing */ 320 dp = argv[argc]; 321 fn = strrchr(dp, '/'); 322 if (fn != NULL) 323 *fn = 0; 324 dir = opendir(dp); 325 if (fn != NULL) 326 *fn++ = '/'; 327 else 328 fn = dp; 329 if (dir == NULL) 330 continue; 331 l = strlen(fn) - 1; 332 while ((dirent = readdir(dir))) { 333 if (dirent->d_name[0] == '.') 334 continue; 335 if (strncmp(dirent->d_name, fn, l) != 0) 336 continue; 337 if (dp != argv[argc]) 338 argc++; 339 argv = realloc(argv, (argc + 2) * sizeof *argv); 340 if (argv == NULL) 341 err(1, "realloc(argv) for %s", cmd); 342 asprintf(argv + argc, "%.*s%s", (int)(fn - dp), dp, 343 dirent->d_name); 344 } 345 if (dp != argv[argc]) 346 free(dp); 347 closedir(dir); 348 } 349 argv[argc] = NULL; 350 return argv; 351 } 352 353 static void 354 free_argv(char **argv) 355 { 356 char **n, *a; 357 358 for (n = argv; (a = *n++);) 359 free(a); 360 free(argv); 361 } 362 363 static WINDOW * 364 show_cmd(const char *scmd, struct winsize *win) 365 { 366 WINDOW *actionwin; 367 int nrow; 368 369 wclear(stdscr); 370 clearok(stdscr, 1); 371 touchwin(stdscr); 372 refresh(); 373 374 mvaddstr(0, 4, msg_string(MSG_Status)); 375 standout(); 376 addstr(msg_string(MSG_Running)); 377 standend(); 378 mvaddstr(1, 4, msg_string(MSG_Command)); 379 standout(); 380 printw("%s", scmd); 381 standend(); 382 addstr("\n\n"); 383 hline(0, win->ws_col); 384 refresh(); 385 386 nrow = getcury(stdscr) + 1; 387 388 actionwin = subwin(stdscr, win->ws_row - nrow, win->ws_col, nrow, 0); 389 if (actionwin == NULL) { 390 fprintf(stderr, "sysinst: failed to allocate output window.\n"); 391 exit(1); 392 } 393 scrollok(actionwin, TRUE); 394 if (has_colors()) { 395 wbkgd(actionwin, getbkgd(stdscr)); 396 wattrset(actionwin, getattrs(stdscr)); 397 } 398 399 wmove(actionwin, 0, 0); 400 wrefresh(actionwin); 401 402 return actionwin; 403 } 404 405 /* 406 * launch a program inside a subwindow, and report its return status when done 407 */ 408 static int 409 launch_subwin(WINDOW **actionwin, char **args, struct winsize *win, int flags, 410 const char *scmd, const char **errstr) 411 { 412 int n, i; 413 int selectfailed; 414 int status, master, slave; 415 fd_set active_fd_set, read_fd_set; 416 pid_t child, pid; 417 char ibuf[MAXBUF]; 418 char pktdata; 419 char *cp, *ncp; 420 struct termios rtt, tt; 421 struct timeval tmo; 422 423 (void)tcgetattr(STDIN_FILENO, &tt); 424 if (openpty(&master, &slave, NULL, &tt, win) == -1) { 425 *errstr = "openpty() failed"; 426 return -1; 427 } 428 429 rtt = tt; 430 431 /* ignore tty signals until we're done with subprocess setup */ 432 ttysig_ignore = 1; 433 ioctl(master, TIOCPKT, &ttysig_ignore); 434 435 redirect_console(master, slave); 436 437 if (logfp) 438 fflush(logfp); 439 if (script) 440 fflush(script); 441 442 child = fork(); 443 switch (child) { 444 case -1: 445 ttysig_ignore = 0; 446 refresh(); 447 *errstr = "fork() failed"; 448 return -1; 449 case 0: /* child */ 450 (void)close(STDIN_FILENO); 451 /* silently stop curses */ 452 (void)close(STDOUT_FILENO); 453 (void)open("/dev/null", O_RDWR, 0); 454 dup2(STDIN_FILENO, STDOUT_FILENO); 455 endwin(); 456 (void)close(master); 457 rtt = tt; 458 rtt.c_lflag |= (ICANON|ECHO); 459 (void)tcsetattr(slave, TCSANOW, &rtt); 460 login_tty(slave); 461 if (logfp) { 462 fprintf(logfp, "executing: %s\n", scmd); 463 fclose(logfp); 464 logfp = NULL; 465 } 466 if (script) { 467 fprintf(script, "%s\n", scmd); 468 fclose(script); 469 script = NULL; 470 } 471 if (strcmp(args[0], "cd") == 0 && strcmp(args[2], "&&") == 0) { 472 target_chdir_or_die(args[1]); 473 args += 3; 474 } 475 if (flags & RUN_XFER_DIR) 476 target_chdir_or_die(xfer_dir); 477 /* 478 * If target_prefix == "", the chroot will fail, but 479 * that's ok, since we don't need it then. 480 */ 481 if (flags & RUN_CHROOT && *target_prefix() 482 && chroot(target_prefix()) != 0) 483 warn("chroot(%s) for %s", target_prefix(), *args); 484 else { 485 execvp(*args, args); 486 warn("execvp %s", *args); 487 } 488 _exit(EXIT_FAILURE); 489 // break; /* end of child */ 490 default: 491 /* 492 * parent: we've set up the subprocess. 493 * forward tty signals to its process group. 494 */ 495 ttysig_forward = child; 496 ttysig_ignore = 0; 497 break; 498 } 499 500 /* 501 * Now loop transferring program output to screen, and keyboard 502 * input to the program. 503 */ 504 505 FD_ZERO(&active_fd_set); 506 FD_SET(master, &active_fd_set); 507 FD_SET(STDIN_FILENO, &active_fd_set); 508 509 for (selectfailed = 0;;) { 510 if (selectfailed) { 511 const char mmsg[] = 512 "select(2) failed but no child died?"; 513 if (logfp) 514 (void)fprintf(logfp, mmsg); 515 errx(1, mmsg); 516 } 517 read_fd_set = active_fd_set; 518 tmo.tv_sec = flags & RUN_SILENT ? 20 : 2; 519 tmo.tv_usec = 0; 520 i = select(FD_SETSIZE, &read_fd_set, NULL, NULL, &tmo); 521 if (i == 0 && *actionwin == NULL && (flags & RUN_SILENT) == 0) 522 *actionwin = show_cmd(scmd, win); 523 if (i < 0) { 524 if (errno != EINTR) { 525 warn("select"); 526 if (logfp) 527 (void)fprintf(logfp, 528 "select failure: %s\n", 529 strerror(errno)); 530 selectfailed = 1; 531 } 532 } else for (i = 0; i < FD_SETSIZE; ++i) { 533 if (!FD_ISSET(i, &read_fd_set)) 534 continue; 535 n = read(i, ibuf, sizeof ibuf - 1); 536 if (n <= 0) { 537 if (n < 0) 538 warn("read"); 539 continue; 540 } 541 ibuf[n] = 0; 542 cp = ibuf; 543 if (i == STDIN_FILENO) { 544 (void)write(master, ibuf, (size_t)n); 545 if (!(rtt.c_lflag & ECHO)) 546 continue; 547 } else { 548 pktdata = ibuf[0]; 549 if (pktdata != 0) { 550 if (pktdata & TIOCPKT_IOCTL) 551 memcpy(&rtt, ibuf, sizeof(rtt)); 552 continue; 553 } 554 cp += 1; 555 } 556 if (*cp == 0 || flags & RUN_SILENT) 557 continue; 558 if (logfp) { 559 fprintf(logfp, "%s", cp); 560 fflush(logfp); 561 } 562 if (*actionwin == NULL) 563 *actionwin = show_cmd(scmd, win); 564 /* posix curses is braindead wrt \r\n so... */ 565 for (ncp = cp; (ncp = strstr(ncp, "\r\n")); ncp += 2) { 566 ncp[0] = '\n'; 567 ncp[1] = '\r'; 568 } 569 waddstr(*actionwin, cp); 570 wrefresh(*actionwin); 571 } 572 pid = wait4(child, &status, WNOHANG, 0); 573 if (pid == child && (WIFEXITED(status) || WIFSIGNALED(status))) 574 break; 575 } 576 close(master); 577 close(slave); 578 discard_console_output(); 579 if (logfp) 580 fflush(logfp); 581 582 /* from here on out, we take tty signals ourselves */ 583 ttysig_forward = 0; 584 585 reset_prog_mode(); 586 587 if (WIFEXITED(status)) { 588 *errstr = msg_string(MSG_Command_failed); 589 return WEXITSTATUS(status); 590 } 591 if (WIFSIGNALED(status)) { 592 *errstr = msg_string(MSG_Command_ended_on_signal); 593 return WTERMSIG(status); 594 } 595 return 0; 596 } 597 598 /* 599 * generic program runner. 600 * flags: 601 * RUN_DISPLAY display command name and output 602 * RUN_FATAL program errors are fatal 603 * RUN_CHROOT chroot to target before the exec 604 * RUN_FULLSCREEN display output only 605 * RUN_SILENT do not display program output 606 * RUN_ERROR_OK don't wait for key if program fails 607 * RUN_PROGRESS don't wait for key if program has output 608 * If both RUN_DISPLAY and RUN_SILENT are clear then the program name will 609 * be displayed as soon as it generates output. 610 * Steps are taken to collect console messages, they will be interleaved 611 * into the program output - but not upset curses. 612 */ 613 614 int 615 run_program(int flags, const char *cmd, ...) 616 { 617 va_list ap; 618 struct winsize win; 619 int ret; 620 WINDOW *actionwin = NULL; 621 char *scmd; 622 char **args; 623 const char *errstr = NULL; 624 625 va_start(ap, cmd); 626 vasprintf(&scmd, cmd, ap); 627 va_end(ap); 628 if (scmd == NULL) 629 err(1, "vasprintf(&scmd, \"%s\", ...)", cmd); 630 631 args = make_argv(scmd); 632 633 /* Make curses save tty settings */ 634 def_prog_mode(); 635 636 (void)ioctl(STDIN_FILENO, TIOCGWINSZ, &win); 637 /* Apparently, we sometimes get 0x0 back, and that's not useful */ 638 if (win.ws_row == 0) 639 win.ws_row = 24; 640 if (win.ws_col == 0) 641 win.ws_col = 80; 642 643 if ((flags & RUN_DISPLAY) != 0) { 644 if (flags & RUN_STDSCR) { 645 actionwin = stdscr; 646 wmove(stdscr, msg_row()+2, 0); 647 wrefresh(stdscr); 648 } else if (flags & RUN_FULLSCREEN) { 649 wclear(stdscr); 650 clearok(stdscr, 1); 651 touchwin(stdscr); 652 refresh(); 653 actionwin = stdscr; 654 } else { 655 actionwin = show_cmd(scmd, &win); 656 } 657 } else 658 win.ws_row -= 4; 659 660 ret = launch_subwin(&actionwin, args, &win, flags, scmd, &errstr); 661 fpurge(stdin); 662 663 /* If the command failed, show command name */ 664 if (actionwin == NULL && ret != 0 && !(flags & RUN_ERROR_OK)) 665 actionwin = show_cmd(scmd, &win); 666 667 if (actionwin != NULL) { 668 int y, x; 669 getyx(actionwin, y, x); 670 if (actionwin != stdscr) 671 mvaddstr(0, 4, msg_string(MSG_Status)); 672 if (ret != 0) { 673 if (actionwin == stdscr && x != 0) 674 addstr("\n"); 675 x = 1; /* force newline below */ 676 standout(); 677 addstr(errstr); 678 standend(); 679 } else { 680 if (actionwin != stdscr) { 681 standout(); 682 addstr(msg_string(MSG_Finished)); 683 standend(); 684 } 685 } 686 clrtoeol(); 687 refresh(); 688 if ((ret != 0 && !(flags & RUN_ERROR_OK)) || 689 (y + x != 0 && !(flags & RUN_PROGRESS))) { 690 if (actionwin != stdscr) 691 move(getbegy(actionwin) - 2, 5); 692 else if (x != 0) 693 addstr("\n"); 694 addstr(msg_string(MSG_Hit_enter_to_continue)); 695 refresh(); 696 getchar(); 697 } else { 698 if (y + x != 0) { 699 /* give user 1 second to see messages */ 700 refresh(); 701 sleep(1); 702 } 703 } 704 } 705 706 /* restore tty setting we saved earlier */ 707 reset_prog_mode(); 708 709 /* clean things up */ 710 if (actionwin != NULL) { 711 if (actionwin != stdscr) 712 delwin(actionwin); 713 if (errstr == 0 || !(flags & RUN_NO_CLEAR)) { 714 wclear(stdscr); 715 touchwin(stdscr); 716 clearok(stdscr, 1); 717 refresh(); 718 } 719 } 720 721 free(scmd); 722 free_argv(args); 723 724 if (ret != 0 && flags & RUN_FATAL) 725 exit(ret); 726 return ret; 727 } 728