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