another obsolete patch
[debian/sudo] / exec_pty.c
1 /*
2  * Copyright (c) 2009-2010 Todd C. Miller <Todd.Miller@courtesan.com>
3  *
4  * Permission to use, copy, modify, and distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16
17 #include <config.h>
18
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #include <sys/socket.h>
22 #include <sys/time.h>
23 #include <sys/wait.h>
24 #ifdef HAVE_TERMIOS_H
25 # include <termios.h>
26 #else
27 # include <termio.h>
28 #endif /* HAVE_TERMIOS_H */
29 #include <sys/ioctl.h>
30 #ifdef HAVE_SYS_SELECT_H
31 # include <sys/select.h>
32 #endif /* HAVE_SYS_SELECT_H */
33 #include <stdio.h>
34 #ifdef STDC_HEADERS
35 # include <stdlib.h>
36 # include <stddef.h>
37 #else
38 # ifdef HAVE_STDLIB_H
39 #  include <stdlib.h>
40 # endif
41 #endif /* STDC_HEADERS */
42 #ifdef HAVE_STRING_H
43 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
44 #  include <memory.h>
45 # endif
46 # include <string.h>
47 #endif /* HAVE_STRING_H */
48 #ifdef HAVE_STRINGS_H
49 # include <strings.h>
50 #endif /* HAVE_STRINGS_H */
51 #ifdef HAVE_UNISTD_H
52 # include <unistd.h>
53 #endif /* HAVE_UNISTD_H */
54 #if TIME_WITH_SYS_TIME
55 # include <time.h>
56 #endif
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <signal.h>
60
61 #include "sudo.h"
62 #include "sudo_exec.h"
63
64 #define SFD_STDIN       0
65 #define SFD_STDOUT      1
66 #define SFD_STDERR      2
67 #define SFD_MASTER      3
68 #define SFD_SLAVE       4
69 #define SFD_USERTTY     5
70
71 #define TERM_COOKED     0
72 #define TERM_RAW        1
73
74 /* Compatibility with older tty systems. */
75 #if !defined(TIOCGSIZE) && defined(TIOCGWINSZ)
76 # define TIOCGSIZE      TIOCGWINSZ
77 # define TIOCSSIZE      TIOCSWINSZ
78 # define ttysize        winsize
79 # define ts_cols        ws_col
80 #endif
81
82 struct io_buffer {
83     struct io_buffer *next;
84     int len; /* buffer length (how much produced) */
85     int off; /* write position (how much already consumed) */
86     int rfd;  /* reader (producer) */
87     int wfd; /* writer (consumer) */
88     int (*action) __P((const char *buf, unsigned int len));
89     char buf[16 * 1024];
90 };
91
92 static char slavename[PATH_MAX];
93 static int foreground;
94 static int io_fds[6] = { -1, -1, -1, -1, -1, -1};
95 static int pipeline = FALSE;
96 static int tty_initialized;
97 static int ttymode = TERM_COOKED;
98 static pid_t ppgrp, child;
99 static struct io_buffer *iobufs;
100
101 static void flush_output __P((void));
102 static int exec_monitor __P((const char *path, char *argv[],
103     char *envp[], int, int));
104 static void exec_pty __P((const char *path, char *argv[],
105     char *envp[], int));
106 static void sigwinch __P((int s));
107 static void sync_ttysize __P((int src, int dst));
108 static void deliver_signal __P((pid_t pid, int signo));
109 static int safe_close __P((int fd));
110
111 /*
112  * Allocate a pty if /dev/tty is a tty.
113  * Fills in io_fds[SFD_USERTTY], io_fds[SFD_MASTER], io_fds[SFD_SLAVE]
114  * and slavename globals.
115  */
116 void
117 pty_setup(uid)
118     uid_t uid;
119 {
120     io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
121     if (io_fds[SFD_USERTTY] != -1) {
122         if (!get_pty(&io_fds[SFD_MASTER], &io_fds[SFD_SLAVE],
123             slavename, sizeof(slavename), uid))
124             error(1, "Can't get pty");
125     }
126 }
127
128 /*
129  * Check whether we are running in the foregroup.
130  * Updates the foreground global and does lazy init of the
131  * the pty slave as needed.
132  */
133 static void
134 check_foreground()
135 {
136     if (io_fds[SFD_USERTTY] != -1) {
137         foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
138         if (foreground && !tty_initialized) {
139             if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
140                 tty_initialized = 1;
141                 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
142             }
143         }
144     }
145 }
146
147 /*
148  * Suspend sudo if the underlying command is suspended.
149  * Returns SIGUSR1 if the child should be resume in foreground else SIGUSR2.
150  */
151 int
152 suspend_parent(signo)
153     int signo;
154 {
155     sigaction_t sa, osa;
156     int n, oldmode = ttymode, rval = 0;
157
158     switch (signo) {
159     case SIGTTOU:
160     case SIGTTIN:
161         /*
162          * If we are the foreground process, just resume the child.
163          * Otherwise, re-send the signal with the handler disabled.
164          */
165         if (!foreground)
166             check_foreground();
167         if (foreground) {
168             if (ttymode != TERM_RAW) {
169                 do {
170                     n = term_raw(io_fds[SFD_USERTTY], 0);
171                 } while (!n && errno == EINTR);
172                 ttymode = TERM_RAW;
173             }
174             rval = SIGUSR1; /* resume child in foreground */
175             break;
176         }
177         ttymode = TERM_RAW;
178         /* FALLTHROUGH */
179     case SIGSTOP:
180     case SIGTSTP:
181         /* Flush any remaining output before suspending. */
182         flush_output();
183
184         /* Restore original tty mode before suspending. */
185         if (oldmode != TERM_COOKED) {
186             do {
187                 n = term_restore(io_fds[SFD_USERTTY], 0);
188             } while (!n && errno == EINTR);
189         }
190
191         /* Suspend self and continue child when we resume. */
192         sa.sa_handler = SIG_DFL;
193         sigaction(signo, &sa, &osa);
194         if (killpg(ppgrp, signo) != 0)
195             warning("killpg(%d, %d)", ppgrp, signo);
196
197         /* Check foreground/background status on resume. */
198         check_foreground();
199
200         /*
201          * Only modify term if we are foreground process and either
202          * the old tty mode was not cooked or child got SIGTT{IN,OU}
203          */
204         if (ttymode != TERM_COOKED) {
205             if (foreground) {
206                 /* Set raw mode. */
207                 do {
208                     n = term_raw(io_fds[SFD_USERTTY], 0);
209                 } while (!n && errno == EINTR);
210             } else {
211                 /* Background process, no access to tty. */
212                 ttymode = TERM_COOKED;
213             }
214         }
215
216         sigaction(signo, &osa, NULL);
217         rval = ttymode == TERM_RAW ? SIGUSR1 : SIGUSR2;
218         break;
219     }
220
221     return(rval);
222 }
223
224 /*
225  * Kill child with increasing urgency.
226  */
227 static void
228 terminate_child(pid, use_pgrp)
229     pid_t pid;
230     int use_pgrp;
231 {
232     /*
233      * Note that SIGCHLD will interrupt the sleep()
234      */
235     if (use_pgrp) {
236         killpg(pid, SIGHUP);
237         killpg(pid, SIGTERM);
238         sleep(2);
239         killpg(pid, SIGKILL);
240     } else {
241         kill(pid, SIGHUP);
242         kill(pid, SIGTERM);
243         sleep(2);
244         kill(pid, SIGKILL);
245     }
246 }
247
248 /*
249  * Allocate a new io_buffer struct and insert it at the head of the list.
250  * Returns the new head element.
251  */
252 static struct io_buffer *
253 io_buf_new(rfd, wfd, action, head)
254     int rfd;
255     int wfd;
256     int (*action) __P((const char *, unsigned int));
257     struct io_buffer *head;
258 {
259     struct io_buffer *iob;
260
261     iob = emalloc(sizeof(*iob));
262     zero_bytes(iob, sizeof(*iob));
263     iob->rfd = rfd;
264     iob->wfd = wfd;
265     iob->action = action;
266     iob->next = head;
267     return iob;
268 }
269
270 /*
271  * Read/write iobufs depending on fdsr and fdsw.
272  * Fills in cstat on error.
273  * Returns the number of errors.
274  */
275 int
276 perform_io(fdsr, fdsw, cstat)
277     fd_set *fdsr;
278     fd_set *fdsw;
279     struct command_status *cstat;
280 {
281     struct io_buffer *iob;
282     int n, errors = 0;
283
284     for (iob = iobufs; iob; iob = iob->next) {
285         if (iob->rfd != -1 && FD_ISSET(iob->rfd, fdsr)) {
286             do {
287                 n = read(iob->rfd, iob->buf + iob->len,
288                     sizeof(iob->buf) - iob->len);
289             } while (n == -1 && errno == EINTR);
290             switch (n) {
291                 case -1:
292                     if (errno == EAGAIN)
293                         break;
294                     if (errno != ENXIO && errno != EBADF) {
295                         errors++;
296                         break;
297                     }
298                     /* FALLTHROUGH */
299                 case 0:
300                     /* got EOF or pty has gone away */
301                     safe_close(iob->rfd);
302                     iob->rfd = -1;
303                     break;
304                 default:
305                     if (!iob->action(iob->buf + iob->len, n))
306                         terminate_child(child, TRUE);
307                     iob->len += n;
308                     break;
309             }
310         }
311         if (iob->wfd != -1 && FD_ISSET(iob->wfd, fdsw)) {
312             do {
313                 n = write(iob->wfd, iob->buf + iob->off,
314                     iob->len - iob->off);
315             } while (n == -1 && errno == EINTR);
316             if (n == -1) {
317                 if (errno == EPIPE || errno == ENXIO || errno == EBADF) {
318                     /* other end of pipe closed or pty revoked */
319                     if (iob->rfd != -1) {
320                         safe_close(iob->rfd);
321                         iob->rfd = -1;
322                     }
323                     safe_close(iob->wfd);
324                     iob->wfd = -1;
325                     continue;
326                 }
327                 if (errno != EAGAIN)
328                     errors++;
329             } else {
330                 iob->off += n;
331             }
332         }
333     }
334     if (errors && cstat != NULL) {
335         cstat->type = CMD_ERRNO;
336         cstat->val = errno;
337     }
338     return errors;
339 }
340
341 /*
342  * Fork a monitor process which runs the actual command as its own child
343  * process with std{in,out,err} hooked up to the pty or pipes as appropriate.
344  * Returns the child pid.
345  */
346 int
347 fork_pty(path, argv, envp, sv, rbac_enabled, maxfd)
348     const char *path;
349     char *argv[];
350     char *envp[];
351     int sv[2];
352     int rbac_enabled;
353     int *maxfd;
354 {
355     struct command_status cstat;
356     struct io_buffer *iob;
357     int io_pipe[3][2], n;
358     sigaction_t sa;
359
360     ppgrp = getpgrp(); /* parent's pgrp, so child can signal us */
361
362     zero_bytes(&sa, sizeof(sa));
363     sigemptyset(&sa.sa_mask);
364
365     if (io_fds[SFD_USERTTY] != -1) {
366         sa.sa_flags = SA_RESTART;
367         sa.sa_handler = sigwinch;
368         sigaction(SIGWINCH, &sa, NULL);
369     }
370
371     /*
372      * Setup stdin/stdout/stderr for child, to be duped after forking.
373      */
374     io_fds[SFD_STDIN] = io_fds[SFD_SLAVE];
375     io_fds[SFD_STDOUT] = io_fds[SFD_SLAVE];
376     io_fds[SFD_STDERR] = io_fds[SFD_SLAVE];
377
378     /* Copy /dev/tty -> pty master */
379     if (io_fds[SFD_USERTTY] != -1) {
380         iobufs = io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_MASTER],
381             log_ttyin, iobufs);
382
383         /* Copy pty master -> /dev/tty */
384         iobufs = io_buf_new(io_fds[SFD_MASTER], io_fds[SFD_USERTTY],
385             log_ttyout, iobufs);
386
387         /* Are we the foreground process? */
388         foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
389     }
390
391     /*
392      * If either stdin, stdout or stderr is not a tty we use a pipe
393      * to interpose ourselves instead of duping the pty fd.
394      */
395     memset(io_pipe, 0, sizeof(io_pipe));
396     if (io_fds[SFD_STDIN] == -1 || !isatty(STDIN_FILENO)) {
397         pipeline = TRUE;
398         if (pipe(io_pipe[STDIN_FILENO]) != 0)
399             error(1, "unable to create pipe");
400         iobufs = io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
401             log_stdin, iobufs);
402         io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
403     }
404     if (io_fds[SFD_STDOUT] == -1 || !isatty(STDOUT_FILENO)) {
405         pipeline = TRUE;
406         if (pipe(io_pipe[STDOUT_FILENO]) != 0)
407             error(1, "unable to create pipe");
408         iobufs = io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
409             log_stdout, iobufs);
410         io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
411     }
412     if (io_fds[SFD_STDERR] == -1 || !isatty(STDERR_FILENO)) {
413         if (pipe(io_pipe[STDERR_FILENO]) != 0)
414             error(1, "unable to create pipe");
415         iobufs = io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
416             log_stderr, iobufs);
417         io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
418     }
419
420     /* Job control signals to relay from parent to child. */
421     sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
422     sa.sa_handler = handler;
423     sigaction(SIGTSTP, &sa, NULL);
424
425     if (foreground) {
426         /* Copy terminal attrs from user tty -> pty slave. */
427         if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
428             tty_initialized = 1;
429             sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
430         }
431
432         /* Start out in raw mode if we are not part of a pipeline. */
433         if (!pipeline) {
434             ttymode = TERM_RAW;
435             do {
436                 n = term_raw(io_fds[SFD_USERTTY], 0);
437             } while (!n && errno == EINTR);
438             if (!n)
439                 error(1, "Can't set terminal to raw mode");
440         }
441     }
442
443     child = fork();
444     switch (child) {
445     case -1:
446         error(1, "fork");
447         break;
448     case 0:
449         /* child */
450         close(sv[0]);
451         fcntl(sv[1], F_SETFD, FD_CLOEXEC);
452         if (exec_setup(rbac_enabled, slavename, io_fds[SFD_SLAVE]) == TRUE) {
453             /* Close the other end of the stdin/stdout/stderr pipes and exec. */
454             if (io_pipe[STDIN_FILENO][1])
455                 close(io_pipe[STDIN_FILENO][1]);
456             if (io_pipe[STDOUT_FILENO][0])
457                 close(io_pipe[STDOUT_FILENO][0]);
458             if (io_pipe[STDERR_FILENO][0])
459                 close(io_pipe[STDERR_FILENO][0]);
460             exec_monitor(path, argv, envp, sv[1], rbac_enabled);
461         }
462         cstat.type = CMD_ERRNO;
463         cstat.val = errno;
464         send(sv[1], &cstat, sizeof(cstat), 0);
465         _exit(1);
466     }
467
468     /* Close the other end of the stdin/stdout/stderr pipes. */
469     if (io_pipe[STDIN_FILENO][0])
470         close(io_pipe[STDIN_FILENO][0]);
471     if (io_pipe[STDOUT_FILENO][1])
472         close(io_pipe[STDOUT_FILENO][1]);
473     if (io_pipe[STDERR_FILENO][1])
474         close(io_pipe[STDERR_FILENO][1]);
475
476     for (iob = iobufs; iob; iob = iob->next) {
477         /* Adjust maxfd. */
478         if (iob->rfd > *maxfd)
479             *maxfd = iob->rfd;
480         if (iob->wfd > *maxfd)
481             *maxfd = iob->wfd;
482
483         /* Set non-blocking mode. */
484         n = fcntl(iob->rfd, F_GETFL, 0);
485         if (n != -1 && !ISSET(n, O_NONBLOCK))
486             (void) fcntl(iob->rfd, F_SETFL, n | O_NONBLOCK);
487         n = fcntl(iob->wfd, F_GETFL, 0);
488         if (n != -1 && !ISSET(n, O_NONBLOCK))
489             (void) fcntl(iob->wfd, F_SETFL, n | O_NONBLOCK);
490     }
491
492     return child;
493 }
494
495 /*
496  * Flush any remaining output and restore /dev/tty to the way we found it.
497  * If the command died due to a signal, writes the reason to stdout.
498  */
499 void
500 pty_close(cstat)
501     struct command_status *cstat;
502 {
503     int n;
504
505     /* Flush any remaining output (the plugin already got it) */
506     if (io_fds[SFD_USERTTY] != -1) {
507         n = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
508         if (n != -1 && ISSET(n, O_NONBLOCK)) {
509             CLR(n, O_NONBLOCK);
510             (void) fcntl(io_fds[SFD_USERTTY], F_SETFL, n);
511         }
512     }
513     flush_output();
514
515     if (io_fds[SFD_USERTTY] != -1) {
516         do {
517             n = term_restore(io_fds[SFD_USERTTY], 0);
518         } while (!n && errno == EINTR);
519     }
520
521     /* If child was signalled, write the reason to stdout like the shell. */
522     if (cstat->type == CMD_WSTATUS && WIFSIGNALED(cstat->val)) {
523         int signo = WTERMSIG(cstat->val);
524         if (signo && signo != SIGINT && signo != SIGPIPE) {
525             const char *reason = strsignal(signo);
526             n = io_fds[SFD_USERTTY] != -1 ?
527                 io_fds[SFD_USERTTY] : STDOUT_FILENO;
528             write(n, reason, strlen(reason));
529             if (WCOREDUMP(cstat->val))
530                 write(n, " (core dumped)", 14);
531             write(n, "\n", 1);
532         }
533     }
534 }
535
536
537 /*
538  * Fill in fdsr and fdsw based on the io buffers list.
539  * Called prior to select().
540  */
541 void
542 fd_set_iobs(fdsr, fdsw)
543     fd_set *fdsr;
544     fd_set *fdsw;
545 {
546     struct io_buffer *iob;
547
548     for (iob = iobufs; iob; iob = iob->next) {
549         if (iob->rfd == -1 && iob->wfd == -1)
550             continue;
551         if (iob->off == iob->len) {
552             iob->off = iob->len = 0;
553             /* Forward the EOF from reader to writer. */
554             if (iob->rfd == -1) {
555                 safe_close(iob->wfd);
556                 iob->wfd = -1;
557             }
558         }
559         /* Don't read/write /dev/tty if we are not in the foreground. */
560         if (iob->rfd != -1 &&
561             (ttymode == TERM_RAW || iob->rfd != io_fds[SFD_USERTTY])) {
562             if (iob->len != sizeof(iob->buf))
563                 FD_SET(iob->rfd, fdsr);
564         }
565         if (iob->wfd != -1 &&
566             (foreground || iob->wfd != io_fds[SFD_USERTTY])) {
567             if (iob->len > iob->off)
568                 FD_SET(iob->wfd, fdsw);
569         }
570     }
571 }
572
573 /*
574  * Deliver a relayed signal to the command.
575  */
576 static void
577 deliver_signal(pid, signo)
578     pid_t pid;
579     int signo;
580 {
581     int status;
582
583     /* Handle signal from parent. */
584     switch (signo) {
585     case SIGKILL:
586         _exit(1); /* XXX */
587         /* NOTREACHED */
588     case SIGPIPE:
589     case SIGHUP:
590     case SIGTERM:
591     case SIGINT:
592     case SIGQUIT:
593     case SIGTSTP:
594         /* relay signal to child */
595         killpg(pid, signo);
596         break;
597     case SIGALRM:
598         terminate_child(pid, TRUE);
599         break;
600     case SIGUSR1:
601         /* foreground process, grant it controlling tty. */
602         do {
603             status = tcsetpgrp(io_fds[SFD_SLAVE], pid);
604         } while (status == -1 && errno == EINTR);
605         killpg(pid, SIGCONT);
606         break;
607     case SIGUSR2:
608         /* background process, I take controlling tty. */
609         do {
610             status = tcsetpgrp(io_fds[SFD_SLAVE], getpid());
611         } while (status == -1 && errno == EINTR);
612         killpg(pid, SIGCONT);
613         break;
614     default:
615         warningx("unexpected signal from child: %d", signo);
616         break;
617     }
618 }
619
620 /*
621  * Send status to parent over socketpair.
622  * Return value is the same as send(2).
623  */
624 static int
625 send_status(fd, cstat)
626     int fd;
627     struct command_status *cstat;
628 {
629     int n = -1;
630
631     if (cstat->type != CMD_INVALID) {
632         do {
633             n = send(fd, cstat, sizeof(*cstat), 0);
634         } while (n == -1 && errno == EINTR);
635         cstat->type = CMD_INVALID; /* prevent re-sending */
636     }
637     return n;
638 }
639
640 /*
641  * Wait for child status after receiving SIGCHLD.
642  * If the child was stopped, the status is send back to the parent.
643  * Otherwise, cstat is filled in but not sent.
644  * Returns TRUE if child is still alive, else FALSE.
645  */
646 static int
647 handle_sigchld(backchannel, cstat)
648     int backchannel;
649     struct command_status *cstat;
650 {
651     int status, alive = TRUE;
652     pid_t pid;
653
654     /* read child status */
655     do {
656         pid = waitpid(child, &status, WUNTRACED|WNOHANG);
657     } while (pid == -1 && errno == EINTR);
658     if (pid == child) {
659         if (cstat->type != CMD_ERRNO) {
660             cstat->type = CMD_WSTATUS;
661             cstat->val = status;
662             if (WIFSTOPPED(status)) {
663                 if (send_status(backchannel, cstat) == -1)
664                     return alive; /* XXX */
665             }
666         }
667         if (!WIFSTOPPED(status))
668             alive = FALSE;
669     }
670     return alive;
671 }
672
673 /*
674  * Monitor process that creates a new session with the controlling tty,
675  * resets signal handlers and forks a child to call exec_pty().
676  * Waits for status changes from the command and relays them to the
677  * parent and relays signals from the parent to the command.
678  * Returns an error if fork(2) fails, else calls _exit(2).
679  */
680 static int
681 exec_monitor(path, argv, envp, backchannel, rbac)
682     const char *path;
683     char *argv[];
684     char *envp[];
685     int backchannel;
686     int rbac;
687 {
688     struct command_status cstat;
689     struct timeval tv;
690     fd_set *fdsr;
691     sigaction_t sa;
692     int errpipe[2], maxfd, n, status;
693     int alive = TRUE;
694
695     /* Close unused fds. */
696     if (io_fds[SFD_MASTER] != -1)
697         close(io_fds[SFD_MASTER]);
698     if (io_fds[SFD_USERTTY] != -1)
699         close(io_fds[SFD_USERTTY]);
700
701     /* Reset SIGWINCH and SIGALRM. */
702     zero_bytes(&sa, sizeof(sa));
703     sigemptyset(&sa.sa_mask);
704     sa.sa_flags = SA_RESTART;
705     sa.sa_handler = SIG_DFL;
706     sigaction(SIGWINCH, &sa, NULL);
707     sigaction(SIGALRM, &sa, NULL);
708
709     /* Ignore any SIGTTIN or SIGTTOU we get. */
710     sa.sa_handler = SIG_IGN;
711     sigaction(SIGTTIN, &sa, NULL);
712     sigaction(SIGTTOU, &sa, NULL);
713
714     /* Note: HP-UX select() will not be interrupted if SA_RESTART set */
715     sa.sa_flags = SA_INTERRUPT;
716     sa.sa_handler = handler;
717     sigaction(SIGCHLD, &sa, NULL);
718
719     /*
720      * Start a new session with the parent as the session leader
721      * and the slave pty as the controlling terminal.
722      * This allows us to be notified when the child has been suspended.
723      */
724     if (setsid() == -1) {
725         warning("setsid");
726         goto bad;
727     }
728     if (io_fds[SFD_SLAVE] != -1) {
729 #ifdef TIOCSCTTY
730         if (ioctl(io_fds[SFD_SLAVE], TIOCSCTTY, NULL) != 0)
731             error(1, "unable to set controlling tty");
732 #else
733         /* Set controlling tty by reopening slave. */
734         if ((n = open(slavename, O_RDWR)) >= 0)
735             close(n);
736 #endif
737     }
738
739     /*
740      * If stdin/stdout is not a tty, start command in the background
741      * since it might be part of a pipeline that reads from /dev/tty.
742      * In this case, we rely on the command receiving SIGTTOU or SIGTTIN
743      * when it needs access to the controlling tty.
744      */
745     if (pipeline)
746         foreground = 0;
747
748     /* Start command and wait for it to stop or exit */
749     if (pipe(errpipe) == -1)
750         error(1, "unable to create pipe");
751     child = fork();
752     if (child == -1) {
753         warning("Can't fork");
754         goto bad;
755     }
756     if (child == 0) {
757         /* We pass errno back to our parent via pipe on exec failure. */
758         close(backchannel);
759         close(errpipe[0]);
760         fcntl(errpipe[1], F_SETFD, FD_CLOEXEC);
761
762         /* setup tty and exec command */
763         exec_pty(path, argv, envp, rbac);
764         cstat.type = CMD_ERRNO;
765         cstat.val = errno;
766         write(errpipe[1], &cstat, sizeof(cstat));
767         _exit(1);
768     }
769     close(errpipe[1]);
770
771     /* If any of stdin/stdout/stderr are pipes, close them in parent. */
772     if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
773         close(io_fds[SFD_STDIN]);
774     if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
775         close(io_fds[SFD_STDOUT]);
776     if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
777         close(io_fds[SFD_STDERR]);
778
779     /*
780      * Put child in its own process group.  If we are starting the command
781      * in the foreground, assign its pgrp to the tty.
782      */
783     setpgid(child, child);
784     if (foreground) {
785         do {
786             status = tcsetpgrp(io_fds[SFD_SLAVE], child);
787         } while (status == -1 && errno == EINTR);
788     }
789
790     /* Wait for errno on pipe, signal on backchannel or for SIGCHLD */
791     maxfd = MAX(errpipe[0], backchannel);
792     fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
793     zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
794     zero_bytes(&cstat, sizeof(cstat));
795     tv.tv_sec = 0;
796     tv.tv_usec = 0;
797     for (;;) {
798         /* Read child status. */
799         if (recvsig[SIGCHLD]) {
800             recvsig[SIGCHLD] = FALSE;
801             alive = handle_sigchld(backchannel, &cstat);
802         }
803
804         /* Check for signal on backchannel or errno on errpipe. */
805         FD_SET(backchannel, fdsr);
806         if (errpipe[0] != -1)
807             FD_SET(errpipe[0], fdsr);
808         maxfd = MAX(errpipe[0], backchannel);
809
810         if (recvsig[SIGCHLD])
811             continue;
812         /* If command exited we just poll, there may be data on errpipe. */
813         n = select(maxfd + 1, fdsr, NULL, NULL, alive ? NULL : &tv);
814         if (n <= 0) {
815             if (n == 0)
816                 goto done;
817             if (errno == EINTR)
818                 continue;
819             error(1, "select failed");
820         }
821
822         if (errpipe[0] != -1 && FD_ISSET(errpipe[0], fdsr)) {
823             /* read errno or EOF from command pipe */
824             n = read(errpipe[0], &cstat, sizeof(cstat));
825             if (n == -1) {
826                 if (errno == EINTR)
827                     continue;
828                 warning("error reading from pipe");
829                 goto done;
830             }
831             /* Got errno or EOF, either way we are done with errpipe. */
832             FD_CLR(errpipe[0], fdsr);
833             close(errpipe[0]);
834             errpipe[0] = -1;
835         }
836         if (FD_ISSET(backchannel, fdsr)) {
837             struct command_status cstmp;
838
839             /* read command from backchannel, should be a signal */
840             n = recv(backchannel, &cstmp, sizeof(cstmp), 0);
841             if (n == -1) {
842                 if (errno == EINTR)
843                     continue;
844                 warning("error reading from socketpair");
845                 goto done;
846             }
847             if (cstmp.type != CMD_SIGNO) {
848                 warningx("unexpected reply type on backchannel: %d", cstmp.type);
849                 continue;
850             }
851             deliver_signal(child, cstmp.val);
852         }
853     }
854
855 done:
856     if (alive) {
857         /* XXX An error occurred, should send an error back. */
858         kill(child, SIGKILL);
859     } else {
860         /* Send parent status. */
861         send_status(backchannel, &cstat);
862     }
863     _exit(1);
864
865 bad:
866     return errno;
867 }
868
869 /*
870  * Flush any output buffered in iobufs or readable from the fds.
871  * Does not read from /dev/tty.
872  */
873 static void
874 flush_output()
875 {
876     struct io_buffer *iob;
877     struct timeval tv;
878     fd_set *fdsr, *fdsw;
879     int nready, nwriters, maxfd = -1;
880
881     /* Determine maxfd */
882     for (iob = iobufs; iob; iob = iob->next) {
883         if (iob->rfd > maxfd)
884             maxfd = iob->rfd;
885         if (iob->wfd > maxfd)
886             maxfd = iob->wfd;
887     }
888     if (maxfd == -1)
889         return;
890
891     fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
892     fdsw = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
893     for (;;) {
894         zero_bytes(fdsw, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
895         zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
896
897         nwriters = 0;
898         for (iob = iobufs; iob; iob = iob->next) {
899             /* Don't read from /dev/tty while flushing. */
900             if (io_fds[SFD_USERTTY] != -1 && iob->rfd == io_fds[SFD_USERTTY])
901                 continue;
902             if (iob->rfd == -1 && iob->wfd == -1)
903                 continue;
904             if (iob->off == iob->len) {
905                 iob->off = iob->len = 0;
906                 /* Forward the EOF from reader to writer. */
907                 if (iob->rfd == -1) {
908                     safe_close(iob->wfd);
909                     iob->wfd = -1;
910                 }
911             }
912             if (iob->rfd != -1) {
913                 if (iob->len != sizeof(iob->buf))
914                     FD_SET(iob->rfd, fdsr);
915             }
916             if (iob->wfd != -1) {
917                 if (iob->len > iob->off) {
918                     nwriters++;
919                     FD_SET(iob->wfd, fdsw);
920                 }
921             }
922         }
923
924         /* Don't sleep in select if there are no buffers that need writing. */
925         tv.tv_sec = 0;
926         tv.tv_usec = 0;
927         nready = select(maxfd + 1, fdsr, fdsw, NULL, nwriters ? NULL : &tv);
928         if (nready <= 0) {
929             if (nready == 0)
930                 break; /* all I/O flushed */
931             if (errno == EINTR)
932                 continue;
933             error(1, "select failed");
934         }
935         if (perform_io(fdsr, fdsw, NULL) != 0)
936             break;
937     }
938     efree(fdsr);
939     efree(fdsw);
940 }
941
942 /*
943  * Sets up std{in,out,err} and executes the actual command.
944  * Returns only if execve() fails.
945  */
946 static void
947 exec_pty(path, argv, envp, rbac_enabled)
948     const char *path;
949     char *argv[];
950     char *envp[];
951     int rbac_enabled;
952 {
953     sigaction_t sa;
954     pid_t self = getpid();
955
956     /* Reset signal handlers. */
957     zero_bytes(&sa, sizeof(sa));
958     sigemptyset(&sa.sa_mask);
959     sa.sa_flags = SA_RESTART;
960     sa.sa_handler = SIG_DFL;
961     sigaction(SIGHUP, &sa, NULL);
962     sigaction(SIGTERM, &sa, NULL);
963     sigaction(SIGINT, &sa, NULL);
964     sigaction(SIGQUIT, &sa, NULL);
965     sigaction(SIGTSTP, &sa, NULL);
966     sigaction(SIGTTIN, &sa, NULL);
967     sigaction(SIGTTOU, &sa, NULL);
968     sigaction(SIGUSR1, &sa, NULL);
969     sigaction(SIGUSR2, &sa, NULL);
970     sigaction(SIGCHLD, &sa, NULL);
971
972     /* Set child process group here too to avoid a race. */
973     setpgid(0, self);
974
975     /* Wire up standard fds, note that stdout/stderr may be pipes. */
976     if (dup2(io_fds[SFD_STDIN], STDIN_FILENO) == -1 ||
977         dup2(io_fds[SFD_STDOUT], STDOUT_FILENO) == -1 ||
978         dup2(io_fds[SFD_STDERR], STDERR_FILENO) == -1)
979         error(1, "dup2");
980
981     /* Wait for parent to grant us the tty if we are foreground. */
982     if (foreground) {
983         while (tcgetpgrp(io_fds[SFD_SLAVE]) != self)
984             ; /* spin */
985     }
986
987     /* We have guaranteed that the slave fd is > 2 */
988     if (io_fds[SFD_SLAVE] != -1)
989         close(io_fds[SFD_SLAVE]);
990     if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
991         close(io_fds[SFD_STDIN]);
992     if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
993         close(io_fds[SFD_STDOUT]);
994     if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
995         close(io_fds[SFD_STDERR]);
996
997     closefrom(def_closefrom);
998 #ifdef HAVE_SELINUX
999     if (rbac_enabled)
1000         selinux_execve(path, argv, envp);
1001     else
1002 #endif
1003         my_execve(path, argv, envp);
1004 }
1005
1006 /*
1007  * Propagates tty size change signals to pty being used by the command.
1008  */
1009 static void
1010 sync_ttysize(src, dst)
1011     int src;
1012     int dst;
1013 {
1014 #ifdef TIOCGSIZE
1015     struct ttysize tsize;
1016     pid_t pgrp;
1017
1018     if (ioctl(src, TIOCGSIZE, &tsize) == 0) {
1019             ioctl(dst, TIOCSSIZE, &tsize);
1020             if ((pgrp = tcgetpgrp(dst)) != -1)
1021                 killpg(pgrp, SIGWINCH);
1022     }
1023 #endif
1024 }
1025
1026 /*
1027  * Handler for SIGWINCH in parent.
1028  */
1029 static void
1030 sigwinch(s)
1031     int s;
1032 {
1033     int serrno = errno;
1034
1035     sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
1036     errno = serrno;
1037 }
1038
1039 /*
1040  * Only close the fd if it is not /dev/tty or std{in,out,err}.
1041  * Return value is the same as send(2).
1042  */
1043 static int
1044 safe_close(fd)
1045     int fd;
1046 {
1047     /* Avoid closing /dev/tty or std{in,out,err}. */
1048     if (fd < 3 || fd == io_fds[SFD_USERTTY]) {
1049         errno = EINVAL;
1050         return -1;
1051     }
1052     return close(fd);
1053 }