2 * Copyright (c) 2009-2011 Todd C. Miller <Todd.Miller@courtesan.com>
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.
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.
19 #include <sys/types.h>
20 #include <sys/param.h>
21 #ifdef HAVE_SYS_SYSMACROS_H
22 # include <sys/sysmacros.h>
24 #include <sys/socket.h>
27 #include <sys/ioctl.h>
28 #ifdef HAVE_SYS_SELECT_H
29 # include <sys/select.h>
30 #endif /* HAVE_SYS_SELECT_H */
39 #endif /* STDC_HEADERS */
41 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
45 #endif /* HAVE_STRING_H */
48 #endif /* HAVE_STRINGS_H */
51 #endif /* HAVE_UNISTD_H */
52 #if TIME_WITH_SYS_TIME
61 #include "sudo_exec.h"
62 #include "sudo_plugin.h"
63 #include "sudo_plugin_int.h"
75 /* Compatibility with older tty systems. */
76 #if !defined(TIOCGWINSZ) && defined(TIOCGSIZE)
77 # define TIOCGWINSZ TIOCGSIZE
78 # define TIOCSWINSZ TIOCSSIZE
79 # define winsize ttysize
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)(const char *buf, unsigned int len);
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, child_pgrp;
99 static sigset_t ttyblock;
100 static struct io_buffer *iobufs;
102 static void flush_output(void);
103 static int exec_monitor(struct command_details *details, int backchannel);
104 static void exec_pty(struct command_details *detail);
105 static void sigwinch(int s);
106 static void sync_ttysize(int src, int dst);
107 static void deliver_signal(pid_t pid, int signo);
108 static int safe_close(int fd);
111 * Cleanup hook for error()/errorx()
114 cleanup(int gotsignal)
116 if (!tq_empty(&io_plugins))
117 term_restore(io_fds[SFD_USERTTY], 0);
119 selinux_restore_tty();
121 utmp_logout(slavename, 0); /* XXX - only if CD_SET_UTMP */
125 * Allocate a pty if /dev/tty is a tty.
126 * Fills in io_fds[SFD_USERTTY], io_fds[SFD_MASTER], io_fds[SFD_SLAVE]
127 * and slavename globals.
130 pty_setup(uid_t uid, const char *tty, const char *utmp_user)
132 io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
133 if (io_fds[SFD_USERTTY] != -1) {
134 if (!get_pty(&io_fds[SFD_MASTER], &io_fds[SFD_SLAVE],
135 slavename, sizeof(slavename), uid))
136 error(1, "Can't get pty");
137 /* Add entry to utmp/utmpx? */
138 if (utmp_user != NULL)
139 utmp_login(tty, slavename, io_fds[SFD_SLAVE], utmp_user);
143 /* Call I/O plugin tty input log method. */
145 log_ttyin(const char *buf, unsigned int n)
147 struct plugin_container *plugin;
151 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
153 tq_foreach_fwd(&io_plugins, plugin) {
154 if (plugin->u.io->log_ttyin) {
155 if (!plugin->u.io->log_ttyin(buf, n)) {
162 sigprocmask(SIG_SETMASK, &omask, NULL);
166 /* Call I/O plugin stdin log method. */
168 log_stdin(const char *buf, unsigned int n)
170 struct plugin_container *plugin;
174 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
176 tq_foreach_fwd(&io_plugins, plugin) {
177 if (plugin->u.io->log_stdin) {
178 if (!plugin->u.io->log_stdin(buf, n)) {
185 sigprocmask(SIG_SETMASK, &omask, NULL);
189 /* Call I/O plugin tty output log method. */
191 log_ttyout(const char *buf, unsigned int n)
193 struct plugin_container *plugin;
197 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
199 tq_foreach_fwd(&io_plugins, plugin) {
200 if (plugin->u.io->log_ttyout) {
201 if (!plugin->u.io->log_ttyout(buf, n)) {
208 sigprocmask(SIG_SETMASK, &omask, NULL);
212 /* Call I/O plugin stdout log method. */
214 log_stdout(const char *buf, unsigned int n)
216 struct plugin_container *plugin;
220 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
222 tq_foreach_fwd(&io_plugins, plugin) {
223 if (plugin->u.io->log_stdout) {
224 if (!plugin->u.io->log_stdout(buf, n)) {
231 sigprocmask(SIG_SETMASK, &omask, NULL);
235 /* Call I/O plugin stderr log method. */
237 log_stderr(const char *buf, unsigned int n)
239 struct plugin_container *plugin;
243 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
245 tq_foreach_fwd(&io_plugins, plugin) {
246 if (plugin->u.io->log_stderr) {
247 if (!plugin->u.io->log_stderr(buf, n)) {
254 sigprocmask(SIG_SETMASK, &omask, NULL);
259 * Check whether we are running in the foregroup.
260 * Updates the foreground global and does lazy init of the
261 * the pty slave as needed.
264 check_foreground(void)
266 if (io_fds[SFD_USERTTY] != -1) {
267 foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
268 if (foreground && !tty_initialized) {
269 if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
271 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
278 * Suspend sudo if the underlying command is suspended.
279 * Returns SIGCONT_FG if the child should be resume in the
280 * foreground or SIGCONT_BG if it is a background process.
283 suspend_parent(int signo)
286 int n, oldmode = ttymode, rval = 0;
292 * If we are the foreground process, just resume the child.
293 * Otherwise, re-send the signal with the handler disabled.
298 if (ttymode != TERM_RAW) {
300 n = term_raw(io_fds[SFD_USERTTY], 0);
301 } while (!n && errno == EINTR);
304 rval = SIGCONT_FG; /* resume child in foreground */
311 /* Flush any remaining output before suspending. */
314 /* Restore original tty mode before suspending. */
315 if (oldmode != TERM_COOKED) {
317 n = term_restore(io_fds[SFD_USERTTY], 0);
318 } while (!n && errno == EINTR);
321 /* Suspend self and continue child when we resume. */
322 sa.sa_handler = SIG_DFL;
323 sigaction(signo, &sa, &osa);
324 sudo_debug(8, "kill parent %d", signo);
325 if (killpg(ppgrp, signo) != 0)
326 warning("killpg(%d, %d)", ppgrp, signo);
328 /* Check foreground/background status on resume. */
332 * Only modify term if we are foreground process and either
333 * the old tty mode was not cooked or child got SIGTT{IN,OU}
335 sudo_debug(8, "parent is in %sground, ttymode %d -> %d",
336 foreground ? "fore" : "back", oldmode, ttymode);
338 if (ttymode != TERM_COOKED) {
342 n = term_raw(io_fds[SFD_USERTTY], 0);
343 } while (!n && errno == EINTR);
345 /* Background process, no access to tty. */
346 ttymode = TERM_COOKED;
350 sigaction(signo, &osa, NULL);
351 rval = ttymode == TERM_RAW ? SIGCONT_FG : SIGCONT_BG;
359 * Kill child with increasing urgency.
362 terminate_child(pid_t pid, int use_pgrp)
365 * Note that SIGCHLD will interrupt the sleep()
369 killpg(pid, SIGTERM);
371 killpg(pid, SIGKILL);
380 static struct io_buffer *
381 io_buf_new(int rfd, int wfd, int (*action)(const char *, unsigned int),
382 struct io_buffer *head)
384 struct io_buffer *iob;
386 iob = emalloc(sizeof(*iob));
387 zero_bytes(iob, sizeof(*iob));
390 iob->action = action;
396 * Read/write iobufs depending on fdsr and fdsw.
397 * Returns the number of errors.
400 perform_io(fd_set *fdsr, fd_set *fdsw, struct command_status *cstat)
402 struct io_buffer *iob;
405 for (iob = iobufs; iob; iob = iob->next) {
406 if (iob->rfd != -1 && FD_ISSET(iob->rfd, fdsr)) {
408 n = read(iob->rfd, iob->buf + iob->len,
409 sizeof(iob->buf) - iob->len);
410 } while (n == -1 && errno == EINTR);
415 if (errno != ENXIO && errno != EBADF) {
421 /* got EOF or pty has gone away */
422 safe_close(iob->rfd);
426 if (!iob->action(iob->buf + iob->len, n))
427 terminate_child(child, TRUE);
432 if (iob->wfd != -1 && FD_ISSET(iob->wfd, fdsw)) {
434 n = write(iob->wfd, iob->buf + iob->off,
435 iob->len - iob->off);
436 } while (n == -1 && errno == EINTR);
438 if (errno == EPIPE || errno == ENXIO || errno == EBADF) {
439 /* other end of pipe closed or pty revoked */
440 if (iob->rfd != -1) {
441 safe_close(iob->rfd);
444 safe_close(iob->wfd);
455 if (errors && cstat != NULL) {
456 cstat->type = CMD_ERRNO;
463 * Fork a monitor process which runs the actual command as its own child
464 * process with std{in,out,err} hooked up to the pty or pipes as appropriate.
465 * Returns the child pid.
468 fork_pty(struct command_details *details, int sv[], int *maxfd)
470 struct command_status cstat;
471 struct io_buffer *iob;
472 int io_pipe[3][2], n;
475 ppgrp = getpgrp(); /* parent's pgrp, so child can signal us */
477 zero_bytes(&sa, sizeof(sa));
478 sigemptyset(&sa.sa_mask);
480 if (io_fds[SFD_USERTTY] != -1) {
481 sa.sa_flags = SA_RESTART;
482 sa.sa_handler = sigwinch;
483 sigaction(SIGWINCH, &sa, NULL);
486 /* So we can block tty-generated signals */
487 sigemptyset(&ttyblock);
488 sigaddset(&ttyblock, SIGINT);
489 sigaddset(&ttyblock, SIGQUIT);
490 sigaddset(&ttyblock, SIGTSTP);
491 sigaddset(&ttyblock, SIGTTIN);
492 sigaddset(&ttyblock, SIGTTOU);
495 * Setup stdin/stdout/stderr for child, to be duped after forking.
497 io_fds[SFD_STDIN] = io_fds[SFD_SLAVE];
498 io_fds[SFD_STDOUT] = io_fds[SFD_SLAVE];
499 io_fds[SFD_STDERR] = io_fds[SFD_SLAVE];
501 /* Copy /dev/tty -> pty master */
502 if (io_fds[SFD_USERTTY] != -1) {
503 iobufs = io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_MASTER],
506 /* Copy pty master -> /dev/tty */
507 iobufs = io_buf_new(io_fds[SFD_MASTER], io_fds[SFD_USERTTY],
510 /* Are we the foreground process? */
511 foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
515 * If either stdin, stdout or stderr is not a tty we use a pipe
516 * to interpose ourselves instead of duping the pty fd.
518 memset(io_pipe, 0, sizeof(io_pipe));
519 if (io_fds[SFD_STDIN] == -1 || !isatty(STDIN_FILENO)) {
521 if (pipe(io_pipe[STDIN_FILENO]) != 0)
522 error(1, "unable to create pipe");
523 iobufs = io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
525 io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
527 if (io_fds[SFD_STDOUT] == -1 || !isatty(STDOUT_FILENO)) {
529 if (pipe(io_pipe[STDOUT_FILENO]) != 0)
530 error(1, "unable to create pipe");
531 iobufs = io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
533 io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
535 if (io_fds[SFD_STDERR] == -1 || !isatty(STDERR_FILENO)) {
536 if (pipe(io_pipe[STDERR_FILENO]) != 0)
537 error(1, "unable to create pipe");
538 iobufs = io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
540 io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
543 /* Job control signals to relay from parent to child. */
544 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
545 sa.sa_handler = handler;
546 sigaction(SIGTSTP, &sa, NULL);
549 /* Copy terminal attrs from user tty -> pty slave. */
550 if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
552 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
555 /* Start out in raw mode if we are not part of a pipeline. */
559 n = term_raw(io_fds[SFD_USERTTY], 0);
560 } while (!n && errno == EINTR);
562 error(1, "Can't set terminal to raw mode");
574 close(signal_pipe[0]);
575 close(signal_pipe[1]);
576 fcntl(sv[1], F_SETFD, FD_CLOEXEC);
577 if (exec_setup(details, slavename, io_fds[SFD_SLAVE]) == TRUE) {
578 /* Close the other end of the stdin/stdout/stderr pipes and exec. */
579 if (io_pipe[STDIN_FILENO][1])
580 close(io_pipe[STDIN_FILENO][1]);
581 if (io_pipe[STDOUT_FILENO][0])
582 close(io_pipe[STDOUT_FILENO][0]);
583 if (io_pipe[STDERR_FILENO][0])
584 close(io_pipe[STDERR_FILENO][0]);
585 exec_monitor(details, sv[1]);
587 cstat.type = CMD_ERRNO;
589 send(sv[1], &cstat, sizeof(cstat), 0);
593 /* Close the other end of the stdin/stdout/stderr pipes. */
594 if (io_pipe[STDIN_FILENO][0])
595 close(io_pipe[STDIN_FILENO][0]);
596 if (io_pipe[STDOUT_FILENO][1])
597 close(io_pipe[STDOUT_FILENO][1]);
598 if (io_pipe[STDERR_FILENO][1])
599 close(io_pipe[STDERR_FILENO][1]);
601 for (iob = iobufs; iob; iob = iob->next) {
602 /* Determine maxfd */
603 if (iob->rfd > *maxfd)
605 if (iob->wfd > *maxfd)
608 /* Set non-blocking mode. */
609 n = fcntl(iob->rfd, F_GETFL, 0);
610 if (n != -1 && !ISSET(n, O_NONBLOCK))
611 (void) fcntl(iob->rfd, F_SETFL, n | O_NONBLOCK);
612 n = fcntl(iob->wfd, F_GETFL, 0);
613 if (n != -1 && !ISSET(n, O_NONBLOCK))
614 (void) fcntl(iob->wfd, F_SETFL, n | O_NONBLOCK);
621 pty_close(struct command_status *cstat)
625 /* Flush any remaining output (the plugin already got it) */
626 if (io_fds[SFD_USERTTY] != -1) {
627 n = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
628 if (n != -1 && ISSET(n, O_NONBLOCK)) {
630 (void) fcntl(io_fds[SFD_USERTTY], F_SETFL, n);
635 if (io_fds[SFD_USERTTY] != -1) {
637 n = term_restore(io_fds[SFD_USERTTY], 0);
638 } while (!n && errno == EINTR);
641 /* If child was signalled, write the reason to stdout like the shell. */
642 if (cstat->type == CMD_WSTATUS && WIFSIGNALED(cstat->val)) {
643 int signo = WTERMSIG(cstat->val);
644 if (signo && signo != SIGINT && signo != SIGPIPE) {
645 const char *reason = strsignal(signo);
646 n = io_fds[SFD_USERTTY] != -1 ?
647 io_fds[SFD_USERTTY] : STDOUT_FILENO;
648 if (write(n, reason, strlen(reason)) != -1) {
649 if (WCOREDUMP(cstat->val)) {
650 if (write(n, " (core dumped)", 14) == -1)
653 if (write(n, "\n", 1) == -1)
658 utmp_logout(slavename, cstat->type == CMD_WSTATUS ? cstat->val : 0); /* XXX - only if CD_SET_UTMP */
662 * Fill in fdsr and fdsw based on the io buffers list.
663 * Called prior to select().
666 fd_set_iobs(fd_set *fdsr, fd_set *fdsw)
668 struct io_buffer *iob;
670 for (iob = iobufs; iob; iob = iob->next) {
671 if (iob->rfd == -1 && iob->wfd == -1)
673 if (iob->off == iob->len) {
674 iob->off = iob->len = 0;
675 /* Forward the EOF from reader to writer. */
676 if (iob->rfd == -1) {
677 safe_close(iob->wfd);
681 /* Don't read/write /dev/tty if we are not in the foreground. */
682 if (iob->rfd != -1 &&
683 (ttymode == TERM_RAW || iob->rfd != io_fds[SFD_USERTTY])) {
684 if (iob->len != sizeof(iob->buf))
685 FD_SET(iob->rfd, fdsr);
687 if (iob->wfd != -1 &&
688 (foreground || iob->wfd != io_fds[SFD_USERTTY])) {
689 if (iob->len > iob->off)
690 FD_SET(iob->wfd, fdsw);
696 deliver_signal(pid_t pid, int signo)
700 /* Handle signal from parent. */
701 sudo_debug(8, "signal %d from parent", signo);
704 terminate_child(pid, TRUE);
707 /* Continue in foreground, grant it controlling tty. */
709 status = tcsetpgrp(io_fds[SFD_SLAVE], child_pgrp);
710 } while (status == -1 && errno == EINTR);
711 killpg(pid, SIGCONT);
714 /* Continue in background, I take controlling tty. */
716 status = tcsetpgrp(io_fds[SFD_SLAVE], getpid());
717 } while (status == -1 && errno == EINTR);
718 killpg(pid, SIGCONT);
724 /* Relay signal to child. */
731 * Send status to parent over socketpair.
732 * Return value is the same as send(2).
735 send_status(int fd, struct command_status *cstat)
739 if (cstat->type != CMD_INVALID) {
741 n = send(fd, cstat, sizeof(*cstat), 0);
742 } while (n == -1 && errno == EINTR);
743 if (n != sizeof(*cstat)) {
744 sudo_debug(8, "unable to send status to parent: %s", strerror(errno));
746 sudo_debug(8, "sent status to parent");
748 cstat->type = CMD_INVALID; /* prevent re-sending */
754 * Wait for child status after receiving SIGCHLD.
755 * If the child was stopped, the status is send back to the parent.
756 * Otherwise, cstat is filled in but not sent.
757 * Returns TRUE if child is still alive, else FALSE.
760 handle_sigchld(int backchannel, struct command_status *cstat)
762 int status, alive = TRUE;
765 /* read child status */
767 pid = waitpid(child, &status, WUNTRACED|WNOHANG);
768 } while (pid == -1 && errno == EINTR);
770 if (cstat->type != CMD_ERRNO) {
771 cstat->type = CMD_WSTATUS;
773 if (WIFSTOPPED(status)) {
774 sudo_debug(8, "command stopped, signal %d",
777 child_pgrp = tcgetpgrp(io_fds[SFD_SLAVE]);
778 } while (child_pgrp == -1 && errno == EINTR);
779 if (send_status(backchannel, cstat) == -1)
780 return alive; /* XXX */
781 } else if (WIFSIGNALED(status)) {
782 sudo_debug(8, "command killed, signal %d",
785 sudo_debug(8, "command exited: %d",
786 WEXITSTATUS(status));
789 if (!WIFSTOPPED(status))
796 * Monitor process that creates a new session with the controlling tty,
797 * resets signal handlers and forks a child to call exec_pty().
798 * Waits for status changes from the command and relays them to the
799 * parent and relays signals from the parent to the command.
800 * Returns an error if fork(2) fails, else calls _exit(2).
803 exec_monitor(struct command_details *details, int backchannel)
805 struct command_status cstat;
809 int errpipe[2], maxfd, n, status;
813 /* Close unused fds. */
814 if (io_fds[SFD_MASTER] != -1)
815 close(io_fds[SFD_MASTER]);
816 if (io_fds[SFD_USERTTY] != -1)
817 close(io_fds[SFD_USERTTY]);
820 * We use a pipe to atomically handle signal notification within
823 if (pipe_nonblock(signal_pipe) != 0)
824 error(1, "cannot create pipe");
826 /* Reset SIGWINCH and SIGALRM. */
827 zero_bytes(&sa, sizeof(sa));
828 sigemptyset(&sa.sa_mask);
829 sa.sa_flags = SA_RESTART;
830 sa.sa_handler = SIG_DFL;
831 sigaction(SIGWINCH, &sa, NULL);
832 sigaction(SIGALRM, &sa, NULL);
834 /* Ignore any SIGTTIN or SIGTTOU we get. */
835 sa.sa_handler = SIG_IGN;
836 sigaction(SIGTTIN, &sa, NULL);
837 sigaction(SIGTTOU, &sa, NULL);
839 /* Note: HP-UX select() will not be interrupted if SA_RESTART set */
840 sa.sa_flags = SA_INTERRUPT;
841 sa.sa_handler = handler;
842 sigaction(SIGCHLD, &sa, NULL);
845 * Start a new session with the parent as the session leader
846 * and the slave pty as the controlling terminal.
847 * This allows us to be notified when the child has been suspended.
849 if (setsid() == -1) {
853 if (io_fds[SFD_SLAVE] != -1) {
855 if (ioctl(io_fds[SFD_SLAVE], TIOCSCTTY, NULL) != 0)
856 error(1, "unable to set controlling tty");
858 /* Set controlling tty by reopening slave. */
859 if ((n = open(slavename, O_RDWR)) >= 0)
865 * If stdin/stdout is not a tty, start command in the background
866 * since it might be part of a pipeline that reads from /dev/tty.
867 * In this case, we rely on the command receiving SIGTTOU or SIGTTIN
868 * when it needs access to the controlling tty.
873 /* Start command and wait for it to stop or exit */
874 if (pipe(errpipe) == -1)
875 error(1, "unable to create pipe");
878 warning("Can't fork");
882 /* We pass errno back to our parent via pipe on exec failure. */
884 close(signal_pipe[0]);
885 close(signal_pipe[1]);
887 fcntl(errpipe[1], F_SETFD, FD_CLOEXEC);
890 /* setup tty and exec command */
892 cstat.type = CMD_ERRNO;
894 if (write(errpipe[1], &cstat, sizeof(cstat)) == -1)
900 /* If any of stdin/stdout/stderr are pipes, close them in parent. */
901 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
902 close(io_fds[SFD_STDIN]);
903 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
904 close(io_fds[SFD_STDOUT]);
905 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
906 close(io_fds[SFD_STDERR]);
909 * Put child in its own process group. If we are starting the command
910 * in the foreground, assign its pgrp to the tty.
913 setpgid(child, child_pgrp);
916 status = tcsetpgrp(io_fds[SFD_SLAVE], child_pgrp);
917 } while (status == -1 && errno == EINTR);
920 /* Wait for errno on pipe, signal on backchannel or for SIGCHLD */
921 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
922 fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
923 zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
924 zero_bytes(&cstat, sizeof(cstat));
928 /* Check for signal on backchannel or errno on errpipe. */
929 FD_SET(backchannel, fdsr);
930 FD_SET(signal_pipe[0], fdsr);
931 if (errpipe[0] != -1)
932 FD_SET(errpipe[0], fdsr);
933 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
935 /* If command exited we just poll, there may be data on errpipe. */
936 n = select(maxfd + 1, fdsr, NULL, NULL, alive ? NULL : &tv);
942 error(1, "select failed");
945 if (FD_ISSET(signal_pipe[0], fdsr)) {
946 n = read(signal_pipe[0], &signo, sizeof(signo));
948 if (errno == EINTR || errno == EAGAIN)
950 warning("error reading from signal pipe");
954 * Handle SIGCHLD specially and deliver other signals
955 * directly to the child.
957 if (signo == SIGCHLD)
958 alive = handle_sigchld(backchannel, &cstat);
960 deliver_signal(child, signo);
963 if (errpipe[0] != -1 && FD_ISSET(errpipe[0], fdsr)) {
964 /* read errno or EOF from command pipe */
965 n = read(errpipe[0], &cstat, sizeof(cstat));
969 warning("error reading from pipe");
972 /* Got errno or EOF, either way we are done with errpipe. */
973 FD_CLR(errpipe[0], fdsr);
977 if (FD_ISSET(backchannel, fdsr)) {
978 struct command_status cstmp;
980 /* read command from backchannel, should be a signal */
981 n = recv(backchannel, &cstmp, sizeof(cstmp), 0);
985 warning("error reading from socketpair");
988 if (cstmp.type != CMD_SIGNO) {
989 warningx("unexpected reply type on backchannel: %d", cstmp.type);
992 deliver_signal(child, cstmp.val);
998 /* XXX An error occurred, should send an error back. */
999 kill(child, SIGKILL);
1001 /* Send parent status. */
1002 send_status(backchannel, &cstat);
1011 * Flush any output buffered in iobufs or readable from the fds.
1012 * Does not read from /dev/tty.
1017 struct io_buffer *iob;
1019 fd_set *fdsr, *fdsw;
1020 int nready, nwriters, maxfd = -1;
1022 /* Determine maxfd */
1023 for (iob = iobufs; iob; iob = iob->next) {
1024 if (iob->rfd > maxfd)
1026 if (iob->wfd > maxfd)
1032 fdsr = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1033 fdsw = (fd_set *)emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1035 zero_bytes(fdsw, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1036 zero_bytes(fdsr, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1039 for (iob = iobufs; iob; iob = iob->next) {
1040 /* Don't read from /dev/tty while flushing. */
1041 if (io_fds[SFD_USERTTY] != -1 && iob->rfd == io_fds[SFD_USERTTY])
1043 if (iob->rfd == -1 && iob->wfd == -1)
1045 if (iob->off == iob->len) {
1046 iob->off = iob->len = 0;
1047 /* Forward the EOF from reader to writer. */
1048 if (iob->rfd == -1) {
1049 safe_close(iob->wfd);
1053 if (iob->rfd != -1) {
1054 if (iob->len != sizeof(iob->buf))
1055 FD_SET(iob->rfd, fdsr);
1057 if (iob->wfd != -1) {
1058 if (iob->len > iob->off) {
1060 FD_SET(iob->wfd, fdsw);
1065 /* Don't sleep in select if there are no buffers that need writing. */
1068 nready = select(maxfd + 1, fdsr, fdsw, NULL, nwriters ? NULL : &tv);
1071 break; /* all I/O flushed */
1074 error(1, "select failed");
1076 if (perform_io(fdsr, fdsw, NULL) != 0)
1084 * Sets up std{in,out,err} and executes the actual command.
1085 * Returns only if execve() fails.
1088 exec_pty(struct command_details *details)
1090 pid_t self = getpid();
1092 /* Set child process group here too to avoid a race. */
1095 /* Wire up standard fds, note that stdout/stderr may be pipes. */
1096 if (dup2(io_fds[SFD_STDIN], STDIN_FILENO) == -1 ||
1097 dup2(io_fds[SFD_STDOUT], STDOUT_FILENO) == -1 ||
1098 dup2(io_fds[SFD_STDERR], STDERR_FILENO) == -1)
1101 /* Wait for parent to grant us the tty if we are foreground. */
1103 while (tcgetpgrp(io_fds[SFD_SLAVE]) != self)
1107 /* We have guaranteed that the slave fd is > 2 */
1108 if (io_fds[SFD_SLAVE] != -1)
1109 close(io_fds[SFD_SLAVE]);
1110 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1111 close(io_fds[SFD_STDIN]);
1112 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1113 close(io_fds[SFD_STDOUT]);
1114 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1115 close(io_fds[SFD_STDERR]);
1117 if (details->closefrom >= 0)
1118 closefrom(details->closefrom);
1120 if (ISSET(details->flags, CD_RBAC_ENABLED))
1121 selinux_execve(details->command, details->argv, details->envp);
1124 my_execve(details->command, details->argv, details->envp);
1128 * Propagates tty size change signals to pty being used by the command.
1131 sync_ttysize(int src, int dst)
1134 struct winsize wsize;
1137 if (ioctl(src, TIOCGWINSZ, &wsize) == 0) {
1138 ioctl(dst, TIOCSWINSZ, &wsize);
1139 if ((pgrp = tcgetpgrp(dst)) != -1)
1140 killpg(pgrp, SIGWINCH);
1146 * Handler for SIGWINCH in parent.
1153 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
1158 * Only close the fd if it is not /dev/tty or std{in,out,err}.
1159 * Return value is the same as send(2).
1164 /* Avoid closing /dev/tty or std{in,out,err}. */
1165 if (fd < 3 || fd == io_fds[SFD_USERTTY]) {