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 bool (*action)(const char *buf, unsigned int len);
92 static char slavename[PATH_MAX];
93 static bool foreground, pipeline, tty_initialized;
94 static int io_fds[6] = { -1, -1, -1, -1, -1, -1};
95 static int ttymode = TERM_COOKED;
96 static pid_t ppgrp, cmnd_pgrp, mon_pgrp;
97 static sigset_t ttyblock;
98 static struct io_buffer *iobufs;
100 static void flush_output(void);
101 static int exec_monitor(struct command_details *details, int backchannel);
102 static void exec_pty(struct command_details *detail, int *errfd);
103 static void sigwinch(int s);
104 static void sync_ttysize(int src, int dst);
105 static void deliver_signal(pid_t pid, int signo, bool from_parent);
106 static int safe_close(int fd);
107 static void check_foreground(void);
110 * Cleanup hook for error()/errorx()
113 cleanup(int gotsignal)
115 debug_decl(cleanup, SUDO_DEBUG_EXEC);
117 if (!tq_empty(&io_plugins) && io_fds[SFD_USERTTY] != -1) {
120 term_restore(io_fds[SFD_USERTTY], 0);
123 selinux_restore_tty();
125 utmp_logout(slavename, 0); /* XXX - only if CD_SET_UTMP */
131 * Generic handler for signals recieved by the monitor process.
132 * The other end of signal_pipe is checked in the monitor event loop.
136 mon_handler(int s, siginfo_t *info, void *context)
138 unsigned char signo = (unsigned char)s;
141 * If the signal came from the command we ran, just ignore
142 * it since we don't want the command to indirectly kill itself.
143 * This can happen with, e.g. BSD-derived versions of reboot
144 * that call kill(-1, SIGTERM) to kill all other processes.
146 if (info != NULL && info->si_code == SI_USER && info->si_pid == cmnd_pid)
150 * The pipe is non-blocking, if we overflow the kernel's pipe
151 * buffer we drop the signal. This is not a problem in practice.
153 ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
159 unsigned char signo = (unsigned char)s;
162 * The pipe is non-blocking, if we overflow the kernel's pipe
163 * buffer we drop the signal. This is not a problem in practice.
165 ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
170 * Allocate a pty if /dev/tty is a tty.
171 * Fills in io_fds[SFD_USERTTY], io_fds[SFD_MASTER], io_fds[SFD_SLAVE]
172 * and slavename globals.
175 pty_setup(uid_t uid, const char *tty, const char *utmp_user)
177 debug_decl(pty_setup, SUDO_DEBUG_EXEC);
179 io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
180 if (io_fds[SFD_USERTTY] != -1) {
181 if (!get_pty(&io_fds[SFD_MASTER], &io_fds[SFD_SLAVE],
182 slavename, sizeof(slavename), uid))
183 error(1, _("unable to allocate pty"));
184 /* Add entry to utmp/utmpx? */
185 if (utmp_user != NULL)
186 utmp_login(tty, slavename, io_fds[SFD_SLAVE], utmp_user);
192 /* Call I/O plugin tty input log method. */
194 log_ttyin(const char *buf, unsigned int n)
196 struct plugin_container *plugin;
199 debug_decl(log_ttyin, SUDO_DEBUG_EXEC);
201 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
202 tq_foreach_fwd(&io_plugins, plugin) {
203 if (plugin->u.io->log_ttyin) {
204 if (!plugin->u.io->log_ttyin(buf, n)) {
210 sigprocmask(SIG_SETMASK, &omask, NULL);
212 debug_return_bool(rval);
215 /* Call I/O plugin stdin log method. */
217 log_stdin(const char *buf, unsigned int n)
219 struct plugin_container *plugin;
222 debug_decl(log_stdin, SUDO_DEBUG_EXEC);
224 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
225 tq_foreach_fwd(&io_plugins, plugin) {
226 if (plugin->u.io->log_stdin) {
227 if (!plugin->u.io->log_stdin(buf, n)) {
233 sigprocmask(SIG_SETMASK, &omask, NULL);
235 debug_return_bool(rval);
238 /* Call I/O plugin tty output log method. */
240 log_ttyout(const char *buf, unsigned int n)
242 struct plugin_container *plugin;
245 debug_decl(log_ttyout, SUDO_DEBUG_EXEC);
247 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
248 tq_foreach_fwd(&io_plugins, plugin) {
249 if (plugin->u.io->log_ttyout) {
250 if (!plugin->u.io->log_ttyout(buf, n)) {
256 sigprocmask(SIG_SETMASK, &omask, NULL);
258 debug_return_bool(rval);
261 /* Call I/O plugin stdout log method. */
263 log_stdout(const char *buf, unsigned int n)
265 struct plugin_container *plugin;
268 debug_decl(log_stdout, SUDO_DEBUG_EXEC);
270 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
271 tq_foreach_fwd(&io_plugins, plugin) {
272 if (plugin->u.io->log_stdout) {
273 if (!plugin->u.io->log_stdout(buf, n)) {
279 sigprocmask(SIG_SETMASK, &omask, NULL);
281 debug_return_bool(rval);
284 /* Call I/O plugin stderr log method. */
286 log_stderr(const char *buf, unsigned int n)
288 struct plugin_container *plugin;
291 debug_decl(log_stderr, SUDO_DEBUG_EXEC);
293 sigprocmask(SIG_BLOCK, &ttyblock, &omask);
294 tq_foreach_fwd(&io_plugins, plugin) {
295 if (plugin->u.io->log_stderr) {
296 if (!plugin->u.io->log_stderr(buf, n)) {
302 sigprocmask(SIG_SETMASK, &omask, NULL);
304 debug_return_bool(rval);
308 * Check whether we are running in the foregroup.
309 * Updates the foreground global and does lazy init of the
310 * the pty slave as needed.
313 check_foreground(void)
315 debug_decl(check_foreground, SUDO_DEBUG_EXEC);
317 if (io_fds[SFD_USERTTY] != -1) {
318 foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
319 if (foreground && !tty_initialized) {
320 if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
321 tty_initialized = true;
322 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
331 * Suspend sudo if the underlying command is suspended.
332 * Returns SIGCONT_FG if the command should be resumed in the
333 * foreground or SIGCONT_BG if it is a background process.
336 suspend_parent(int signo)
338 char signame[SIG2STR_MAX];
340 int n, oldmode = ttymode, rval = 0;
341 debug_decl(suspend_parent, SUDO_DEBUG_EXEC);
347 * If we are the foreground process, just resume the command.
348 * Otherwise, re-send the signal with the handler disabled.
353 if (ttymode != TERM_RAW) {
355 n = term_raw(io_fds[SFD_USERTTY], 0);
356 } while (!n && errno == EINTR);
359 rval = SIGCONT_FG; /* resume command in foreground */
366 /* Flush any remaining output before suspending. */
369 /* Restore original tty mode before suspending. */
370 if (oldmode != TERM_COOKED) {
372 n = term_restore(io_fds[SFD_USERTTY], 0);
373 } while (!n && errno == EINTR);
376 if (sig2str(signo, signame) == -1)
377 snprintf(signame, sizeof(signame), "%d", signo);
379 /* Suspend self and continue command when we resume. */
380 zero_bytes(&sa, sizeof(sa));
381 sigemptyset(&sa.sa_mask);
382 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
383 sa.sa_handler = SIG_DFL;
384 sigaction(signo, &sa, &osa);
385 sudo_debug_printf(SUDO_DEBUG_INFO, "kill parent SIG%s", signame);
386 if (killpg(ppgrp, signo) != 0)
387 warning("killpg(%d, SIG%s)", (int)ppgrp, signame);
389 /* Check foreground/background status on resume. */
393 * Only modify term if we are foreground process and either
394 * the old tty mode was not cooked or command got SIGTT{IN,OU}
396 sudo_debug_printf(SUDO_DEBUG_INFO, "parent is in %s, ttymode %d -> %d",
397 foreground ? "foreground" : "background", oldmode, ttymode);
399 if (ttymode != TERM_COOKED) {
403 n = term_raw(io_fds[SFD_USERTTY], 0);
404 } while (!n && errno == EINTR);
406 /* Background process, no access to tty. */
407 ttymode = TERM_COOKED;
411 sigaction(signo, &osa, NULL);
412 rval = ttymode == TERM_RAW ? SIGCONT_FG : SIGCONT_BG;
416 debug_return_int(rval);
420 * Kill command with increasing urgency.
423 terminate_command(pid_t pid, bool use_pgrp)
425 debug_decl(terminate_command, SUDO_DEBUG_EXEC);
428 * Note that SIGCHLD will interrupt the sleep()
431 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGHUP", (int)pid);
433 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGTERM", (int)pid);
434 killpg(pid, SIGTERM);
436 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGKILL", (int)pid);
437 killpg(pid, SIGKILL);
439 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGHUP", (int)pid);
441 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGTERM", (int)pid);
444 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGKILL", (int)pid);
451 static struct io_buffer *
452 io_buf_new(int rfd, int wfd, bool (*action)(const char *, unsigned int),
453 struct io_buffer *head)
455 struct io_buffer *iob;
456 debug_decl(io_buf_new, SUDO_DEBUG_EXEC);
458 iob = ecalloc(1, sizeof(*iob));
461 iob->action = action;
464 debug_return_ptr(iob);
468 * Read/write iobufs depending on fdsr and fdsw.
469 * Returns the number of errors.
472 perform_io(fd_set *fdsr, fd_set *fdsw, struct command_status *cstat)
474 struct io_buffer *iob;
476 debug_decl(perform_io, SUDO_DEBUG_EXEC);
478 for (iob = iobufs; iob; iob = iob->next) {
479 if (iob->rfd != -1 && FD_ISSET(iob->rfd, fdsr)) {
481 n = read(iob->rfd, iob->buf + iob->len,
482 sizeof(iob->buf) - iob->len);
483 } while (n == -1 && errno == EINTR);
486 if (errno != EAGAIN) {
487 /* treat read error as fatal and close the fd */
488 sudo_debug_printf(SUDO_DEBUG_ERROR,
489 "error reading fd %d: %s", iob->rfd,
491 safe_close(iob->rfd);
496 /* got EOF or pty has gone away */
497 sudo_debug_printf(SUDO_DEBUG_INFO,
498 "read EOF from fd %d", iob->rfd);
499 safe_close(iob->rfd);
503 sudo_debug_printf(SUDO_DEBUG_INFO,
504 "read %d bytes from fd %d", n, iob->rfd);
505 if (!iob->action(iob->buf + iob->len, n))
506 terminate_command(cmnd_pid, true);
511 if (iob->wfd != -1 && FD_ISSET(iob->wfd, fdsw)) {
513 n = write(iob->wfd, iob->buf + iob->off,
514 iob->len - iob->off);
515 } while (n == -1 && errno == EINTR);
517 if (errno == EPIPE || errno == ENXIO || errno == EIO || errno == EBADF) {
518 sudo_debug_printf(SUDO_DEBUG_INFO,
519 "unable to write %d bytes to fd %d",
520 iob->len - iob->off, iob->wfd);
521 /* other end of pipe closed or pty revoked */
522 if (iob->rfd != -1) {
523 safe_close(iob->rfd);
526 safe_close(iob->wfd);
530 if (errno != EAGAIN) {
532 sudo_debug_printf(SUDO_DEBUG_ERROR,
533 "error writing fd %d: %s", iob->wfd, strerror(errno));
536 sudo_debug_printf(SUDO_DEBUG_INFO,
537 "wrote %d bytes to fd %d", n, iob->wfd);
542 if (errors && cstat != NULL) {
543 cstat->type = CMD_ERRNO;
546 debug_return_int(errors);
550 * Fork a monitor process which runs the actual command as its own child
551 * process with std{in,out,err} hooked up to the pty or pipes as appropriate.
552 * Returns the child pid.
555 fork_pty(struct command_details *details, int sv[], int *maxfd, sigset_t *omask)
557 struct command_status cstat;
558 struct io_buffer *iob;
559 int io_pipe[3][2], n;
563 debug_decl(fork_pty, SUDO_DEBUG_EXEC);
565 ppgrp = getpgrp(); /* parent's pgrp, so child can signal us */
567 zero_bytes(&sa, sizeof(sa));
568 sigemptyset(&sa.sa_mask);
570 if (io_fds[SFD_USERTTY] != -1) {
571 sa.sa_flags = SA_RESTART;
572 sa.sa_handler = sigwinch;
573 sigaction(SIGWINCH, &sa, NULL);
576 /* So we can block tty-generated signals */
577 sigemptyset(&ttyblock);
578 sigaddset(&ttyblock, SIGINT);
579 sigaddset(&ttyblock, SIGQUIT);
580 sigaddset(&ttyblock, SIGTSTP);
581 sigaddset(&ttyblock, SIGTTIN);
582 sigaddset(&ttyblock, SIGTTOU);
585 * Setup stdin/stdout/stderr for child, to be duped after forking.
586 * In background mode there is no stdin.
588 if (!ISSET(details->flags, CD_BACKGROUND))
589 io_fds[SFD_STDIN] = io_fds[SFD_SLAVE];
590 io_fds[SFD_STDOUT] = io_fds[SFD_SLAVE];
591 io_fds[SFD_STDERR] = io_fds[SFD_SLAVE];
593 if (io_fds[SFD_USERTTY] != -1) {
594 /* Read from /dev/tty, write to pty master */
595 if (!ISSET(details->flags, CD_BACKGROUND)) {
596 iobufs = io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_MASTER],
600 /* Read from pty master, write to /dev/tty */
601 iobufs = io_buf_new(io_fds[SFD_MASTER], io_fds[SFD_USERTTY],
604 /* Are we the foreground process? */
605 foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
609 * If either stdin, stdout or stderr is not a tty we use a pipe
610 * to interpose ourselves instead of duping the pty fd.
612 memset(io_pipe, 0, sizeof(io_pipe));
613 if (io_fds[SFD_STDIN] == -1 || !isatty(STDIN_FILENO)) {
614 sudo_debug_printf(SUDO_DEBUG_INFO, "stdin not a tty, creating a pipe");
616 if (pipe(io_pipe[STDIN_FILENO]) != 0)
617 error(1, _("unable to create pipe"));
618 iobufs = io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
620 io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
622 if (io_fds[SFD_STDOUT] == -1 || !isatty(STDOUT_FILENO)) {
623 sudo_debug_printf(SUDO_DEBUG_INFO, "stdout not a tty, creating a pipe");
625 if (pipe(io_pipe[STDOUT_FILENO]) != 0)
626 error(1, _("unable to create pipe"));
627 iobufs = io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
629 io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
631 if (io_fds[SFD_STDERR] == -1 || !isatty(STDERR_FILENO)) {
632 sudo_debug_printf(SUDO_DEBUG_INFO, "stderr not a tty, creating a pipe");
633 if (pipe(io_pipe[STDERR_FILENO]) != 0)
634 error(1, _("unable to create pipe"));
635 iobufs = io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
637 io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
640 /* Job control signals to relay from parent to child. */
641 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
643 sa.sa_flags |= SA_SIGINFO;
644 sa.sa_sigaction = handler;
646 sa.sa_handler = handler;
648 sigaction(SIGTSTP, &sa, NULL);
650 /* We don't want to receive SIGTTIN/SIGTTOU, getting EIO is preferable. */
651 sa.sa_handler = SIG_IGN;
652 sigaction(SIGTTIN, &sa, NULL);
653 sigaction(SIGTTOU, &sa, NULL);
656 /* Copy terminal attrs from user tty -> pty slave. */
657 if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
658 tty_initialized = true;
659 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
662 /* Start out in raw mode if we are not part of a pipeline. */
666 n = term_raw(io_fds[SFD_USERTTY], 0);
667 } while (!n && errno == EINTR);
669 error(1, _("unable to set terminal to raw mode"));
674 * The policy plugin's session init must be run before we fork
675 * or certain pam modules won't be able to track their state.
677 if (policy_init_session(details) != true)
678 errorx(1, _("policy plugin failed session initialization"));
681 * Block some signals until cmnd_pid is set in the parent to avoid a
682 * race between exec of the command and receipt of a fatal signal from it.
685 sigaddset(&mask, SIGTERM);
686 sigaddset(&mask, SIGHUP);
687 sigaddset(&mask, SIGINT);
688 sigaddset(&mask, SIGQUIT);
689 sigprocmask(SIG_BLOCK, &mask, omask);
691 child = sudo_debug_fork();
694 error(1, _("unable to fork"));
699 close(signal_pipe[0]);
700 close(signal_pipe[1]);
701 fcntl(sv[1], F_SETFD, FD_CLOEXEC);
702 sigprocmask(SIG_SETMASK, omask, NULL);
703 if (exec_setup(details, slavename, io_fds[SFD_SLAVE]) == true) {
704 /* Close the other end of the stdin/stdout/stderr pipes and exec. */
705 if (io_pipe[STDIN_FILENO][1])
706 close(io_pipe[STDIN_FILENO][1]);
707 if (io_pipe[STDOUT_FILENO][0])
708 close(io_pipe[STDOUT_FILENO][0]);
709 if (io_pipe[STDERR_FILENO][0])
710 close(io_pipe[STDERR_FILENO][0]);
711 exec_monitor(details, sv[1]);
713 cstat.type = CMD_ERRNO;
715 ignore_result(send(sv[1], &cstat, sizeof(cstat), 0));
719 /* Close the other end of the stdin/stdout/stderr pipes. */
720 if (io_pipe[STDIN_FILENO][0])
721 close(io_pipe[STDIN_FILENO][0]);
722 if (io_pipe[STDOUT_FILENO][1])
723 close(io_pipe[STDOUT_FILENO][1]);
724 if (io_pipe[STDERR_FILENO][1])
725 close(io_pipe[STDERR_FILENO][1]);
727 for (iob = iobufs; iob; iob = iob->next) {
728 /* Determine maxfd */
729 if (iob->rfd > *maxfd)
731 if (iob->wfd > *maxfd)
734 /* Set non-blocking mode. */
735 n = fcntl(iob->rfd, F_GETFL, 0);
736 if (n != -1 && !ISSET(n, O_NONBLOCK))
737 (void) fcntl(iob->rfd, F_SETFL, n | O_NONBLOCK);
738 n = fcntl(iob->wfd, F_GETFL, 0);
739 if (n != -1 && !ISSET(n, O_NONBLOCK))
740 (void) fcntl(iob->wfd, F_SETFL, n | O_NONBLOCK);
743 debug_return_int(child);
747 pty_close(struct command_status *cstat)
750 debug_decl(pty_close, SUDO_DEBUG_EXEC);
752 /* Flush any remaining output (the plugin already got it) */
753 if (io_fds[SFD_USERTTY] != -1) {
754 n = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
755 if (n != -1 && ISSET(n, O_NONBLOCK)) {
757 (void) fcntl(io_fds[SFD_USERTTY], F_SETFL, n);
762 if (io_fds[SFD_USERTTY] != -1) {
766 n = term_restore(io_fds[SFD_USERTTY], 0);
767 } while (!n && errno == EINTR);
771 /* If child was signalled, write the reason to stdout like the shell. */
772 if (cstat->type == CMD_WSTATUS && WIFSIGNALED(cstat->val)) {
773 int signo = WTERMSIG(cstat->val);
774 if (signo && signo != SIGINT && signo != SIGPIPE) {
775 const char *reason = strsignal(signo);
776 n = io_fds[SFD_USERTTY] != -1 ?
777 io_fds[SFD_USERTTY] : STDOUT_FILENO;
778 if (write(n, reason, strlen(reason)) != -1) {
779 if (WCOREDUMP(cstat->val)) {
780 ignore_result(write(n, " (core dumped)", 14));
782 ignore_result(write(n, "\n", 1));
786 utmp_logout(slavename, cstat->type == CMD_WSTATUS ? cstat->val : 0); /* XXX - only if CD_SET_UTMP */
791 * Fill in fdsr and fdsw based on the io buffers list.
792 * Called prior to select().
795 fd_set_iobs(fd_set *fdsr, fd_set *fdsw)
797 struct io_buffer *iob;
798 debug_decl(fd_set_iobs, SUDO_DEBUG_EXEC);
800 for (iob = iobufs; iob; iob = iob->next) {
801 if (iob->rfd == -1 && iob->wfd == -1)
803 if (iob->off == iob->len) {
804 iob->off = iob->len = 0;
805 /* Forward the EOF from reader to writer. */
806 if (iob->rfd == -1) {
807 safe_close(iob->wfd);
811 /* Don't read/write /dev/tty if we are not in the foreground. */
812 if (iob->rfd != -1 &&
813 (ttymode == TERM_RAW || iob->rfd != io_fds[SFD_USERTTY])) {
814 if (iob->len != sizeof(iob->buf))
815 FD_SET(iob->rfd, fdsr);
817 if (iob->wfd != -1 &&
818 (foreground || iob->wfd != io_fds[SFD_USERTTY])) {
819 if (iob->len > iob->off)
820 FD_SET(iob->wfd, fdsw);
827 deliver_signal(pid_t pid, int signo, bool from_parent)
829 char signame[SIG2STR_MAX];
831 debug_decl(deliver_signal, SUDO_DEBUG_EXEC);
833 if (sig2str(signo, signame) == -1)
834 snprintf(signame, sizeof(signame), "%d", signo);
836 /* Handle signal from parent. */
837 sudo_debug_printf(SUDO_DEBUG_INFO, "received SIG%s%s",
838 signame, from_parent ? " from parent" : "");
841 terminate_command(pid, true);
844 /* Continue in foreground, grant it controlling tty. */
846 status = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
847 } while (status == -1 && errno == EINTR);
848 killpg(pid, SIGCONT);
851 /* Continue in background, I take controlling tty. */
853 status = tcsetpgrp(io_fds[SFD_SLAVE], mon_pgrp);
854 } while (status == -1 && errno == EINTR);
855 killpg(pid, SIGCONT);
861 /* Relay signal to command. */
869 * Send status to parent over socketpair.
870 * Return value is the same as send(2).
873 send_status(int fd, struct command_status *cstat)
876 debug_decl(send_status, SUDO_DEBUG_EXEC);
878 if (cstat->type != CMD_INVALID) {
879 sudo_debug_printf(SUDO_DEBUG_INFO,
880 "sending status message to parent: [%d, %d]",
881 cstat->type, cstat->val);
883 n = send(fd, cstat, sizeof(*cstat), 0);
884 } while (n == -1 && errno == EINTR);
885 if (n != sizeof(*cstat)) {
886 sudo_debug_printf(SUDO_DEBUG_ERROR,
887 "unable to send status to parent: %s", strerror(errno));
889 cstat->type = CMD_INVALID; /* prevent re-sending */
895 * Wait for command status after receiving SIGCHLD.
896 * If the command was stopped, the status is send back to the parent.
897 * Otherwise, cstat is filled in but not sent.
898 * Returns true if command is still alive, else false.
901 handle_sigchld(int backchannel, struct command_status *cstat)
906 debug_decl(handle_sigchld, SUDO_DEBUG_EXEC);
908 /* read command status */
910 pid = waitpid(cmnd_pid, &status, WUNTRACED|WNOHANG);
911 } while (pid == -1 && errno == EINTR);
912 if (pid == cmnd_pid) {
913 if (cstat->type != CMD_ERRNO) {
914 char signame[SIG2STR_MAX];
916 cstat->type = CMD_WSTATUS;
918 if (WIFSTOPPED(status)) {
919 if (sig2str(WSTOPSIG(status), signame) == -1)
920 snprintf(signame, sizeof(signame), "%d", WSTOPSIG(status));
921 sudo_debug_printf(SUDO_DEBUG_INFO,
922 "command stopped, SIG%s", signame);
923 /* Saved the foreground pgid so we can restore it later. */
925 pid = tcgetpgrp(io_fds[SFD_SLAVE]);
926 } while (pid == -1 && errno == EINTR);
929 if (send_status(backchannel, cstat) == -1)
930 return alive; /* XXX */
931 } else if (WIFSIGNALED(status)) {
932 if (sig2str(WTERMSIG(status), signame) == -1)
933 snprintf(signame, sizeof(signame), "%d", WTERMSIG(status));
934 sudo_debug_printf(SUDO_DEBUG_INFO,
935 "command killed, SIG%s", signame);
937 sudo_debug_printf(SUDO_DEBUG_INFO, "command exited: %d",
938 WEXITSTATUS(status));
941 if (!WIFSTOPPED(status))
944 debug_return_bool(alive);
948 * Monitor process that creates a new session with the controlling tty,
949 * resets signal handlers and forks a child to call exec_pty().
950 * Waits for status changes from the command and relays them to the
951 * parent and relays signals from the parent to the command.
952 * Returns an error if fork(2) fails, else calls _exit(2).
955 exec_monitor(struct command_details *details, int backchannel)
957 struct command_status cstat;
961 int errpipe[2], maxfd, n;
964 debug_decl(exec_monitor, SUDO_DEBUG_EXEC);
966 /* Close unused fds. */
967 if (io_fds[SFD_MASTER] != -1)
968 close(io_fds[SFD_MASTER]);
969 if (io_fds[SFD_USERTTY] != -1)
970 close(io_fds[SFD_USERTTY]);
973 * We use a pipe to atomically handle signal notification within
976 if (pipe_nonblock(signal_pipe) != 0)
977 error(1, _("unable to create pipe"));
979 /* Reset SIGWINCH and SIGALRM. */
980 zero_bytes(&sa, sizeof(sa));
981 sigemptyset(&sa.sa_mask);
982 sa.sa_flags = SA_RESTART;
983 sa.sa_handler = SIG_DFL;
984 sigaction(SIGWINCH, &sa, NULL);
985 sigaction(SIGALRM, &sa, NULL);
987 /* Ignore any SIGTTIN or SIGTTOU we get. */
988 sa.sa_handler = SIG_IGN;
989 sigaction(SIGTTIN, &sa, NULL);
990 sigaction(SIGTTOU, &sa, NULL);
992 /* Note: HP-UX select() will not be interrupted if SA_RESTART set */
993 sa.sa_flags = SA_INTERRUPT;
995 sa.sa_flags |= SA_SIGINFO;
996 sa.sa_sigaction = mon_handler;
998 sa.sa_handler = mon_handler;
1000 sigaction(SIGCHLD, &sa, NULL);
1002 /* Catch common signals so we can cleanup properly. */
1003 sa.sa_flags = SA_RESTART;
1005 sa.sa_flags |= SA_SIGINFO;
1006 sa.sa_sigaction = mon_handler;
1008 sa.sa_handler = mon_handler;
1010 sigaction(SIGHUP, &sa, NULL);
1011 sigaction(SIGINT, &sa, NULL);
1012 sigaction(SIGQUIT, &sa, NULL);
1013 sigaction(SIGTERM, &sa, NULL);
1014 sigaction(SIGTSTP, &sa, NULL);
1015 sigaction(SIGUSR1, &sa, NULL);
1016 sigaction(SIGUSR2, &sa, NULL);
1019 * Start a new session with the parent as the session leader
1020 * and the slave pty as the controlling terminal.
1021 * This allows us to be notified when the command has been suspended.
1023 if (setsid() == -1) {
1027 if (io_fds[SFD_SLAVE] != -1) {
1029 if (ioctl(io_fds[SFD_SLAVE], TIOCSCTTY, NULL) != 0)
1030 error(1, _("unable to set controlling tty"));
1032 /* Set controlling tty by reopening slave. */
1033 if ((n = open(slavename, O_RDWR)) >= 0)
1038 mon_pgrp = getpgrp(); /* save a copy of our process group */
1041 * If stdin/stdout is not a tty, start command in the background
1042 * since it might be part of a pipeline that reads from /dev/tty.
1043 * In this case, we rely on the command receiving SIGTTOU or SIGTTIN
1044 * when it needs access to the controlling tty.
1049 /* Start command and wait for it to stop or exit */
1050 if (pipe(errpipe) == -1)
1051 error(1, _("unable to create pipe"));
1052 cmnd_pid = sudo_debug_fork();
1053 if (cmnd_pid == -1) {
1054 warning(_("unable to fork"));
1057 if (cmnd_pid == 0) {
1058 /* We pass errno back to our parent via pipe on exec failure. */
1060 close(signal_pipe[0]);
1061 close(signal_pipe[1]);
1063 fcntl(errpipe[1], F_SETFD, FD_CLOEXEC);
1066 /* setup tty and exec command */
1067 exec_pty(details, &errpipe[1]);
1068 cstat.type = CMD_ERRNO;
1070 ignore_result(write(errpipe[1], &cstat, sizeof(cstat)));
1075 /* Send the command's pid to main sudo process. */
1076 cstat.type = CMD_PID;
1077 cstat.val = cmnd_pid;
1078 ignore_result(send(backchannel, &cstat, sizeof(cstat), 0));
1080 /* If any of stdin/stdout/stderr are pipes, close them in parent. */
1081 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1082 close(io_fds[SFD_STDIN]);
1083 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1084 close(io_fds[SFD_STDOUT]);
1085 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1086 close(io_fds[SFD_STDERR]);
1089 * Put command in its own process group. If we are starting the command
1090 * in the foreground, assign its pgrp to the tty.
1092 cmnd_pgrp = cmnd_pid;
1093 setpgid(cmnd_pid, cmnd_pgrp);
1096 n = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
1097 } while (n == -1 && errno == EINTR);
1100 /* Wait for errno on pipe, signal on backchannel or for SIGCHLD */
1101 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
1102 fdsr = ecalloc(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1103 memset(&cstat, 0, sizeof(cstat));
1107 /* Check for signal on backchannel or errno on errpipe. */
1108 FD_SET(backchannel, fdsr);
1109 FD_SET(signal_pipe[0], fdsr);
1110 if (errpipe[0] != -1)
1111 FD_SET(errpipe[0], fdsr);
1112 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
1114 /* If command exited we just poll, there may be data on errpipe. */
1115 n = select(maxfd + 1, fdsr, NULL, NULL, alive ? NULL : &tv);
1119 if (errno == EINTR || errno == ENOMEM)
1121 warning("monitor: %s", _("select failed"));
1125 if (FD_ISSET(signal_pipe[0], fdsr)) {
1126 n = read(signal_pipe[0], &signo, sizeof(signo));
1128 if (errno == EINTR || errno == EAGAIN)
1130 warning(_("error reading from signal pipe"));
1134 * Handle SIGCHLD specially and deliver other signals
1135 * directly to the command.
1137 if (signo == SIGCHLD) {
1138 if (!handle_sigchld(backchannel, &cstat))
1141 deliver_signal(cmnd_pid, signo, false);
1145 if (errpipe[0] != -1 && FD_ISSET(errpipe[0], fdsr)) {
1146 /* read errno or EOF from command pipe */
1147 n = read(errpipe[0], &cstat, sizeof(cstat));
1151 warning(_("error reading from pipe"));
1154 /* Got errno or EOF, either way we are done with errpipe. */
1155 FD_CLR(errpipe[0], fdsr);
1159 if (FD_ISSET(backchannel, fdsr)) {
1160 struct command_status cstmp;
1162 /* read command from backchannel, should be a signal */
1163 n = recv(backchannel, &cstmp, sizeof(cstmp), 0);
1167 warning(_("error reading from socketpair"));
1170 if (cstmp.type != CMD_SIGNO) {
1171 warningx(_("unexpected reply type on backchannel: %d"),
1175 deliver_signal(cmnd_pid, cstmp.val, true);
1181 /* XXX An error occurred, should send an error back. */
1182 kill(cmnd_pid, SIGKILL);
1184 /* Send parent status. */
1185 send_status(backchannel, &cstat);
1187 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, 1);
1191 debug_return_int(errno);
1195 * Flush any output buffered in iobufs or readable from the fds.
1196 * Does not read from /dev/tty.
1201 struct io_buffer *iob;
1203 fd_set *fdsr, *fdsw;
1204 int nready, nwriters, maxfd = -1;
1205 debug_decl(flush_output, SUDO_DEBUG_EXEC);
1207 /* Determine maxfd */
1208 for (iob = iobufs; iob; iob = iob->next) {
1209 if (iob->rfd > maxfd)
1211 if (iob->wfd > maxfd)
1217 fdsr = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1218 fdsw = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1220 memset(fdsw, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1221 memset(fdsr, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1224 for (iob = iobufs; iob; iob = iob->next) {
1225 /* Don't read from /dev/tty while flushing. */
1226 if (io_fds[SFD_USERTTY] != -1 && iob->rfd == io_fds[SFD_USERTTY])
1228 if (iob->rfd == -1 && iob->wfd == -1)
1230 if (iob->off == iob->len) {
1231 iob->off = iob->len = 0;
1232 /* Forward the EOF from reader to writer. */
1233 if (iob->rfd == -1) {
1234 safe_close(iob->wfd);
1238 if (iob->rfd != -1) {
1239 if (iob->len != sizeof(iob->buf))
1240 FD_SET(iob->rfd, fdsr);
1242 if (iob->wfd != -1) {
1243 if (iob->len > iob->off) {
1245 FD_SET(iob->wfd, fdsw);
1250 /* Don't sleep in select if there are no buffers that need writing. */
1253 nready = select(maxfd + 1, fdsr, fdsw, NULL, nwriters ? NULL : &tv);
1256 break; /* all I/O flushed */
1257 if (errno == EINTR || errno == ENOMEM)
1259 warning(_("select failed"));
1261 if (perform_io(fdsr, fdsw, NULL) != 0 || nready == -1)
1270 * Sets up std{in,out,err} and executes the actual command.
1271 * Returns only if execve() fails.
1274 exec_pty(struct command_details *details, int *errfd)
1276 pid_t self = getpid();
1277 debug_decl(exec_pty, SUDO_DEBUG_EXEC);
1279 /* Set command process group here too to avoid a race. */
1282 /* Wire up standard fds, note that stdout/stderr may be pipes. */
1283 if (dup2(io_fds[SFD_STDIN], STDIN_FILENO) == -1 ||
1284 dup2(io_fds[SFD_STDOUT], STDOUT_FILENO) == -1 ||
1285 dup2(io_fds[SFD_STDERR], STDERR_FILENO) == -1)
1288 /* Wait for parent to grant us the tty if we are foreground. */
1290 while (tcgetpgrp(io_fds[SFD_SLAVE]) != self)
1294 /* We have guaranteed that the slave fd is > 2 */
1295 if (io_fds[SFD_SLAVE] != -1)
1296 close(io_fds[SFD_SLAVE]);
1297 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1298 close(io_fds[SFD_STDIN]);
1299 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1300 close(io_fds[SFD_STDOUT]);
1301 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1302 close(io_fds[SFD_STDERR]);
1304 sudo_debug_execve(SUDO_DEBUG_INFO, details->command,
1305 details->argv, details->envp);
1307 if (details->closefrom >= 0) {
1308 int maxfd = details->closefrom;
1309 dup2(*errfd, maxfd);
1310 (void)fcntl(maxfd, F_SETFD, FD_CLOEXEC);
1312 if (sudo_debug_fd_set(maxfd) != -1)
1317 if (ISSET(details->flags, CD_RBAC_ENABLED)) {
1318 selinux_execve(details->command, details->argv, details->envp,
1319 ISSET(details->flags, CD_NOEXEC));
1323 sudo_execve(details->command, details->argv, details->envp,
1324 ISSET(details->flags, CD_NOEXEC));
1326 sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to exec %s: %s",
1327 details->command, strerror(errno));
1332 * Propagates tty size change signals to pty being used by the command.
1335 sync_ttysize(int src, int dst)
1338 struct winsize wsize;
1340 debug_decl(sync_ttysize, SUDO_DEBUG_EXEC);
1342 if (ioctl(src, TIOCGWINSZ, &wsize) == 0) {
1343 ioctl(dst, TIOCSWINSZ, &wsize);
1344 if ((pgrp = tcgetpgrp(dst)) != -1)
1345 killpg(pgrp, SIGWINCH);
1353 * Handler for SIGWINCH in parent.
1360 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
1365 * Only close the fd if it is not /dev/tty or std{in,out,err}.
1366 * Return value is the same as send(2).
1371 debug_decl(safe_close, SUDO_DEBUG_EXEC);
1373 /* Avoid closing /dev/tty or std{in,out,err}. */
1374 if (fd < 3 || fd == io_fds[SFD_USERTTY]) {
1376 debug_return_int(-1);
1378 debug_return_int(close(fd));