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