File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / sudo / src / exec.c
Revision 1.1.1.5 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Mon Oct 14 07:56:35 2013 UTC (10 years, 9 months ago) by misho
Branches: sudo, MAIN
CVS tags: v1_8_8p0, v1_8_8, HEAD
v 1.8.8

    1: /*
    2:  * Copyright (c) 2009-2013 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: #ifdef HAVE_SYS_SYSMACROS_H
   21: # include <sys/sysmacros.h>
   22: #endif
   23: #include <sys/socket.h>
   24: #include <sys/stat.h>
   25: #include <sys/time.h>
   26: #include <sys/wait.h>
   27: #include <sys/ioctl.h>
   28: #ifdef HAVE_SYS_SELECT_H
   29: # include <sys/select.h>
   30: #endif /* HAVE_SYS_SELECT_H */
   31: #include <stdio.h>
   32: #ifdef STDC_HEADERS
   33: # include <stdlib.h>
   34: # include <stddef.h>
   35: #else
   36: # ifdef HAVE_STDLIB_H
   37: #  include <stdlib.h>
   38: # endif
   39: #endif /* STDC_HEADERS */
   40: #ifdef HAVE_STRING_H
   41: # include <string.h>
   42: #endif /* HAVE_STRING_H */
   43: #ifdef HAVE_STRINGS_H
   44: # include <strings.h>
   45: #endif /* HAVE_STRINGS_H */
   46: #ifdef HAVE_UNISTD_H
   47: # include <unistd.h>
   48: #endif /* HAVE_UNISTD_H */
   49: #if TIME_WITH_SYS_TIME
   50: # include <time.h>
   51: #endif
   52: #include <errno.h>
   53: #include <fcntl.h>
   54: #include <signal.h>
   55: #include <termios.h>
   56: 
   57: #include "sudo.h"
   58: #include "sudo_exec.h"
   59: #include "sudo_plugin.h"
   60: #include "sudo_plugin_int.h"
   61: 
   62: /* We keep a tailq of signals to forward to child. */
   63: struct sigforward {
   64:     struct sigforward *prev, *next;
   65:     int signo;
   66: };
   67: TQ_DECLARE(sigforward)
   68: static struct sigforward_list sigfwd_list;
   69: static pid_t ppgrp = -1;
   70: 
   71: volatile pid_t cmnd_pid = -1;
   72: 
   73: static int dispatch_signals(int sv[2], pid_t child, int log_io,
   74:     struct command_status *cstat);
   75: static int dispatch_pending_signals(struct command_status *cstat);
   76: static void forward_signals(int fd);
   77: static void schedule_signal(int signo);
   78: #ifdef SA_SIGINFO
   79: static void handler_user_only(int s, siginfo_t *info, void *context);
   80: #endif
   81: 
   82: /*
   83:  * Fork and execute a command, returns the child's pid.
   84:  * Sends errno back on sv[1] if execve() fails.
   85:  */
   86: static int fork_cmnd(struct command_details *details, int sv[2])
   87: {
   88:     struct command_status cstat;
   89:     sigaction_t sa;
   90:     debug_decl(fork_cmnd, SUDO_DEBUG_EXEC)
   91: 
   92:     ppgrp = getpgrp();	/* parent's process group */
   93: 
   94:     /*
   95:      * Handle suspend/restore of sudo and the command.
   96:      * In most cases, the command will be in the same process group as
   97:      * sudo and job control will "just work".  However, if the command
   98:      * changes its process group ID and does not change it back (or is
   99:      * kill by SIGSTOP which is not catchable), we need to resume the
  100:      * command manually.  Also, if SIGTSTP is sent directly to sudo,
  101:      * we need to suspend the command, and then suspend ourself, restoring
  102:      * the default SIGTSTP handler temporarily.
  103:      *
  104:      * XXX - currently we send SIGCONT upon resume in some cases where
  105:      * we don't need to (e.g. command pgrp == parent pgrp).
  106:      */
  107:     memset(&sa, 0, sizeof(sa));
  108:     sigfillset(&sa.sa_mask);
  109:     sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
  110: #ifdef SA_SIGINFO
  111:     sa.sa_flags |= SA_SIGINFO;
  112:     sa.sa_sigaction = handler;
  113: #else
  114:     sa.sa_handler = handler;
  115: #endif
  116:     sudo_sigaction(SIGCONT, &sa, NULL);
  117: #ifdef SA_SIGINFO
  118:     sa.sa_sigaction = handler_user_only;
  119: #endif
  120:     sudo_sigaction(SIGTSTP, &sa, NULL);
  121: 
  122:     /*
  123:      * The policy plugin's session init must be run before we fork
  124:      * or certain pam modules won't be able to track their state.
  125:      */
  126:     if (policy_init_session(details) != true)
  127: 	fatalx(_("policy plugin failed session initialization"));
  128: 
  129:     cmnd_pid = sudo_debug_fork();
  130:     switch (cmnd_pid) {
  131:     case -1:
  132: 	fatal(_("unable to fork"));
  133: 	break;
  134:     case 0:
  135: 	/* child */
  136: 	close(sv[0]);
  137: 	close(signal_pipe[0]);
  138: 	close(signal_pipe[1]);
  139: 	fcntl(sv[1], F_SETFD, FD_CLOEXEC);
  140: 	exec_cmnd(details, &cstat, &sv[1]);
  141: 	send(sv[1], &cstat, sizeof(cstat), 0);
  142: 	sudo_debug_exit_int(__func__, __FILE__, __LINE__, sudo_debug_subsys, 1);
  143: 	_exit(1);
  144:     }
  145:     sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d", details->command,
  146: 	(int)cmnd_pid);
  147:     debug_return_int(cmnd_pid);
  148: }
  149: 
  150: /*
  151:  * Setup the execution environment and execute the command.
  152:  * If SELinux is enabled, run the command via sesh, otherwise
  153:  * execute it directly.
  154:  * If the exec fails, cstat is filled in with the value of errno.
  155:  */
  156: void
  157: exec_cmnd(struct command_details *details, struct command_status *cstat,
  158:     int *errfd)
  159: {
  160:     debug_decl(exec_cmnd, SUDO_DEBUG_EXEC)
  161: 
  162:     restore_signals();
  163:     if (exec_setup(details, NULL, -1) == true) {
  164: 	/* headed for execve() */
  165: 	sudo_debug_execve(SUDO_DEBUG_INFO, details->command,
  166: 	    details->argv, details->envp);
  167: 	if (details->closefrom >= 0) {
  168: 	    int maxfd = details->closefrom;
  169: 	    /* Preserve back channel if present. */
  170: 	    if (errfd != NULL) {
  171: 		dup2(*errfd, maxfd);
  172: 		(void)fcntl(maxfd, F_SETFD, FD_CLOEXEC);
  173: 		*errfd = maxfd++;
  174: 	    }
  175: 	    if (sudo_debug_fd_set(maxfd) != -1)
  176: 		maxfd++;
  177: 	    closefrom(maxfd);
  178: 	}
  179: #ifdef HAVE_SELINUX
  180: 	if (ISSET(details->flags, CD_RBAC_ENABLED)) {
  181: 	    selinux_execve(details->command, details->argv, details->envp,
  182: 		ISSET(details->flags, CD_NOEXEC));
  183: 	} else
  184: #endif
  185: 	{
  186: 	    sudo_execve(details->command, details->argv, details->envp,
  187: 		ISSET(details->flags, CD_NOEXEC));
  188: 	}
  189: 	cstat->type = CMD_ERRNO;
  190: 	cstat->val = errno;
  191: 	sudo_debug_printf(SUDO_DEBUG_ERROR, "unable to exec %s: %s",
  192: 	    details->command, strerror(errno));
  193:     }
  194:     debug_return;
  195: }
  196: 
  197: /*
  198:  * Execute a command, potentially in a pty with I/O loggging, and
  199:  * wait for it to finish.
  200:  * This is a little bit tricky due to how POSIX job control works and
  201:  * we fact that we have two different controlling terminals to deal with.
  202:  */
  203: int
  204: sudo_execute(struct command_details *details, struct command_status *cstat)
  205: {
  206:     int maxfd, n, nready, sv[2];
  207:     const char *utmp_user = NULL;
  208:     bool log_io = false;
  209:     fd_set *fdsr, *fdsw;
  210:     sigaction_t sa;
  211:     sigset_t omask;
  212:     pid_t child;
  213:     debug_decl(sudo_execute, SUDO_DEBUG_EXEC)
  214: 
  215:     dispatch_pending_signals(cstat);
  216: 
  217:     /* If running in background mode, fork and exit. */
  218:     if (ISSET(details->flags, CD_BACKGROUND)) {
  219: 	switch (sudo_debug_fork()) {
  220: 	    case -1:
  221: 		cstat->type = CMD_ERRNO;
  222: 		cstat->val = errno;
  223: 		debug_return_int(-1);
  224: 	    case 0:
  225: 		/* child continues without controlling terminal */
  226: 		(void)setpgid(0, 0);
  227: 		break;
  228: 	    default:
  229: 		/* parent exits (but does not flush buffers) */
  230: 		sudo_debug_exit_int(__func__, __FILE__, __LINE__,
  231: 		    sudo_debug_subsys, 0);
  232: 		_exit(0);
  233: 	}
  234:     }
  235: 
  236:     /*
  237:      * If we have an I/O plugin or the policy plugin has requested one, we
  238:      * need to allocate a pty.  It is OK to set log_io in the pty-only case
  239:      * as the io plugin tailqueue will be empty and no I/O logging will occur.
  240:      */
  241:     if (!tq_empty(&io_plugins) || ISSET(details->flags, CD_USE_PTY)) {
  242: 	log_io = true;
  243: 	if (ISSET(details->flags, CD_SET_UTMP))
  244: 	    utmp_user = details->utmp_user ? details->utmp_user : user_details.username;
  245: 	sudo_debug_printf(SUDO_DEBUG_INFO, "allocate pty for I/O logging");
  246: 	pty_setup(details->euid, user_details.tty, utmp_user);
  247:     } else if (!ISSET(details->flags, CD_SET_TIMEOUT) &&
  248: 	policy_plugin.u.policy->close == NULL) {
  249: 	/* If no I/O logging, timeout or policy close we can exec directly. */
  250: 	exec_cmnd(details, cstat, NULL);
  251: 	goto done;
  252:     }
  253: 
  254:     /*
  255:      * We communicate with the child over a bi-directional pair of sockets.
  256:      * Parent sends signal info to child and child sends back wait status.
  257:      */
  258:     if (socketpair(PF_UNIX, SOCK_DGRAM, 0, sv) == -1)
  259: 	fatal(_("unable to create sockets"));
  260: 
  261:     /*
  262:      * Signals to forward to the child process (excluding SIGALRM and SIGCHLD).
  263:      * We block all other signals while running the signal handler.
  264:      * Note: HP-UX select() will not be interrupted if SA_RESTART set.
  265:      */
  266:     memset(&sa, 0, sizeof(sa));
  267:     sigfillset(&sa.sa_mask);
  268:     sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
  269: #ifdef SA_SIGINFO
  270:     sa.sa_flags |= SA_SIGINFO;
  271:     sa.sa_sigaction = handler;
  272: #else
  273:     sa.sa_handler = handler;
  274: #endif
  275:     sudo_sigaction(SIGTERM, &sa, NULL);
  276:     sudo_sigaction(SIGALRM, &sa, NULL); /* XXX - only if there is a timeout */
  277:     sudo_sigaction(SIGCHLD, &sa, NULL);
  278:     sudo_sigaction(SIGPIPE, &sa, NULL);
  279:     sudo_sigaction(SIGUSR1, &sa, NULL);
  280:     sudo_sigaction(SIGUSR2, &sa, NULL);
  281: 
  282:     /*
  283:      * When not running the command in a pty, we do not want to
  284:      * forward signals generated by the kernel that the child will
  285:      * already have received either by virtue of being in the
  286:      * controlling tty's process group (SIGINT, SIGQUIT) or because
  287:      * the session is terminating (SIGHUP).
  288:      */
  289: #ifdef SA_SIGINFO
  290:     if (!log_io) {
  291: 	sa.sa_flags |= SA_SIGINFO;
  292: 	sa.sa_sigaction = handler_user_only;
  293:     }
  294: #endif
  295:     sudo_sigaction(SIGHUP, &sa, NULL);
  296:     sudo_sigaction(SIGINT, &sa, NULL);
  297:     sudo_sigaction(SIGQUIT, &sa, NULL);
  298: 
  299:     /* Max fd we will be selecting on. */
  300:     maxfd = MAX(sv[0], signal_pipe[0]);
  301: 
  302:     /*
  303:      * Child will run the command in the pty, parent will pass data
  304:      * to and from pty.  Adjusts maxfd as needed.
  305:      */
  306:     if (log_io)
  307: 	child = fork_pty(details, sv, &maxfd, &omask);
  308:     else
  309: 	child = fork_cmnd(details, sv);
  310:     close(sv[1]);
  311: 
  312:     /* Set command timeout if specified. */
  313:     if (ISSET(details->flags, CD_SET_TIMEOUT))
  314: 	alarm(details->timeout);
  315: 
  316:     /*
  317:      * I/O logging must be in the C locale for floating point numbers
  318:      * to be logged consistently.
  319:      */
  320:     setlocale(LC_ALL, "C");
  321: 
  322:     /*
  323:      * In the event loop we pass input from user tty to master
  324:      * and pass output from master to stdout and IO plugin.
  325:      */
  326:     fdsr = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
  327:     fdsw = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
  328:     for (;;) {
  329: 	memset(fdsw, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
  330: 	memset(fdsr, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
  331: 
  332: 	FD_SET(signal_pipe[0], fdsr);
  333: 	FD_SET(sv[0], fdsr);
  334: 	if (!tq_empty(&sigfwd_list))
  335: 	    FD_SET(sv[0], fdsw);
  336: 	if (log_io)
  337: 	    fd_set_iobs(fdsr, fdsw); /* XXX - better name */
  338: 	nready = select(maxfd + 1, fdsr, fdsw, NULL, NULL);
  339: 	sudo_debug_printf(SUDO_DEBUG_DEBUG, "select returns %d", nready);
  340: 	if (nready == -1) {
  341: 	    if (errno == EINTR || errno == ENOMEM)
  342: 		continue;
  343: 	    if (errno == EBADF || errno == EIO) {
  344: 		/* One of the ttys must have gone away. */
  345: 		goto do_tty_io;
  346: 	    }
  347: 	    warning(_("select failed"));
  348: 	    sudo_debug_printf(SUDO_DEBUG_ERROR,
  349: 		"select failure, terminating child");
  350: 	    schedule_signal(SIGKILL);
  351: 	    forward_signals(sv[0]);
  352: 	    break;
  353: 	}
  354: 	if (FD_ISSET(sv[0], fdsw)) {
  355: 	    forward_signals(sv[0]);
  356: 	}
  357: 	if (FD_ISSET(signal_pipe[0], fdsr)) {
  358: 	    n = dispatch_signals(sv, child, log_io, cstat);
  359: 	    if (n == 0) {
  360: 		/* Child has exited, cstat is set, we are done. */
  361: 		break;
  362: 	    }
  363: 	    if (n == -1) {
  364: 		/* Error reading signal_pipe[0], should not happen. */
  365: 		break;
  366: 	    }
  367: 	    /* Restart event loop so signals get sent to child immediately. */
  368: 	    continue;
  369: 	}
  370: 	if (FD_ISSET(sv[0], fdsr)) {
  371: 	    /* read child status */
  372: 	    n = recv(sv[0], cstat, sizeof(*cstat), 0);
  373: 	    if (n != sizeof(*cstat)) {
  374: 		if (n == -1) {
  375: 		    if (errno == EINTR)
  376: 			continue;
  377: 		    /*
  378: 		     * If not logging I/O we may receive ECONNRESET when
  379: 		     * the command is executed and sv is closed.
  380: 		     * It is safe to ignore this.
  381: 		     */
  382: 		    if (log_io && errno != EAGAIN) {
  383: 			cstat->type = CMD_ERRNO;
  384: 			cstat->val = errno;
  385: 			break;
  386: 		    }
  387: 		    sudo_debug_printf(SUDO_DEBUG_ERROR,
  388: 			"failed to read child status: %s", strerror(errno));
  389: 		} else {
  390: 		    /* Short read or EOF. */
  391: 		    sudo_debug_printf(SUDO_DEBUG_ERROR,
  392: 			"failed to read child status: %s",
  393: 			n ? "short read" : "EOF");
  394: 		    /* XXX - should set cstat */
  395: 		    break;
  396: 		}
  397: 	    }
  398: 	    if (cstat->type == CMD_PID) {
  399: 		/*
  400:                  * Once we know the command's pid we can unblock
  401:                  * signals which ere blocked in fork_pty().  This
  402:                  * avoids a race between exec of the command and
  403:                  * receipt of a fatal signal from it.
  404: 		 */
  405: 		cmnd_pid = cstat->val;
  406: 		sudo_debug_printf(SUDO_DEBUG_INFO, "executed %s, pid %d",
  407: 		    details->command, (int)cmnd_pid);
  408: 		if (log_io)
  409: 		    sigprocmask(SIG_SETMASK, &omask, NULL);
  410: 	    } else if (cstat->type == CMD_WSTATUS) {
  411: 		if (WIFSTOPPED(cstat->val)) {
  412: 		    /* Suspend parent and tell child how to resume on return. */
  413: 		    sudo_debug_printf(SUDO_DEBUG_INFO,
  414: 			"child stopped, suspending parent");
  415: 		    n = suspend_parent(WSTOPSIG(cstat->val));
  416: 		    schedule_signal(n);
  417: 		    continue;
  418: 		} else {
  419: 		    /* Child exited or was killed, either way we are done. */
  420: 		    sudo_debug_printf(SUDO_DEBUG_INFO, "child exited or was killed");
  421: 		    break;
  422: 		}
  423: 	    } else if (cstat->type == CMD_ERRNO) {
  424: 		/* Child was unable to execute command or broken pipe. */
  425: 		sudo_debug_printf(SUDO_DEBUG_INFO, "errno from child: %s",
  426: 		    strerror(cstat->val));
  427: 		break;
  428: 	    }
  429: 	}
  430: do_tty_io:
  431: 	if (perform_io(fdsr, fdsw, cstat) != 0) {
  432: 	    /* I/O error, kill child if still alive and finish. */
  433: 	    sudo_debug_printf(SUDO_DEBUG_ERROR, "I/O error, terminating child");
  434: 	    schedule_signal(SIGKILL);
  435: 	    forward_signals(sv[0]);
  436: 	    break;
  437: 	}
  438:     }
  439: 
  440:     if (log_io) {
  441: 	/* Flush any remaining output and free pty-related memory. */
  442: 	pty_close(cstat);
  443:    }
  444: 
  445: #ifdef HAVE_SELINUX
  446:     if (ISSET(details->flags, CD_RBAC_ENABLED)) {
  447: 	/* This is probably not needed in log_io mode. */
  448: 	if (selinux_restore_tty() != 0)
  449: 	    warningx(_("unable to restore tty label"));
  450:     }
  451: #endif
  452: 
  453:     efree(fdsr);
  454:     efree(fdsw);
  455:     while (!tq_empty(&sigfwd_list)) {
  456: 	struct sigforward *sigfwd = tq_first(&sigfwd_list);
  457: 	tq_remove(&sigfwd_list, sigfwd);
  458: 	efree(sigfwd);
  459:     }
  460: done:
  461:     debug_return_int(cstat->type == CMD_ERRNO ? -1 : 0);
  462: }
  463: 
  464: /*
  465:  * Read signals on signal_pipe written by handler().
  466:  * Returns -1 on error, 0 on child exit, else 1.
  467:  */
  468: static int
  469: dispatch_signals(int sv[2], pid_t child, int log_io, struct command_status *cstat)
  470: {
  471:     char signame[SIG2STR_MAX];
  472:     unsigned char signo;
  473:     ssize_t nread;
  474:     int status;
  475:     pid_t pid;
  476:     debug_decl(dispatch_signals, SUDO_DEBUG_EXEC)
  477: 
  478:     for (;;) {
  479: 	/* read signal pipe */
  480: 	nread = read(signal_pipe[0], &signo, sizeof(signo));
  481: 	if (nread <= 0) {
  482: 	    /* It should not be possible to get EOF but just in case. */
  483: 	    if (nread == 0)
  484: 		errno = ECONNRESET;
  485: 	    /* Restart if interrupted by signal so the pipe doesn't fill. */
  486: 	    if (errno == EINTR)
  487: 		continue;
  488: 	    /* If pipe is empty, we are done. */
  489: 	    if (errno == EAGAIN)
  490: 		break;
  491: 	    sudo_debug_printf(SUDO_DEBUG_ERROR, "error reading signal pipe %s",
  492: 		strerror(errno));
  493: 	    cstat->type = CMD_ERRNO;
  494: 	    cstat->val = errno;
  495: 	    debug_return_int(-1);
  496: 	}
  497: 	if (sig2str(signo, signame) == -1)
  498: 	    snprintf(signame, sizeof(signame), "%d", signo);
  499: 	sudo_debug_printf(SUDO_DEBUG_DIAG, "received SIG%s", signame);
  500: 	if (signo == SIGCHLD) {
  501: 	    /*
  502: 	     * If logging I/O, child is the intermediate process,
  503: 	     * otherwise it is the command itself.
  504: 	     */
  505: 	    do {
  506: 		pid = waitpid(child, &status, WUNTRACED|WNOHANG);
  507: 	    } while (pid == -1 && errno == EINTR);
  508: 	    if (pid == child) {
  509: 		if (log_io) {
  510: 		    /*
  511: 		     * On BSD we get ECONNRESET on sv[0] if monitor dies
  512: 		     * and select() will return with sv[0] readable.
  513: 		     * On Linux that doesn't appear to happen so if the
  514: 		     * monitor dies, shut down the socketpair to force a
  515: 		     * select() notification.
  516: 		     */
  517: 		    (void) shutdown(sv[0], SHUT_WR);
  518: 		} else if (WIFSTOPPED(status)) {
  519: 		    /*
  520: 		     * Save the controlling terminal's process group
  521: 		     * so we can restore it after we resume, if needed.
  522: 		     * Most well-behaved shells change the pgrp back to
  523: 		     * its original value before suspending so we must
  524: 		     * not try to restore in that case, lest we race with
  525: 		     * the child upon resume, potentially stopping sudo
  526: 		     * with SIGTTOU while the command continues to run.
  527: 		     */
  528: 		    sigaction_t sa, osa;
  529: 		    pid_t saved_pgrp = (pid_t)-1;
  530: 		    int signo = WSTOPSIG(status);
  531: 		    int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
  532: 		    if (fd != -1) {
  533: 			saved_pgrp = tcgetpgrp(fd);
  534: 			/*
  535: 			 * Child was stopped trying to access controlling
  536: 			 * terminal.  If the child has a different pgrp
  537: 			 * and we own the controlling terminal, give it
  538: 			 * to the child's pgrp and let it continue.
  539: 			 */
  540: 			if (signo == SIGTTOU || signo == SIGTTIN) {
  541: 			    if (saved_pgrp == ppgrp) {
  542: 				pid_t child_pgrp = getpgid(child);
  543: 				if (child_pgrp != ppgrp) {
  544: 				    if (tcsetpgrp(fd, child_pgrp) == 0) {
  545: 					if (killpg(child_pgrp, SIGCONT) != 0) {
  546: 					    warning("kill(%d, SIGCONT)",
  547: 						(int)child_pgrp);
  548: 					}
  549: 					close(fd);
  550: 					debug_return_int(1);
  551: 				    }
  552: 				}
  553: 			    }
  554: 			}
  555: 		    }
  556: 		    if (signo == SIGTSTP) {
  557: 			memset(&sa, 0, sizeof(sa));
  558: 			sigemptyset(&sa.sa_mask);
  559: 			sa.sa_flags = SA_RESTART;
  560: 			sa.sa_handler = SIG_DFL;
  561: 			sudo_sigaction(SIGTSTP, &sa, &osa);
  562: 		    }
  563: 		    if (kill(getpid(), signo) != 0)
  564: 			warning("kill(%d, SIG%s)", (int)getpid(), signame);
  565: 		    if (signo == SIGTSTP)
  566: 			sudo_sigaction(SIGTSTP, &osa, NULL);
  567: 		    if (fd != -1) {
  568: 			/*
  569: 			 * Restore command's process group if different.
  570: 			 * Otherwise, we cannot resume some shells.
  571: 			 */
  572: 			if (saved_pgrp != ppgrp)
  573: 			    (void)tcsetpgrp(fd, saved_pgrp);
  574: 			close(fd);
  575: 		    }
  576: 		} else {
  577: 		    /* Child has exited or been killed, we are done. */
  578: 		    cstat->type = CMD_WSTATUS;
  579: 		    cstat->val = status;
  580: 		    debug_return_int(0);
  581: 		}
  582: 	    }
  583: 	} else {
  584: 	    if (log_io) {
  585: 		/* Schedule signo to be forwared to the child. */
  586: 		schedule_signal(signo);
  587: 	    } else {
  588: 		/* Nothing listening on sv[0], send directly. */
  589: 		if (signo == SIGALRM)
  590: 		    terminate_command(child, false);
  591: 		else if (kill(child, signo) != 0)
  592: 		    warning("kill(%d, SIG%s)", (int)child, signame);
  593: 	    }
  594: 	}
  595:     }
  596:     debug_return_int(1);
  597: }
  598: 
  599: /*
  600:  * Drain pending signals from signale_pipe written by sudo_handler().
  601:  * Handles the case where the signal was sent to us before
  602:  * we have executed the command.
  603:  * Returns 1 if we should terminate, else 0.
  604:  */
  605: static int
  606: dispatch_pending_signals(struct command_status *cstat)
  607: {
  608:     ssize_t nread;
  609:     struct sigaction sa;
  610:     unsigned char signo = 0;
  611:     int rval = 0;
  612:     debug_decl(dispatch_pending_signals, SUDO_DEBUG_EXEC)
  613: 
  614:     for (;;) {
  615: 	nread = read(signal_pipe[0], &signo, sizeof(signo));
  616: 	if (nread <= 0) {
  617: 	    /* It should not be possible to get EOF but just in case. */
  618: 	    if (nread == 0)
  619: 		errno = ECONNRESET;
  620: 	    /* Restart if interrupted by signal so the pipe doesn't fill. */
  621: 	    if (errno == EINTR)
  622: 		continue;
  623: 	    /* If pipe is empty, we are done. */
  624: 	    if (errno == EAGAIN)
  625: 		break;
  626: 	    sudo_debug_printf(SUDO_DEBUG_ERROR, "error reading signal pipe %s",
  627: 		strerror(errno));
  628: 	    cstat->type = CMD_ERRNO;
  629: 	    cstat->val = errno;
  630: 	    rval = 1;
  631: 	    break;
  632: 	}
  633: 	/* Take the first terminal signal. */
  634: 	if (signo == SIGINT || signo == SIGQUIT) {
  635: 	    cstat->type = CMD_WSTATUS;
  636: 	    cstat->val = signo + 128;
  637: 	    rval = 1;
  638: 	    break;
  639: 	}
  640:     }
  641:     /* Only stop if we haven't already been terminated. */
  642:     if (signo == SIGTSTP)
  643:     {
  644: 	memset(&sa, 0, sizeof(sa));
  645: 	sigemptyset(&sa.sa_mask);
  646: 	sa.sa_flags = SA_RESTART;
  647: 	sa.sa_handler = SIG_DFL;
  648: 	sudo_sigaction(SIGTSTP, &sa, NULL);
  649: 	if (kill(getpid(), SIGTSTP) != 0)
  650: 	    warning("kill(%d, SIGTSTP)", (int)getpid());
  651: 	/* No need to reinstall SIGTSTP handler. */
  652:     }
  653:     debug_return_int(rval);
  654: }
  655: 
  656: /*
  657:  * Forward signals in sigfwd_list to child listening on fd.
  658:  */
  659: static void
  660: forward_signals(int sock)
  661: {
  662:     char signame[SIG2STR_MAX];
  663:     struct sigforward *sigfwd;
  664:     struct command_status cstat;
  665:     ssize_t nsent;
  666:     debug_decl(forward_signals, SUDO_DEBUG_EXEC)
  667: 
  668:     while (!tq_empty(&sigfwd_list)) {
  669: 	sigfwd = tq_first(&sigfwd_list);
  670: 	if (sigfwd->signo == SIGCONT_FG)
  671: 	    strlcpy(signame, "CONT_FG", sizeof(signame));
  672: 	else if (sigfwd->signo == SIGCONT_BG)
  673: 	    strlcpy(signame, "CONT_BG", sizeof(signame));
  674: 	else if (sig2str(sigfwd->signo, signame) == -1)
  675: 	    snprintf(signame, sizeof(signame), "%d", sigfwd->signo);
  676: 	sudo_debug_printf(SUDO_DEBUG_INFO,
  677: 	    "sending SIG%s to child over backchannel", signame);
  678: 	cstat.type = CMD_SIGNO;
  679: 	cstat.val = sigfwd->signo;
  680: 	do {
  681: 	    nsent = send(sock, &cstat, sizeof(cstat), 0);
  682: 	} while (nsent == -1 && errno == EINTR);
  683: 	tq_remove(&sigfwd_list, sigfwd);
  684: 	efree(sigfwd);
  685: 	if (nsent != sizeof(cstat)) {
  686: 	    if (errno == EPIPE) {
  687: 		sudo_debug_printf(SUDO_DEBUG_ERROR,
  688: 		    "broken pipe writing to child over backchannel");
  689: 		/* Other end of socket gone, empty out sigfwd_list. */
  690: 		while (!tq_empty(&sigfwd_list)) {
  691: 		    sigfwd = tq_first(&sigfwd_list);
  692: 		    tq_remove(&sigfwd_list, sigfwd);
  693: 		    efree(sigfwd);
  694: 		}
  695: 		/* XXX - child (monitor) is dead, we should exit too? */
  696: 	    }
  697: 	    break;
  698: 	}
  699:     }
  700:     debug_return;
  701: }
  702: 
  703: /*
  704:  * Schedule a signal to be forwared.
  705:  */
  706: static void
  707: schedule_signal(int signo)
  708: {
  709:     struct sigforward *sigfwd;
  710:     char signame[SIG2STR_MAX];
  711:     debug_decl(schedule_signal, SUDO_DEBUG_EXEC)
  712: 
  713:     if (signo == SIGCONT_FG)
  714: 	strlcpy(signame, "CONT_FG", sizeof(signame));
  715:     else if (signo == SIGCONT_BG)
  716: 	strlcpy(signame, "CONT_BG", sizeof(signame));
  717:     else if (sig2str(signo, signame) == -1)
  718: 	snprintf(signame, sizeof(signame), "%d", signo);
  719:     sudo_debug_printf(SUDO_DEBUG_DIAG, "scheduled SIG%s for child", signame);
  720: 
  721:     sigfwd = ecalloc(1, sizeof(*sigfwd));
  722:     sigfwd->prev = sigfwd;
  723:     /* sigfwd->next = NULL; */
  724:     sigfwd->signo = signo;
  725:     tq_append(&sigfwd_list, sigfwd);
  726: 
  727:     debug_return;
  728: }
  729: 
  730: /*
  731:  * Generic handler for signals passed from parent -> child.
  732:  * The other end of signal_pipe is checked in the main event loop.
  733:  */
  734: #ifdef SA_SIGINFO
  735: void
  736: handler(int s, siginfo_t *info, void *context)
  737: {
  738:     unsigned char signo = (unsigned char)s;
  739: 
  740:     /*
  741:      * If the signal came from the command we ran, just ignore
  742:      * it since we don't want the child to indirectly kill itself.
  743:      * This can happen with, e.g. BSD-derived versions of reboot
  744:      * that call kill(-1, SIGTERM) to kill all other processes.
  745:      */
  746:     if (info != NULL && info->si_code == SI_USER && info->si_pid == cmnd_pid)
  747: 	    return;
  748: 
  749:     /*
  750:      * The pipe is non-blocking, if we overflow the kernel's pipe
  751:      * buffer we drop the signal.  This is not a problem in practice.
  752:      */
  753:     ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  754: }
  755: #else
  756: void
  757: handler(int s)
  758: {
  759:     unsigned char signo = (unsigned char)s;
  760: 
  761:     /*
  762:      * The pipe is non-blocking, if we overflow the kernel's pipe
  763:      * buffer we drop the signal.  This is not a problem in practice.
  764:      */
  765:     ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  766: }
  767: #endif
  768: 
  769: #ifdef SA_SIGINFO
  770: /*
  771:  * Generic handler for signals passed from parent -> child.
  772:  * The other end of signal_pipe is checked in the main event loop.
  773:  * This version is for the non-pty case and does not forward
  774:  * signals that are generated by the kernel.
  775:  */
  776: static void
  777: handler_user_only(int s, siginfo_t *info, void *context)
  778: {
  779:     unsigned char signo = (unsigned char)s;
  780: 
  781:     /* Only forward user-generated signals. */
  782:     if (info != NULL && info->si_code == SI_USER) {
  783: 	/*
  784: 	 * The pipe is non-blocking, if we overflow the kernel's pipe
  785: 	 * buffer we drop the signal.  This is not a problem in practice.
  786: 	 */
  787: 	ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  788:     }
  789: }
  790: #endif /* SA_SIGINFO */
  791: 
  792: /*
  793:  * Open a pipe and make both ends non-blocking.
  794:  * Returns 0 on success and -1 on error.
  795:  */
  796: int
  797: pipe_nonblock(int fds[2])
  798: {
  799:     int flags, rval;
  800:     debug_decl(pipe_nonblock, SUDO_DEBUG_EXEC)
  801: 
  802:     rval = pipe(fds);
  803:     if (rval != -1) {
  804: 	flags = fcntl(fds[0], F_GETFL, 0);
  805: 	if (flags != -1 && !ISSET(flags, O_NONBLOCK))
  806: 	    rval = fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
  807: 	if (rval != -1) {
  808: 	    flags = fcntl(fds[1], F_GETFL, 0);
  809: 	    if (flags != -1 && !ISSET(flags, O_NONBLOCK))
  810: 		rval = fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);
  811: 	}
  812: 	if (rval == -1) {
  813: 	    close(fds[0]);
  814: 	    close(fds[1]);
  815: 	}
  816:     }
  817: 
  818:     debug_return_int(rval);
  819: }

FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>