2 * Copyright (c) 2009-2013 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 #ifdef HAVE_SYS_SYSMACROS_H
21 # include <sys/sysmacros.h>
23 #include <sys/socket.h>
26 #include <sys/ioctl.h>
27 #ifdef HAVE_SYS_SELECT_H
28 # include <sys/select.h>
29 #endif /* HAVE_SYS_SELECT_H */
38 #endif /* STDC_HEADERS */
40 # if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
44 #endif /* HAVE_STRING_H */
47 #endif /* HAVE_STRINGS_H */
50 #endif /* HAVE_UNISTD_H */
51 #if TIME_WITH_SYS_TIME
60 #include "sudo_exec.h"
61 #include "sudo_plugin.h"
62 #include "sudo_plugin_int.h"
74 /* Compatibility with older tty systems. */
75 #if !defined(TIOCGWINSZ) && defined(TIOCGSIZE)
76 # define TIOCGWINSZ TIOCGSIZE
77 # define TIOCSWINSZ TIOCSSIZE
78 # define winsize ttysize
82 struct io_buffer *next;
83 int len; /* buffer length (how much produced) */
84 int off; /* write position (how much already consumed) */
85 int rfd; /* reader (producer) */
86 int wfd; /* writer (consumer) */
87 bool (*action)(const char *buf, unsigned int len);
91 static char slavename[PATH_MAX];
92 static bool foreground, pipeline, tty_initialized;
93 static int io_fds[6] = { -1, -1, -1, -1, -1, -1};
94 static int ttymode = TERM_COOKED;
95 static pid_t ppgrp, cmnd_pgrp, mon_pgrp;
96 static sigset_t ttyblock;
97 static struct io_buffer *iobufs;
99 static void flush_output(void);
100 static int exec_monitor(struct command_details *details, int backchannel);
101 static void exec_pty(struct command_details *details,
102 struct command_status *cstat, 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 fatal()/fatalx()
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 fatal(_("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];
341 debug_decl(suspend_parent, SUDO_DEBUG_EXEC);
347 * If sudo is already the foreground process, just resume the command
348 * in the foreground. If not, we'll suspend sudo and resume later.
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 */
365 /* Flush any remaining output before suspending. */
368 /* Restore original tty mode before suspending. */
369 if (ttymode != TERM_COOKED) {
371 n = term_restore(io_fds[SFD_USERTTY], 0);
372 } while (!n && errno == EINTR);
375 if (sig2str(signo, signame) == -1)
376 snprintf(signame, sizeof(signame), "%d", signo);
378 /* Suspend self and continue command when we resume. */
379 if (signo != SIGSTOP) {
380 memset(&sa, 0, sizeof(sa));
381 sigemptyset(&sa.sa_mask);
382 sa.sa_flags = SA_RESTART;
383 sa.sa_handler = SIG_DFL;
384 sudo_sigaction(signo, &sa, &osa);
386 sudo_debug_printf(SUDO_DEBUG_INFO, "kill parent SIG%s", signame);
387 if (killpg(ppgrp, signo) != 0)
388 warning("killpg(%d, SIG%s)", (int)ppgrp, signame);
390 /* Check foreground/background status on resume. */
394 * We always resume the command in the foreground if sudo itself
395 * is the foreground process. This helps work around poorly behaved
396 * programs that catch SIGTTOU/SIGTTIN but suspend themselves with
397 * SIGSTOP. At worst, sudo will go into the background but upon
398 * resume the command will be runnable. Otherwise, we can get into
399 * a situation where the command will immediately suspend itself.
401 sudo_debug_printf(SUDO_DEBUG_INFO, "parent is in %s, ttymode %d -> %d",
402 foreground ? "foreground" : "background", ttymode,
403 foreground ? TERM_RAW : TERM_COOKED);
406 /* Foreground process, set tty to raw mode. */
408 n = term_raw(io_fds[SFD_USERTTY], 0);
409 } while (!n && errno == EINTR);
412 /* Background process, no access to tty. */
413 ttymode = TERM_COOKED;
416 if (signo != SIGSTOP)
417 sudo_sigaction(signo, &osa, NULL);
418 rval = ttymode == TERM_RAW ? SIGCONT_FG : SIGCONT_BG;
422 debug_return_int(rval);
426 * Kill command with increasing urgency.
429 terminate_command(pid_t pid, bool use_pgrp)
431 debug_decl(terminate_command, SUDO_DEBUG_EXEC);
434 * Note that SIGCHLD will interrupt the sleep()
437 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGHUP", (int)pid);
439 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGTERM", (int)pid);
440 killpg(pid, SIGTERM);
442 sudo_debug_printf(SUDO_DEBUG_INFO, "killpg %d SIGKILL", (int)pid);
443 killpg(pid, SIGKILL);
445 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGHUP", (int)pid);
447 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGTERM", (int)pid);
450 sudo_debug_printf(SUDO_DEBUG_INFO, "kill %d SIGKILL", (int)pid);
457 static struct io_buffer *
458 io_buf_new(int rfd, int wfd, bool (*action)(const char *, unsigned int),
459 struct io_buffer *head)
461 struct io_buffer *iob;
462 debug_decl(io_buf_new, SUDO_DEBUG_EXEC);
464 iob = ecalloc(1, sizeof(*iob));
467 iob->action = action;
470 debug_return_ptr(iob);
474 * Read/write iobufs depending on fdsr and fdsw.
475 * Returns the number of errors.
478 perform_io(fd_set *fdsr, fd_set *fdsw, struct command_status *cstat)
480 struct io_buffer *iob;
482 debug_decl(perform_io, SUDO_DEBUG_EXEC);
484 for (iob = iobufs; iob; iob = iob->next) {
485 if (iob->rfd != -1 && FD_ISSET(iob->rfd, fdsr)) {
487 n = read(iob->rfd, iob->buf + iob->len,
488 sizeof(iob->buf) - iob->len);
489 } while (n == -1 && errno == EINTR);
492 if (errno != EAGAIN) {
493 /* treat read error as fatal and close the fd */
494 sudo_debug_printf(SUDO_DEBUG_ERROR,
495 "error reading fd %d: %s", iob->rfd,
497 safe_close(iob->rfd);
502 /* got EOF or pty has gone away */
503 sudo_debug_printf(SUDO_DEBUG_INFO,
504 "read EOF from fd %d", iob->rfd);
505 safe_close(iob->rfd);
509 sudo_debug_printf(SUDO_DEBUG_INFO,
510 "read %d bytes from fd %d", n, iob->rfd);
511 if (!iob->action(iob->buf + iob->len, n))
512 terminate_command(cmnd_pid, true);
517 if (iob->wfd != -1 && FD_ISSET(iob->wfd, fdsw)) {
519 n = write(iob->wfd, iob->buf + iob->off,
520 iob->len - iob->off);
521 } while (n == -1 && errno == EINTR);
523 if (errno == EPIPE || errno == ENXIO || errno == EIO || errno == EBADF) {
524 sudo_debug_printf(SUDO_DEBUG_INFO,
525 "unable to write %d bytes to fd %d",
526 iob->len - iob->off, iob->wfd);
527 /* other end of pipe closed or pty revoked */
528 if (iob->rfd != -1) {
529 safe_close(iob->rfd);
532 safe_close(iob->wfd);
536 if (errno != EAGAIN) {
538 sudo_debug_printf(SUDO_DEBUG_ERROR,
539 "error writing fd %d: %s", iob->wfd, strerror(errno));
542 sudo_debug_printf(SUDO_DEBUG_INFO,
543 "wrote %d bytes to fd %d", n, iob->wfd);
548 if (errors && cstat != NULL) {
549 cstat->type = CMD_ERRNO;
552 debug_return_int(errors);
556 * Fork a monitor process which runs the actual command as its own child
557 * process with std{in,out,err} hooked up to the pty or pipes as appropriate.
558 * Returns the child pid.
561 fork_pty(struct command_details *details, int sv[], int *maxfd, sigset_t *omask)
563 struct command_status cstat;
564 struct io_buffer *iob;
565 int io_pipe[3][2], n;
569 debug_decl(fork_pty, SUDO_DEBUG_EXEC);
571 ppgrp = getpgrp(); /* parent's pgrp, so child can signal us */
573 memset(&sa, 0, sizeof(sa));
574 sigemptyset(&sa.sa_mask);
576 if (io_fds[SFD_USERTTY] != -1) {
577 sa.sa_flags = SA_RESTART;
578 sa.sa_handler = sigwinch;
579 sudo_sigaction(SIGWINCH, &sa, NULL);
582 /* So we can block tty-generated signals */
583 sigemptyset(&ttyblock);
584 sigaddset(&ttyblock, SIGINT);
585 sigaddset(&ttyblock, SIGQUIT);
586 sigaddset(&ttyblock, SIGTSTP);
587 sigaddset(&ttyblock, SIGTTIN);
588 sigaddset(&ttyblock, SIGTTOU);
591 * Setup stdin/stdout/stderr for child, to be duped after forking.
592 * In background mode there is no stdin.
594 if (!ISSET(details->flags, CD_BACKGROUND))
595 io_fds[SFD_STDIN] = io_fds[SFD_SLAVE];
596 io_fds[SFD_STDOUT] = io_fds[SFD_SLAVE];
597 io_fds[SFD_STDERR] = io_fds[SFD_SLAVE];
599 if (io_fds[SFD_USERTTY] != -1) {
600 /* Read from /dev/tty, write to pty master */
601 if (!ISSET(details->flags, CD_BACKGROUND)) {
602 iobufs = io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_MASTER],
606 /* Read from pty master, write to /dev/tty */
607 iobufs = io_buf_new(io_fds[SFD_MASTER], io_fds[SFD_USERTTY],
610 /* Are we the foreground process? */
611 foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
615 * If either stdin, stdout or stderr is not a tty we use a pipe
616 * to interpose ourselves instead of duping the pty fd.
618 memset(io_pipe, 0, sizeof(io_pipe));
619 if (io_fds[SFD_STDIN] == -1 || !isatty(STDIN_FILENO)) {
620 sudo_debug_printf(SUDO_DEBUG_INFO, "stdin not a tty, creating a pipe");
622 if (pipe(io_pipe[STDIN_FILENO]) != 0)
623 fatal(_("unable to create pipe"));
624 iobufs = io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
626 io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
628 if (io_fds[SFD_STDOUT] == -1 || !isatty(STDOUT_FILENO)) {
629 sudo_debug_printf(SUDO_DEBUG_INFO, "stdout not a tty, creating a pipe");
631 if (pipe(io_pipe[STDOUT_FILENO]) != 0)
632 fatal(_("unable to create pipe"));
633 iobufs = io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
635 io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
637 if (io_fds[SFD_STDERR] == -1 || !isatty(STDERR_FILENO)) {
638 sudo_debug_printf(SUDO_DEBUG_INFO, "stderr not a tty, creating a pipe");
639 if (pipe(io_pipe[STDERR_FILENO]) != 0)
640 fatal(_("unable to create pipe"));
641 iobufs = io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
643 io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
646 /* We don't want to receive SIGTTIN/SIGTTOU, getting EIO is preferable. */
647 sa.sa_handler = SIG_IGN;
648 sudo_sigaction(SIGTTIN, &sa, NULL);
649 sudo_sigaction(SIGTTOU, &sa, NULL);
651 /* Job control signals to relay from parent to child. */
652 sigfillset(&sa.sa_mask);
653 sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
655 sa.sa_flags |= SA_SIGINFO;
656 sa.sa_sigaction = handler;
658 sa.sa_handler = handler;
660 sudo_sigaction(SIGTSTP, &sa, NULL);
663 /* Copy terminal attrs from user tty -> pty slave. */
664 if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
665 tty_initialized = true;
666 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
669 /* Start out in raw mode unless part of a pipeline or backgrounded. */
670 if (!pipeline && !ISSET(details->flags, CD_EXEC_BG)) {
673 n = term_raw(io_fds[SFD_USERTTY], 0);
674 } while (!n && errno == EINTR);
676 fatal(_("unable to set terminal to raw mode"));
681 * The policy plugin's session init must be run before we fork
682 * or certain pam modules won't be able to track their state.
684 if (policy_init_session(details) != true)
685 fatalx(_("policy plugin failed session initialization"));
688 * Block some signals until cmnd_pid is set in the parent to avoid a
689 * race between exec of the command and receipt of a fatal signal from it.
692 sigaddset(&mask, SIGTERM);
693 sigaddset(&mask, SIGHUP);
694 sigaddset(&mask, SIGINT);
695 sigaddset(&mask, SIGQUIT);
696 sigprocmask(SIG_BLOCK, &mask, omask);
698 child = sudo_debug_fork();
701 fatal(_("unable to fork"));
706 close(signal_pipe[0]);
707 close(signal_pipe[1]);
708 fcntl(sv[1], F_SETFD, FD_CLOEXEC);
709 sigprocmask(SIG_SETMASK, omask, NULL);
710 /* Close the other end of the stdin/stdout/stderr pipes and exec. */
711 if (io_pipe[STDIN_FILENO][1])
712 close(io_pipe[STDIN_FILENO][1]);
713 if (io_pipe[STDOUT_FILENO][0])
714 close(io_pipe[STDOUT_FILENO][0]);
715 if (io_pipe[STDERR_FILENO][0])
716 close(io_pipe[STDERR_FILENO][0]);
717 exec_monitor(details, sv[1]);
718 cstat.type = CMD_ERRNO;
720 ignore_result(send(sv[1], &cstat, sizeof(cstat), 0));
724 /* Close the other end of the stdin/stdout/stderr pipes. */
725 if (io_pipe[STDIN_FILENO][0])
726 close(io_pipe[STDIN_FILENO][0]);
727 if (io_pipe[STDOUT_FILENO][1])
728 close(io_pipe[STDOUT_FILENO][1]);
729 if (io_pipe[STDERR_FILENO][1])
730 close(io_pipe[STDERR_FILENO][1]);
732 for (iob = iobufs; iob; iob = iob->next) {
733 /* Determine maxfd */
734 if (iob->rfd > *maxfd)
736 if (iob->wfd > *maxfd)
739 /* Set non-blocking mode. */
740 n = fcntl(iob->rfd, F_GETFL, 0);
741 if (n != -1 && !ISSET(n, O_NONBLOCK))
742 (void) fcntl(iob->rfd, F_SETFL, n | O_NONBLOCK);
743 n = fcntl(iob->wfd, F_GETFL, 0);
744 if (n != -1 && !ISSET(n, O_NONBLOCK))
745 (void) fcntl(iob->wfd, F_SETFL, n | O_NONBLOCK);
748 debug_return_int(child);
752 pty_close(struct command_status *cstat)
755 debug_decl(pty_close, SUDO_DEBUG_EXEC);
757 /* Flush any remaining output (the plugin already got it) */
758 if (io_fds[SFD_USERTTY] != -1) {
759 n = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
760 if (n != -1 && ISSET(n, O_NONBLOCK)) {
762 (void) fcntl(io_fds[SFD_USERTTY], F_SETFL, n);
767 if (io_fds[SFD_USERTTY] != -1) {
771 n = term_restore(io_fds[SFD_USERTTY], 0);
772 } while (!n && errno == EINTR);
776 /* If child was signalled, write the reason to stdout like the shell. */
777 if (cstat->type == CMD_WSTATUS && WIFSIGNALED(cstat->val)) {
778 int signo = WTERMSIG(cstat->val);
779 if (signo && signo != SIGINT && signo != SIGPIPE) {
780 const char *reason = strsignal(signo);
781 n = io_fds[SFD_USERTTY] != -1 ?
782 io_fds[SFD_USERTTY] : STDOUT_FILENO;
783 if (write(n, reason, strlen(reason)) != -1) {
784 if (WCOREDUMP(cstat->val)) {
785 ignore_result(write(n, " (core dumped)", 14));
787 ignore_result(write(n, "\n", 1));
791 utmp_logout(slavename, cstat->type == CMD_WSTATUS ? cstat->val : 0); /* XXX - only if CD_SET_UTMP */
796 * Fill in fdsr and fdsw based on the io buffers list.
797 * Called prior to select().
800 fd_set_iobs(fd_set *fdsr, fd_set *fdsw)
802 struct io_buffer *iob;
803 debug_decl(fd_set_iobs, SUDO_DEBUG_EXEC);
805 for (iob = iobufs; iob; iob = iob->next) {
806 if (iob->rfd == -1 && iob->wfd == -1)
808 if (iob->off == iob->len) {
809 iob->off = iob->len = 0;
810 /* Forward the EOF from reader to writer. */
811 if (iob->rfd == -1) {
812 safe_close(iob->wfd);
816 /* Don't read/write /dev/tty if we are not in the foreground. */
817 if (iob->rfd != -1 &&
818 (ttymode == TERM_RAW || iob->rfd != io_fds[SFD_USERTTY])) {
819 if (iob->len != sizeof(iob->buf))
820 FD_SET(iob->rfd, fdsr);
822 if (iob->wfd != -1 &&
823 (foreground || iob->wfd != io_fds[SFD_USERTTY])) {
824 if (iob->len > iob->off)
825 FD_SET(iob->wfd, fdsw);
832 deliver_signal(pid_t pid, int signo, bool from_parent)
834 char signame[SIG2STR_MAX];
836 debug_decl(deliver_signal, SUDO_DEBUG_EXEC);
838 if (signo == SIGCONT_FG)
839 strlcpy(signame, "CONT_FG", sizeof(signame));
840 else if (signo == SIGCONT_BG)
841 strlcpy(signame, "CONT_BG", sizeof(signame));
842 else if (sig2str(signo, signame) == -1)
843 snprintf(signame, sizeof(signame), "%d", signo);
845 /* Handle signal from parent. */
846 sudo_debug_printf(SUDO_DEBUG_INFO, "received SIG%s%s",
847 signame, from_parent ? " from parent" : "");
850 terminate_command(pid, true);
853 /* Continue in foreground, grant it controlling tty. */
855 status = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
856 } while (status == -1 && errno == EINTR);
857 killpg(pid, SIGCONT);
860 /* Continue in background, I take controlling tty. */
862 status = tcsetpgrp(io_fds[SFD_SLAVE], mon_pgrp);
863 } while (status == -1 && errno == EINTR);
864 killpg(pid, SIGCONT);
870 /* Relay signal to command. */
878 * Send status to parent over socketpair.
879 * Return value is the same as send(2).
882 send_status(int fd, struct command_status *cstat)
885 debug_decl(send_status, SUDO_DEBUG_EXEC);
887 if (cstat->type != CMD_INVALID) {
888 sudo_debug_printf(SUDO_DEBUG_INFO,
889 "sending status message to parent: [%d, %d]",
890 cstat->type, cstat->val);
892 n = send(fd, cstat, sizeof(*cstat), 0);
893 } while (n == -1 && errno == EINTR);
894 if (n != sizeof(*cstat)) {
895 sudo_debug_printf(SUDO_DEBUG_ERROR,
896 "unable to send status to parent: %s", strerror(errno));
898 cstat->type = CMD_INVALID; /* prevent re-sending */
904 * Wait for command status after receiving SIGCHLD.
905 * If the command was stopped, the status is send back to the parent.
906 * Otherwise, cstat is filled in but not sent.
907 * Returns true if command is still alive, else false.
910 handle_sigchld(int backchannel, struct command_status *cstat)
915 debug_decl(handle_sigchld, SUDO_DEBUG_EXEC);
917 /* read command status */
919 pid = waitpid(cmnd_pid, &status, WUNTRACED|WNOHANG);
920 } while (pid == -1 && errno == EINTR);
921 if (pid == cmnd_pid) {
922 if (cstat->type != CMD_ERRNO) {
923 char signame[SIG2STR_MAX];
925 cstat->type = CMD_WSTATUS;
927 if (WIFSTOPPED(status)) {
928 if (sig2str(WSTOPSIG(status), signame) == -1)
929 snprintf(signame, sizeof(signame), "%d", WSTOPSIG(status));
930 sudo_debug_printf(SUDO_DEBUG_INFO,
931 "command stopped, SIG%s", signame);
932 /* Saved the foreground pgid so we can restore it later. */
934 pid = tcgetpgrp(io_fds[SFD_SLAVE]);
935 } while (pid == -1 && errno == EINTR);
938 if (send_status(backchannel, cstat) == -1)
939 return alive; /* XXX */
940 } else if (WIFSIGNALED(status)) {
941 if (sig2str(WTERMSIG(status), signame) == -1)
942 snprintf(signame, sizeof(signame), "%d", WTERMSIG(status));
943 sudo_debug_printf(SUDO_DEBUG_INFO,
944 "command killed, SIG%s", signame);
946 sudo_debug_printf(SUDO_DEBUG_INFO, "command exited: %d",
947 WEXITSTATUS(status));
950 if (!WIFSTOPPED(status))
953 debug_return_bool(alive);
957 * Monitor process that creates a new session with the controlling tty,
958 * resets signal handlers and forks a child to call exec_pty().
959 * Waits for status changes from the command and relays them to the
960 * parent and relays signals from the parent to the command.
961 * Returns an error if fork(2) fails, else calls _exit(2).
964 exec_monitor(struct command_details *details, int backchannel)
966 struct command_status cstat;
970 int errpipe[2], maxfd, n;
973 debug_decl(exec_monitor, SUDO_DEBUG_EXEC);
975 /* Close unused fds. */
976 if (io_fds[SFD_MASTER] != -1)
977 close(io_fds[SFD_MASTER]);
978 if (io_fds[SFD_USERTTY] != -1)
979 close(io_fds[SFD_USERTTY]);
982 * We use a pipe to atomically handle signal notification within
985 if (pipe_nonblock(signal_pipe) != 0)
986 fatal(_("unable to create pipe"));
988 /* Reset SIGWINCH and SIGALRM. */
989 memset(&sa, 0, sizeof(sa));
990 sigemptyset(&sa.sa_mask);
991 sa.sa_flags = SA_RESTART;
992 sa.sa_handler = SIG_DFL;
993 sudo_sigaction(SIGWINCH, &sa, NULL);
994 sudo_sigaction(SIGALRM, &sa, NULL);
996 /* Ignore any SIGTTIN or SIGTTOU we get. */
997 sa.sa_handler = SIG_IGN;
998 sudo_sigaction(SIGTTIN, &sa, NULL);
999 sudo_sigaction(SIGTTOU, &sa, NULL);
1001 /* Block all signals in mon_handler(). */
1002 sigfillset(&sa.sa_mask);
1004 /* Note: HP-UX select() will not be interrupted if SA_RESTART set */
1005 sa.sa_flags = SA_INTERRUPT;
1007 sa.sa_flags |= SA_SIGINFO;
1008 sa.sa_sigaction = mon_handler;
1010 sa.sa_handler = mon_handler;
1012 sudo_sigaction(SIGCHLD, &sa, NULL);
1014 /* Catch common signals so we can cleanup properly. */
1015 sa.sa_flags = SA_RESTART;
1017 sa.sa_flags |= SA_SIGINFO;
1018 sa.sa_sigaction = mon_handler;
1020 sa.sa_handler = mon_handler;
1022 sudo_sigaction(SIGHUP, &sa, NULL);
1023 sudo_sigaction(SIGINT, &sa, NULL);
1024 sudo_sigaction(SIGQUIT, &sa, NULL);
1025 sudo_sigaction(SIGTERM, &sa, NULL);
1026 sudo_sigaction(SIGTSTP, &sa, NULL);
1027 sudo_sigaction(SIGUSR1, &sa, NULL);
1028 sudo_sigaction(SIGUSR2, &sa, NULL);
1031 * Start a new session with the parent as the session leader
1032 * and the slave pty as the controlling terminal.
1033 * This allows us to be notified when the command has been suspended.
1035 if (setsid() == -1) {
1039 if (io_fds[SFD_SLAVE] != -1) {
1041 if (ioctl(io_fds[SFD_SLAVE], TIOCSCTTY, NULL) != 0)
1042 fatal(_("unable to set controlling tty"));
1044 /* Set controlling tty by reopening slave. */
1045 if ((n = open(slavename, O_RDWR)) >= 0)
1050 mon_pgrp = getpgrp(); /* save a copy of our process group */
1053 * If stdin/stdout is not a tty, start command in the background
1054 * since it might be part of a pipeline that reads from /dev/tty.
1055 * In this case, we rely on the command receiving SIGTTOU or SIGTTIN
1056 * when it needs access to the controlling tty.
1061 /* Start command and wait for it to stop or exit */
1062 if (pipe(errpipe) == -1)
1063 fatal(_("unable to create pipe"));
1064 cmnd_pid = sudo_debug_fork();
1065 if (cmnd_pid == -1) {
1066 warning(_("unable to fork"));
1069 if (cmnd_pid == 0) {
1070 /* We pass errno back to our parent via pipe on exec failure. */
1072 close(signal_pipe[0]);
1073 close(signal_pipe[1]);
1075 fcntl(errpipe[1], F_SETFD, FD_CLOEXEC);
1078 /* setup tty and exec command */
1079 exec_pty(details, &cstat, &errpipe[1]);
1080 ignore_result(write(errpipe[1], &cstat, sizeof(cstat)));
1085 /* Send the command's pid to main sudo process. */
1086 cstat.type = CMD_PID;
1087 cstat.val = cmnd_pid;
1088 ignore_result(send(backchannel, &cstat, sizeof(cstat), 0));
1090 /* If any of stdin/stdout/stderr are pipes, close them in parent. */
1091 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1092 close(io_fds[SFD_STDIN]);
1093 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1094 close(io_fds[SFD_STDOUT]);
1095 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1096 close(io_fds[SFD_STDERR]);
1098 /* Put command in its own process group. */
1099 cmnd_pgrp = cmnd_pid;
1100 setpgid(cmnd_pid, cmnd_pgrp);
1102 /* Make the command the foreground process for the pty slave. */
1103 if (foreground && !ISSET(details->flags, CD_EXEC_BG)) {
1105 n = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
1106 } while (n == -1 && errno == EINTR);
1109 /* Wait for errno on pipe, signal on backchannel or for SIGCHLD */
1110 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
1111 fdsr = ecalloc(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1112 memset(&cstat, 0, sizeof(cstat));
1116 /* Check for signal on backchannel or errno on errpipe. */
1117 FD_SET(backchannel, fdsr);
1118 FD_SET(signal_pipe[0], fdsr);
1119 if (errpipe[0] != -1)
1120 FD_SET(errpipe[0], fdsr);
1121 maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
1123 /* If command exited we just poll, there may be data on errpipe. */
1124 n = select(maxfd + 1, fdsr, NULL, NULL, alive ? NULL : &tv);
1128 if (errno == EINTR || errno == ENOMEM)
1130 warning("monitor: %s", _("select failed"));
1134 if (FD_ISSET(signal_pipe[0], fdsr)) {
1135 n = read(signal_pipe[0], &signo, sizeof(signo));
1137 if (errno == EINTR || errno == EAGAIN)
1139 warning(_("error reading from signal pipe"));
1143 * Handle SIGCHLD specially and deliver other signals
1144 * directly to the command.
1146 if (signo == SIGCHLD) {
1147 if (!handle_sigchld(backchannel, &cstat))
1150 deliver_signal(cmnd_pid, signo, false);
1154 if (errpipe[0] != -1 && FD_ISSET(errpipe[0], fdsr)) {
1155 /* read errno or EOF from command pipe */
1156 n = read(errpipe[0], &cstat, sizeof(cstat));
1160 warning(_("error reading from pipe"));
1163 /* Got errno or EOF, either way we are done with errpipe. */
1164 FD_CLR(errpipe[0], fdsr);
1168 if (FD_ISSET(backchannel, fdsr)) {
1169 struct command_status cstmp;
1171 /* read command from backchannel, should be a signal */
1172 n = recv(backchannel, &cstmp, sizeof(cstmp), 0);
1176 warning(_("error reading from socketpair"));
1179 if (cstmp.type != CMD_SIGNO) {
1180 warningx(_("unexpected reply type on backchannel: %d"),
1184 deliver_signal(cmnd_pid, cstmp.val, true);
1190 /* XXX An error occurred, should send an error back. */
1191 kill(cmnd_pid, SIGKILL);
1193 /* Send parent status. */
1194 send_status(backchannel, &cstat);
1196 sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, 1);
1200 debug_return_int(errno);
1204 * Flush any output buffered in iobufs or readable from the fds.
1205 * Does not read from /dev/tty.
1210 struct io_buffer *iob;
1212 fd_set *fdsr, *fdsw;
1213 int nready, nwriters, maxfd = -1;
1214 debug_decl(flush_output, SUDO_DEBUG_EXEC);
1216 /* Determine maxfd */
1217 for (iob = iobufs; iob; iob = iob->next) {
1218 if (iob->rfd > maxfd)
1220 if (iob->wfd > maxfd)
1226 fdsr = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1227 fdsw = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1229 memset(fdsw, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1230 memset(fdsr, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1233 for (iob = iobufs; iob; iob = iob->next) {
1234 /* Don't read from /dev/tty while flushing. */
1235 if (io_fds[SFD_USERTTY] != -1 && iob->rfd == io_fds[SFD_USERTTY])
1237 if (iob->rfd == -1 && iob->wfd == -1)
1239 if (iob->off == iob->len) {
1240 iob->off = iob->len = 0;
1241 /* Forward the EOF from reader to writer. */
1242 if (iob->rfd == -1) {
1243 safe_close(iob->wfd);
1247 if (iob->rfd != -1) {
1248 if (iob->len != sizeof(iob->buf))
1249 FD_SET(iob->rfd, fdsr);
1251 if (iob->wfd != -1) {
1252 if (iob->len > iob->off) {
1254 FD_SET(iob->wfd, fdsw);
1259 /* Don't sleep in select if there are no buffers that need writing. */
1262 nready = select(maxfd + 1, fdsr, fdsw, NULL, nwriters ? NULL : &tv);
1265 break; /* all I/O flushed */
1266 if (errno == EINTR || errno == ENOMEM)
1268 warning(_("select failed"));
1270 if (perform_io(fdsr, fdsw, NULL) != 0 || nready == -1)
1279 * Sets up std{in,out,err} and executes the actual command.
1280 * Returns only if execve() fails.
1283 exec_pty(struct command_details *details,
1284 struct command_status *cstat, int *errfd)
1286 pid_t self = getpid();
1287 debug_decl(exec_pty, SUDO_DEBUG_EXEC);
1289 /* Register cleanup function */
1290 fatal_callback_register(pty_cleanup);
1292 /* Set command process group here too to avoid a race. */
1295 /* Wire up standard fds, note that stdout/stderr may be pipes. */
1296 if (dup2(io_fds[SFD_STDIN], STDIN_FILENO) == -1 ||
1297 dup2(io_fds[SFD_STDOUT], STDOUT_FILENO) == -1 ||
1298 dup2(io_fds[SFD_STDERR], STDERR_FILENO) == -1)
1301 /* Wait for parent to grant us the tty if we are foreground. */
1302 if (foreground && !ISSET(details->flags, CD_EXEC_BG)) {
1303 while (tcgetpgrp(io_fds[SFD_SLAVE]) != self)
1307 /* We have guaranteed that the slave fd is > 2 */
1308 if (io_fds[SFD_SLAVE] != -1)
1309 close(io_fds[SFD_SLAVE]);
1310 if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1311 close(io_fds[SFD_STDIN]);
1312 if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1313 close(io_fds[SFD_STDOUT]);
1314 if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1315 close(io_fds[SFD_STDERR]);
1317 /* Execute command; only returns on error. */
1318 exec_cmnd(details, cstat, errfd);
1324 * Propagates tty size change signals to pty being used by the command.
1327 sync_ttysize(int src, int dst)
1330 struct winsize wsize;
1332 debug_decl(sync_ttysize, SUDO_DEBUG_EXEC);
1334 if (ioctl(src, TIOCGWINSZ, &wsize) == 0) {
1335 ioctl(dst, TIOCSWINSZ, &wsize);
1336 if ((pgrp = tcgetpgrp(dst)) != -1)
1337 killpg(pgrp, SIGWINCH);
1345 * Handler for SIGWINCH in parent.
1352 sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
1357 * Only close the fd if it is not /dev/tty or std{in,out,err}.
1358 * Return value is the same as send(2).
1363 debug_decl(safe_close, SUDO_DEBUG_EXEC);
1365 /* Avoid closing /dev/tty or std{in,out,err}. */
1366 if (fd < 3 || fd == io_fds[SFD_USERTTY]) {
1368 debug_return_int(-1);
1370 debug_return_int(close(fd));