File:  [ELWIX - Embedded LightWeight unIX -] / embedaddon / sudo / src / exec.c
Revision 1.1.1.4 (vendor branch): download - view: text, annotated - select for diffs - revision graph
Mon Jul 22 10:46:13 2013 UTC (10 years, 11 months ago) by misho
Branches: sudo, MAIN
CVS tags: v1_8_7p0, v1_8_7, HEAD
1.8.7

    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 {
  519: 		    if (WIFSTOPPED(status)) {
  520: 			/*
  521: 			 * Save the controlling terminal's process group
  522: 			 * so we can restore it after we resume, if needed.
  523: 			 * Most well-behaved shells change the pgrp back to
  524: 			 * its original value before suspending so we must
  525: 			 * not try to restore in that case, lest we race with
  526: 			 * the child upon resume, potentially stopping sudo
  527: 			 * with SIGTTOU while the command continues to run.
  528: 			 */
  529: 			sigaction_t sa, osa;
  530: 			pid_t saved_pgrp = (pid_t)-1;
  531: 			int signo = WSTOPSIG(status);
  532: 			int fd = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
  533: 			if (fd != -1) {
  534: 			    if ((saved_pgrp = tcgetpgrp(fd)) == ppgrp)
  535: 				saved_pgrp = -1;
  536: 			}
  537: 			if (signo == SIGTSTP) {
  538: 			    memset(&sa, 0, sizeof(sa));
  539: 			    sigemptyset(&sa.sa_mask);
  540: 			    sa.sa_flags = SA_RESTART;
  541: 			    sa.sa_handler = SIG_DFL;
  542: 			    sudo_sigaction(SIGTSTP, &sa, &osa);
  543: 			}
  544: 			if (kill(getpid(), signo) != 0)
  545: 			    warning("kill(%d, SIG%s)", (int)getpid(), signame);
  546: 			if (signo == SIGTSTP)
  547: 			    sudo_sigaction(SIGTSTP, &osa, NULL);
  548: 			if (fd != -1) {
  549: 			    /*
  550: 			     * Restore command's process group if different.
  551: 			     * Otherwise, we cannot resume some shells.
  552: 			     */
  553: 			    if (saved_pgrp != (pid_t)-1)
  554: 				(void)tcsetpgrp(fd, saved_pgrp);
  555: 			    close(fd);
  556: 			}
  557: 		    } else {
  558: 			/* Child has exited, we are done. */
  559: 			cstat->type = CMD_WSTATUS;
  560: 			cstat->val = status;
  561: 			debug_return_int(0);
  562: 		    }
  563: 		}
  564: 	    }
  565: 	} else {
  566: 	    if (log_io) {
  567: 		/* Schedule signo to be forwared to the child. */
  568: 		schedule_signal(signo);
  569: 	    } else {
  570: 		/* Nothing listening on sv[0], send directly. */
  571: 		if (signo == SIGALRM)
  572: 		    terminate_command(child, false);
  573: 		else if (kill(child, signo) != 0)
  574: 		    warning("kill(%d, SIG%s)", (int)child, signame);
  575: 	    }
  576: 	}
  577:     }
  578:     debug_return_int(1);
  579: }
  580: 
  581: /*
  582:  * Drain pending signals from signale_pipe written by sudo_handler().
  583:  * Handles the case where the signal was sent to us before
  584:  * we have executed the command.
  585:  * Returns 1 if we should terminate, else 0.
  586:  */
  587: static int
  588: dispatch_pending_signals(struct command_status *cstat)
  589: {
  590:     ssize_t nread;
  591:     struct sigaction sa;
  592:     unsigned char signo = 0;
  593:     int rval = 0;
  594:     debug_decl(dispatch_pending_signals, SUDO_DEBUG_EXEC)
  595: 
  596:     for (;;) {
  597: 	nread = read(signal_pipe[0], &signo, sizeof(signo));
  598: 	if (nread <= 0) {
  599: 	    /* It should not be possible to get EOF but just in case. */
  600: 	    if (nread == 0)
  601: 		errno = ECONNRESET;
  602: 	    /* Restart if interrupted by signal so the pipe doesn't fill. */
  603: 	    if (errno == EINTR)
  604: 		continue;
  605: 	    /* If pipe is empty, we are done. */
  606: 	    if (errno == EAGAIN)
  607: 		break;
  608: 	    sudo_debug_printf(SUDO_DEBUG_ERROR, "error reading signal pipe %s",
  609: 		strerror(errno));
  610: 	    cstat->type = CMD_ERRNO;
  611: 	    cstat->val = errno;
  612: 	    rval = 1;
  613: 	    break;
  614: 	}
  615: 	/* Take the first terminal signal. */
  616: 	if (signo == SIGINT || signo == SIGQUIT) {
  617: 	    cstat->type = CMD_WSTATUS;
  618: 	    cstat->val = signo + 128;
  619: 	    rval = 1;
  620: 	    break;
  621: 	}
  622:     }
  623:     /* Only stop if we haven't already been terminated. */
  624:     if (signo == SIGTSTP)
  625:     {
  626: 	memset(&sa, 0, sizeof(sa));
  627: 	sigemptyset(&sa.sa_mask);
  628: 	sa.sa_flags = SA_RESTART;
  629: 	sa.sa_handler = SIG_DFL;
  630: 	sudo_sigaction(SIGTSTP, &sa, NULL);
  631: 	if (kill(getpid(), SIGTSTP) != 0)
  632: 	    warning("kill(%d, SIGTSTP)", (int)getpid());
  633: 	/* No need to reinstall SIGTSTP handler. */
  634:     }
  635:     debug_return_int(rval);
  636: }
  637: 
  638: /*
  639:  * Forward signals in sigfwd_list to child listening on fd.
  640:  */
  641: static void
  642: forward_signals(int sock)
  643: {
  644:     char signame[SIG2STR_MAX];
  645:     struct sigforward *sigfwd;
  646:     struct command_status cstat;
  647:     ssize_t nsent;
  648:     debug_decl(forward_signals, SUDO_DEBUG_EXEC)
  649: 
  650:     while (!tq_empty(&sigfwd_list)) {
  651: 	sigfwd = tq_first(&sigfwd_list);
  652: 	if (sigfwd->signo == SIGCONT_FG)
  653: 	    strlcpy(signame, "CONT_FG", sizeof(signame));
  654: 	else if (sigfwd->signo == SIGCONT_BG)
  655: 	    strlcpy(signame, "CONT_BG", sizeof(signame));
  656: 	else if (sig2str(sigfwd->signo, signame) == -1)
  657: 	    snprintf(signame, sizeof(signame), "%d", sigfwd->signo);
  658: 	sudo_debug_printf(SUDO_DEBUG_INFO,
  659: 	    "sending SIG%s to child over backchannel", signame);
  660: 	cstat.type = CMD_SIGNO;
  661: 	cstat.val = sigfwd->signo;
  662: 	do {
  663: 	    nsent = send(sock, &cstat, sizeof(cstat), 0);
  664: 	} while (nsent == -1 && errno == EINTR);
  665: 	tq_remove(&sigfwd_list, sigfwd);
  666: 	efree(sigfwd);
  667: 	if (nsent != sizeof(cstat)) {
  668: 	    if (errno == EPIPE) {
  669: 		sudo_debug_printf(SUDO_DEBUG_ERROR,
  670: 		    "broken pipe writing to child over backchannel");
  671: 		/* Other end of socket gone, empty out sigfwd_list. */
  672: 		while (!tq_empty(&sigfwd_list)) {
  673: 		    sigfwd = tq_first(&sigfwd_list);
  674: 		    tq_remove(&sigfwd_list, sigfwd);
  675: 		    efree(sigfwd);
  676: 		}
  677: 		/* XXX - child (monitor) is dead, we should exit too? */
  678: 	    }
  679: 	    break;
  680: 	}
  681:     }
  682:     debug_return;
  683: }
  684: 
  685: /*
  686:  * Schedule a signal to be forwared.
  687:  */
  688: static void
  689: schedule_signal(int signo)
  690: {
  691:     struct sigforward *sigfwd;
  692:     char signame[SIG2STR_MAX];
  693:     debug_decl(schedule_signal, SUDO_DEBUG_EXEC)
  694: 
  695:     if (signo == SIGCONT_FG)
  696: 	strlcpy(signame, "CONT_FG", sizeof(signame));
  697:     else if (signo == SIGCONT_BG)
  698: 	strlcpy(signame, "CONT_BG", sizeof(signame));
  699:     else if (sig2str(signo, signame) == -1)
  700: 	snprintf(signame, sizeof(signame), "%d", signo);
  701:     sudo_debug_printf(SUDO_DEBUG_DIAG, "scheduled SIG%s for child", signame);
  702: 
  703:     sigfwd = ecalloc(1, sizeof(*sigfwd));
  704:     sigfwd->prev = sigfwd;
  705:     /* sigfwd->next = NULL; */
  706:     sigfwd->signo = signo;
  707:     tq_append(&sigfwd_list, sigfwd);
  708: 
  709:     debug_return;
  710: }
  711: 
  712: /*
  713:  * Generic handler for signals passed from parent -> child.
  714:  * The other end of signal_pipe is checked in the main event loop.
  715:  */
  716: #ifdef SA_SIGINFO
  717: void
  718: handler(int s, siginfo_t *info, void *context)
  719: {
  720:     unsigned char signo = (unsigned char)s;
  721: 
  722:     /*
  723:      * If the signal came from the command we ran, just ignore
  724:      * it since we don't want the child to indirectly kill itself.
  725:      * This can happen with, e.g. BSD-derived versions of reboot
  726:      * that call kill(-1, SIGTERM) to kill all other processes.
  727:      */
  728:     if (info != NULL && info->si_code == SI_USER && info->si_pid == cmnd_pid)
  729: 	    return;
  730: 
  731:     /*
  732:      * The pipe is non-blocking, if we overflow the kernel's pipe
  733:      * buffer we drop the signal.  This is not a problem in practice.
  734:      */
  735:     ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  736: }
  737: #else
  738: void
  739: handler(int s)
  740: {
  741:     unsigned char signo = (unsigned char)s;
  742: 
  743:     /*
  744:      * The pipe is non-blocking, if we overflow the kernel's pipe
  745:      * buffer we drop the signal.  This is not a problem in practice.
  746:      */
  747:     ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  748: }
  749: #endif
  750: 
  751: #ifdef SA_SIGINFO
  752: /*
  753:  * Generic handler for signals passed from parent -> child.
  754:  * The other end of signal_pipe is checked in the main event loop.
  755:  * This version is for the non-pty case and does not forward
  756:  * signals that are generated by the kernel.
  757:  */
  758: static void
  759: handler_user_only(int s, siginfo_t *info, void *context)
  760: {
  761:     unsigned char signo = (unsigned char)s;
  762: 
  763:     /* Only forward user-generated signals. */
  764:     if (info != NULL && info->si_code == SI_USER) {
  765: 	/*
  766: 	 * The pipe is non-blocking, if we overflow the kernel's pipe
  767: 	 * buffer we drop the signal.  This is not a problem in practice.
  768: 	 */
  769: 	ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
  770:     }
  771: }
  772: #endif /* SA_SIGINFO */
  773: 
  774: /*
  775:  * Open a pipe and make both ends non-blocking.
  776:  * Returns 0 on success and -1 on error.
  777:  */
  778: int
  779: pipe_nonblock(int fds[2])
  780: {
  781:     int flags, rval;
  782:     debug_decl(pipe_nonblock, SUDO_DEBUG_EXEC)
  783: 
  784:     rval = pipe(fds);
  785:     if (rval != -1) {
  786: 	flags = fcntl(fds[0], F_GETFL, 0);
  787: 	if (flags != -1 && !ISSET(flags, O_NONBLOCK))
  788: 	    rval = fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);
  789: 	if (rval != -1) {
  790: 	    flags = fcntl(fds[1], F_GETFL, 0);
  791: 	    if (flags != -1 && !ISSET(flags, O_NONBLOCK))
  792: 		rval = fcntl(fds[1], F_SETFL, flags | O_NONBLOCK);
  793: 	}
  794: 	if (rval == -1) {
  795: 	    close(fds[0]);
  796: 	    close(fds[1]);
  797: 	}
  798:     }
  799: 
  800:     debug_return_int(rval);
  801: }

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