1/*
2 * Copyright (c) 2009-2012 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#include <sys/param.h>
21#ifdef HAVE_SYS_SYSMACROS_H
22# include <sys/sysmacros.h>
23#endif
24#include <sys/socket.h>
25#include <sys/time.h>
26#include <sys/wait.h>
27#ifdef HAVE_TERMIOS_H
28# include <termios.h>
29#else
30# include <termio.h>
31#endif /* HAVE_TERMIOS_H */
32#include <sys/ioctl.h>
33#ifdef HAVE_SYS_SELECT_H
34# include <sys/select.h>
35#endif /* HAVE_SYS_SELECT_H */
36#include <stdio.h>
37#ifdef STDC_HEADERS
38# include <stdlib.h>
39# include <stddef.h>
40#else
41# ifdef HAVE_STDLIB_H
42#  include <stdlib.h>
43# endif
44#endif /* STDC_HEADERS */
45#ifdef HAVE_STRING_H
46# if defined(HAVE_MEMORY_H) && !defined(STDC_HEADERS)
47#  include <memory.h>
48# endif
49# include <string.h>
50#endif /* HAVE_STRING_H */
51#ifdef HAVE_STRINGS_H
52# include <strings.h>
53#endif /* HAVE_STRINGS_H */
54#ifdef HAVE_UNISTD_H
55# include <unistd.h>
56#endif /* HAVE_UNISTD_H */
57#if TIME_WITH_SYS_TIME
58# include <time.h>
59#endif
60#include <errno.h>
61#include <fcntl.h>
62#include <signal.h>
63
64#include "sudo.h"
65#include "sudo_exec.h"
66
67#define SFD_STDIN	0
68#define SFD_STDOUT	1
69#define SFD_STDERR	2
70#define SFD_MASTER	3
71#define SFD_SLAVE	4
72#define SFD_USERTTY	5
73
74#define TERM_COOKED	0
75#define TERM_RAW	1
76
77/* Compatibility with older tty systems. */
78#if !defined(TIOCGWINSZ) && defined(TIOCGSIZE)
79# define TIOCGWINSZ	TIOCGSIZE
80# define TIOCSWINSZ	TIOCSSIZE
81# define winsize	ttysize
82#endif
83
84struct io_buffer {
85    struct io_buffer *next;
86    int len; /* buffer length (how much produced) */
87    int off; /* write position (how much already consumed) */
88    int rfd;  /* reader (producer) */
89    int wfd; /* writer (consumer) */
90    int (*action) __P((const char *buf, unsigned int len));
91    char buf[16 * 1024];
92};
93
94static char slavename[PATH_MAX];
95static int foreground;
96static int io_fds[6] = { -1, -1, -1, -1, -1, -1};
97static int pipeline = FALSE;
98static int tty_initialized;
99static int ttymode = TERM_COOKED;
100static pid_t ppgrp, cmnd_pgrp, mon_pgrp;;
101static struct io_buffer *iobufs;
102
103static void flush_output __P((void));
104static int exec_monitor __P((const char *path, char *argv[],
105    char *envp[], int, int));
106static void exec_pty __P((const char *path, char *argv[],
107    char *envp[], int, int *));
108static RETSIGTYPE sigwinch __P((int s));
109static void sync_ttysize __P((int src, int dst));
110static void deliver_signal __P((pid_t pid, int signo));
111static int safe_close __P((int fd));
112
113/*
114 * Allocate a pty if /dev/tty is a tty.
115 * Fills in io_fds[SFD_USERTTY], io_fds[SFD_MASTER], io_fds[SFD_SLAVE]
116 * and slavename globals.
117 */
118void
119pty_setup(uid)
120    uid_t uid;
121{
122    io_fds[SFD_USERTTY] = open(_PATH_TTY, O_RDWR|O_NOCTTY, 0);
123    if (io_fds[SFD_USERTTY] != -1) {
124	if (!get_pty(&io_fds[SFD_MASTER], &io_fds[SFD_SLAVE],
125	    slavename, sizeof(slavename), uid))
126	    error(1, "Can't get pty");
127    }
128}
129
130/*
131 * Check whether we are running in the foregroup.
132 * Updates the foreground global and does lazy init of the
133 * the pty slave as needed.
134 */
135static void
136check_foreground()
137{
138    if (io_fds[SFD_USERTTY] != -1) {
139	foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
140	if (foreground && !tty_initialized) {
141	    if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
142		tty_initialized = 1;
143		sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
144	    }
145	}
146    }
147}
148
149/*
150 * Generic handler for signals recieved by the monitor process.
151 * The other end of signal_pipe is checked in the monitor event loop.
152 */
153#ifdef SA_SIGINFO
154void
155mon_handler(s, info, context)
156    int s;
157    siginfo_t *info;
158    void *context;
159{
160    unsigned char signo = (unsigned char)s;
161
162    /*
163     * If the signal came from the command we ran, just ignore
164     * it since we don't want the command to indirectly kill itself.
165     * This can happen with, e.g. BSD-derived versions of reboot
166     * that call kill(-1, SIGTERM) to kill all other processes.
167     */
168    if (info != NULL && info->si_code == SI_USER && info->si_pid == cmnd_pid)
169	    return;
170
171    /*
172     * The pipe is non-blocking, if we overflow the kernel's pipe
173     * buffer we drop the signal.  This is not a problem in practice.
174     */
175    ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
176}
177#else
178void
179mon_handler(s)
180    int s;
181{
182    unsigned char signo = (unsigned char)s;
183
184    /*
185     * The pipe is non-blocking, if we overflow the kernel's pipe
186     * buffer we drop the signal.  This is not a problem in practice.
187     */
188    ignore_result(write(signal_pipe[1], &signo, sizeof(signo)));
189}
190#endif
191
192/*
193 * Suspend sudo if the underlying command is suspended.
194 * Returns SIGCONT_FG if the command should be resume in the
195 * foreground or SIGCONT_BG if it is a background process.
196 */
197int
198suspend_parent(signo)
199    int signo;
200{
201    sigaction_t sa, osa;
202    int n, oldmode = ttymode, rval = 0;
203
204    switch (signo) {
205    case SIGTTOU:
206    case SIGTTIN:
207	/*
208	 * If we are the foreground process, just resume the command.
209	 * Otherwise, re-send the signal with the handler disabled.
210	 */
211	if (!foreground)
212	    check_foreground();
213	if (foreground) {
214	    if (ttymode != TERM_RAW) {
215		do {
216		    n = term_raw(io_fds[SFD_USERTTY], 0);
217		} while (!n && errno == EINTR);
218		ttymode = TERM_RAW;
219	    }
220	    rval = SIGCONT_FG; /* resume command in foreground */
221	    break;
222	}
223	ttymode = TERM_RAW;
224	/* FALLTHROUGH */
225    case SIGSTOP:
226    case SIGTSTP:
227	/* Flush any remaining output before suspending. */
228	flush_output();
229
230	/* Restore original tty mode before suspending. */
231	if (oldmode != TERM_COOKED) {
232	    do {
233		n = term_restore(io_fds[SFD_USERTTY], 0);
234	    } while (!n && errno == EINTR);
235	}
236
237	/* Suspend self and continue command when we resume. */
238	if (signo != SIGSTOP) {
239	    zero_bytes(&sa, sizeof(sa));
240	    sigemptyset(&sa.sa_mask);
241	    sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
242	    sa.sa_handler = SIG_DFL;
243	    sigaction(signo, &sa, &osa);
244	}
245	if (killpg(ppgrp, signo) != 0)
246	    warning("killpg(%d, %d)", ppgrp, signo);
247
248	/* Check foreground/background status on resume. */
249	check_foreground();
250
251	/*
252	 * Only modify term if we are foreground process and either
253	 * the old tty mode was not cooked or command got SIGTT{IN,OU}
254	 */
255	if (ttymode != TERM_COOKED) {
256	    if (foreground) {
257		/* Set raw mode. */
258		do {
259		    n = term_raw(io_fds[SFD_USERTTY], 0);
260		} while (!n && errno == EINTR);
261	    } else {
262		/* Background process, no access to tty. */
263		ttymode = TERM_COOKED;
264	    }
265	}
266
267	if (signo != SIGSTOP)
268	    sigaction(signo, &osa, NULL);
269	rval = ttymode == TERM_RAW ? SIGCONT_FG : SIGCONT_BG;
270	break;
271    }
272
273    return rval;
274}
275
276/*
277 * Kill command with increasing urgency.
278 */
279static void
280terminate_command(pid, use_pgrp)
281    pid_t pid;
282    int use_pgrp;
283{
284    /*
285     * Note that SIGCHLD will interrupt the sleep()
286     */
287    if (use_pgrp) {
288	killpg(pid, SIGHUP);
289	killpg(pid, SIGTERM);
290	sleep(2);
291	killpg(pid, SIGKILL);
292    } else {
293	kill(pid, SIGHUP);
294	kill(pid, SIGTERM);
295	sleep(2);
296	kill(pid, SIGKILL);
297    }
298}
299
300/*
301 * Allocate a new io_buffer struct and insert it at the head of the list.
302 * Returns the new head element.
303 */
304static struct io_buffer *
305io_buf_new(rfd, wfd, action, head)
306    int rfd;
307    int wfd;
308    int (*action) __P((const char *, unsigned int));
309    struct io_buffer *head;
310{
311    struct io_buffer *iob;
312
313    iob = ecalloc(1, sizeof(*iob));
314    iob->rfd = rfd;
315    iob->wfd = wfd;
316    iob->action = action;
317    iob->next = head;
318    return iob;
319}
320
321/*
322 * Read/write iobufs depending on fdsr and fdsw.
323 * Fills in cstat on error.
324 * Returns the number of errors.
325 */
326int
327perform_io(fdsr, fdsw, cstat)
328    fd_set *fdsr;
329    fd_set *fdsw;
330    struct command_status *cstat;
331{
332    struct io_buffer *iob;
333    int n, errors = 0;
334
335    for (iob = iobufs; iob; iob = iob->next) {
336	if (iob->rfd != -1 && FD_ISSET(iob->rfd, fdsr)) {
337	    do {
338		n = read(iob->rfd, iob->buf + iob->len,
339		    sizeof(iob->buf) - iob->len);
340	    } while (n == -1 && errno == EINTR);
341	    switch (n) {
342		case -1:
343		    if (errno != EAGAIN) {
344			/* treat read error as fatal and close the fd */
345			safe_close(iob->rfd);
346			iob->rfd = -1;
347		    }
348		    break;
349		case 0:
350		    /* got EOF or pty has gone away */
351		    safe_close(iob->rfd);
352		    iob->rfd = -1;
353		    break;
354		default:
355		    if (!iob->action(iob->buf + iob->len, n))
356			terminate_command(cmnd_pid, TRUE);
357		    iob->len += n;
358		    break;
359	    }
360	}
361	if (iob->wfd != -1 && FD_ISSET(iob->wfd, fdsw)) {
362	    do {
363		n = write(iob->wfd, iob->buf + iob->off,
364		    iob->len - iob->off);
365	    } while (n == -1 && errno == EINTR);
366	    if (n == -1) {
367		if (errno == EPIPE || errno == ENXIO || errno == EIO || errno == EBADF) {
368		    /* other end of pipe closed or pty revoked */
369		    if (iob->rfd != -1) {
370			safe_close(iob->rfd);
371			iob->rfd = -1;
372		    }
373		    safe_close(iob->wfd);
374		    iob->wfd = -1;
375		    continue;
376		}
377		if (errno != EAGAIN)
378		    errors++;
379	    } else {
380		iob->off += n;
381	    }
382	}
383    }
384    if (errors && cstat != NULL) {
385	cstat->type = CMD_ERRNO;
386	cstat->val = errno;
387    }
388    return errors;
389}
390
391/*
392 * Fork a monitor process which runs the actual command as its own child
393 * process with std{in,out,err} hooked up to the pty or pipes as appropriate.
394 * Returns the child pid.
395 */
396int
397fork_pty(path, argv, envp, sv, rbac_enabled, bgmode, maxfd, omask)
398    const char *path;
399    char *argv[];
400    char *envp[];
401    int sv[2];
402    int rbac_enabled;
403    int bgmode;
404    int *maxfd;
405    sigset_t *omask;
406{
407    struct command_status cstat;
408    struct io_buffer *iob;
409    int io_pipe[3][2], n;
410    sigaction_t sa;
411    sigset_t mask;
412    pid_t child;
413
414    ppgrp = getpgrp(); /* parent's pgrp, so child can signal us */
415
416    zero_bytes(&sa, sizeof(sa));
417    sigemptyset(&sa.sa_mask);
418
419    if (io_fds[SFD_USERTTY] != -1) {
420	sa.sa_flags = SA_RESTART;
421	sa.sa_handler = sigwinch;
422	sigaction(SIGWINCH, &sa, NULL);
423    }
424
425    /*
426     * Setup stdin/stdout/stderr for child, to be duped after forking.
427     * In background mode there is no stdin.
428     */
429    if (!bgmode)
430	io_fds[SFD_STDIN] = io_fds[SFD_SLAVE];
431    io_fds[SFD_STDOUT] = io_fds[SFD_SLAVE];
432    io_fds[SFD_STDERR] = io_fds[SFD_SLAVE];
433
434    if (io_fds[SFD_USERTTY] != -1) {
435	/* Read from /dev/tty, write to pty master */
436	if (!bgmode) {
437	    iobufs = io_buf_new(io_fds[SFD_USERTTY], io_fds[SFD_MASTER],
438		log_ttyin, iobufs);
439	}
440
441	/* Read from pty master, write to /dev/tty */
442	iobufs = io_buf_new(io_fds[SFD_MASTER], io_fds[SFD_USERTTY],
443	    log_ttyout, iobufs);
444
445	/* Are we the foreground process? */
446	foreground = tcgetpgrp(io_fds[SFD_USERTTY]) == ppgrp;
447    }
448
449    /*
450     * If either stdin, stdout or stderr is not a tty we use a pipe
451     * to interpose ourselves instead of duping the pty fd.
452     */
453    memset(io_pipe, 0, sizeof(io_pipe));
454    if (io_fds[SFD_STDIN] == -1 || !isatty(STDIN_FILENO)) {
455	pipeline = TRUE;
456	if (pipe(io_pipe[STDIN_FILENO]) != 0)
457	    error(1, "unable to create pipe");
458	iobufs = io_buf_new(STDIN_FILENO, io_pipe[STDIN_FILENO][1],
459	    log_stdin, iobufs);
460	io_fds[SFD_STDIN] = io_pipe[STDIN_FILENO][0];
461    }
462    if (io_fds[SFD_STDOUT] == -1 || !isatty(STDOUT_FILENO)) {
463	pipeline = TRUE;
464	if (pipe(io_pipe[STDOUT_FILENO]) != 0)
465	    error(1, "unable to create pipe");
466	iobufs = io_buf_new(io_pipe[STDOUT_FILENO][0], STDOUT_FILENO,
467	    log_stdout, iobufs);
468	io_fds[SFD_STDOUT] = io_pipe[STDOUT_FILENO][1];
469    }
470    if (io_fds[SFD_STDERR] == -1 || !isatty(STDERR_FILENO)) {
471	if (pipe(io_pipe[STDERR_FILENO]) != 0)
472	    error(1, "unable to create pipe");
473	iobufs = io_buf_new(io_pipe[STDERR_FILENO][0], STDERR_FILENO,
474	    log_stderr, iobufs);
475	io_fds[SFD_STDERR] = io_pipe[STDERR_FILENO][1];
476    }
477
478    /* Job control signals to relay from parent to child. */
479    sa.sa_flags = SA_INTERRUPT; /* do not restart syscalls */
480#ifdef SA_SIGINFO
481    sa.sa_flags |= SA_SIGINFO;
482    sa.sa_sigaction = handler;
483#else
484    sa.sa_handler = handler;
485#endif
486    sigaction(SIGTSTP, &sa, NULL);
487
488    /* We don't want to receive SIGTTIN/SIGTTOU, getting EIO is preferable. */
489    sa.sa_handler = SIG_IGN;
490    sigaction(SIGTTIN, &sa, NULL);
491    sigaction(SIGTTOU, &sa, NULL);
492
493    if (foreground) {
494	/* Copy terminal attrs from user tty -> pty slave. */
495	if (term_copy(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE])) {
496	    tty_initialized = 1;
497	    sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
498	}
499
500	/* Start out in raw mode if we are not part of a pipeline. */
501	if (!pipeline) {
502	    ttymode = TERM_RAW;
503	    do {
504		n = term_raw(io_fds[SFD_USERTTY], 0);
505	    } while (!n && errno == EINTR);
506	    if (!n)
507		error(1, "Can't set terminal to raw mode");
508	}
509    }
510
511    /*
512     * Block some signals until cmnd_pid is set in the parent to avoid a
513     * race between exec of the command and receipt of a fatal signal from it.
514     */
515    sigemptyset(&mask);
516    sigaddset(&mask, SIGTERM);
517    sigaddset(&mask, SIGHUP);
518    sigaddset(&mask, SIGINT);
519    sigaddset(&mask, SIGQUIT);
520    sigprocmask(SIG_BLOCK, &mask, omask);
521
522    child = fork();
523    switch (child) {
524    case -1:
525	error(1, "fork");
526	break;
527    case 0:
528	/* child */
529	close(sv[0]);
530	close(signal_pipe[0]);
531	close(signal_pipe[1]);
532	fcntl(sv[1], F_SETFD, FD_CLOEXEC);
533	sigprocmask(SIG_SETMASK, omask, NULL);
534	if (exec_setup(rbac_enabled, slavename, io_fds[SFD_SLAVE]) == TRUE) {
535	    /* Close the other end of the stdin/stdout/stderr pipes and exec. */
536	    if (io_pipe[STDIN_FILENO][1])
537		close(io_pipe[STDIN_FILENO][1]);
538	    if (io_pipe[STDOUT_FILENO][0])
539		close(io_pipe[STDOUT_FILENO][0]);
540	    if (io_pipe[STDERR_FILENO][0])
541		close(io_pipe[STDERR_FILENO][0]);
542	    exec_monitor(path, argv, envp, sv[1], rbac_enabled);
543	}
544	cstat.type = CMD_ERRNO;
545	cstat.val = errno;
546	ignore_result(send(sv[1], &cstat, sizeof(cstat), 0));
547	_exit(1);
548    }
549
550    /* Close the other end of the stdin/stdout/stderr pipes. */
551    if (io_pipe[STDIN_FILENO][0])
552	close(io_pipe[STDIN_FILENO][0]);
553    if (io_pipe[STDOUT_FILENO][1])
554	close(io_pipe[STDOUT_FILENO][1]);
555    if (io_pipe[STDERR_FILENO][1])
556	close(io_pipe[STDERR_FILENO][1]);
557
558    for (iob = iobufs; iob; iob = iob->next) {
559	/* Adjust maxfd. */
560	if (iob->rfd > *maxfd)
561	    *maxfd = iob->rfd;
562	if (iob->wfd > *maxfd)
563	    *maxfd = iob->wfd;
564
565	/* Set non-blocking mode. */
566	n = fcntl(iob->rfd, F_GETFL, 0);
567	if (n != -1 && !ISSET(n, O_NONBLOCK))
568	    (void) fcntl(iob->rfd, F_SETFL, n | O_NONBLOCK);
569	n = fcntl(iob->wfd, F_GETFL, 0);
570	if (n != -1 && !ISSET(n, O_NONBLOCK))
571	    (void) fcntl(iob->wfd, F_SETFL, n | O_NONBLOCK);
572    }
573
574    return child;
575}
576
577/*
578 * Flush any remaining output and restore /dev/tty to the way we found it.
579 * If the command died due to a signal, writes the reason to stdout.
580 */
581void
582pty_close(cstat)
583    struct command_status *cstat;
584{
585    int n;
586
587    /* Flush any remaining output (the plugin already got it) */
588    if (io_fds[SFD_USERTTY] != -1) {
589	n = fcntl(io_fds[SFD_USERTTY], F_GETFL, 0);
590	if (n != -1 && ISSET(n, O_NONBLOCK)) {
591	    CLR(n, O_NONBLOCK);
592	    (void) fcntl(io_fds[SFD_USERTTY], F_SETFL, n);
593	}
594    }
595    flush_output();
596
597    if (io_fds[SFD_USERTTY] != -1) {
598	check_foreground();
599	if (foreground) {
600	    do {
601		n = term_restore(io_fds[SFD_USERTTY], 0);
602	    } while (!n && errno == EINTR);
603	}
604    }
605
606    /* If child was signalled, write the reason to stdout like the shell. */
607    if (cstat->type == CMD_WSTATUS && WIFSIGNALED(cstat->val)) {
608	int signo = WTERMSIG(cstat->val);
609	if (signo && signo != SIGINT && signo != SIGPIPE) {
610	    const char *reason = strsignal(signo);
611	    n = io_fds[SFD_USERTTY] != -1 ?
612		io_fds[SFD_USERTTY] : STDOUT_FILENO;
613	    if (write(n, reason, strlen(reason)) != -1) {
614		if (WCOREDUMP(cstat->val)) {
615		    ignore_result(write(n, " (core dumped)", 14));
616		}
617		ignore_result(write(n, "\n", 1));
618	    }
619	}
620    }
621}
622
623
624/*
625 * Fill in fdsr and fdsw based on the io buffers list.
626 * Called prior to select().
627 */
628void
629fd_set_iobs(fdsr, fdsw)
630    fd_set *fdsr;
631    fd_set *fdsw;
632{
633    struct io_buffer *iob;
634
635    for (iob = iobufs; iob; iob = iob->next) {
636	if (iob->rfd == -1 && iob->wfd == -1)
637	    continue;
638	if (iob->off == iob->len) {
639	    iob->off = iob->len = 0;
640	    /* Forward the EOF from reader to writer. */
641	    if (iob->rfd == -1) {
642		safe_close(iob->wfd);
643		iob->wfd = -1;
644	    }
645	}
646	/* Don't read/write /dev/tty if we are not in the foreground. */
647	if (iob->rfd != -1 &&
648	    (ttymode == TERM_RAW || iob->rfd != io_fds[SFD_USERTTY])) {
649	    if (iob->len != sizeof(iob->buf))
650		FD_SET(iob->rfd, fdsr);
651	}
652	if (iob->wfd != -1 &&
653	    (foreground || iob->wfd != io_fds[SFD_USERTTY])) {
654	    if (iob->len > iob->off)
655		FD_SET(iob->wfd, fdsw);
656	}
657    }
658}
659
660/*
661 * Deliver a relayed signal to the command.
662 */
663static void
664deliver_signal(pid, signo)
665    pid_t pid;
666    int signo;
667{
668    int status;
669
670    /* Handle signal from parent. */
671    switch (signo) {
672    case SIGCONT_FG:
673	/* Continue in foreground, grant it controlling tty. */
674	do {
675	    status = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
676	} while (status == -1 && errno == EINTR);
677	killpg(pid, SIGCONT);
678	break;
679    case SIGCONT_BG:
680	/* Continue in background, I take controlling tty. */
681	do {
682	    status = tcsetpgrp(io_fds[SFD_SLAVE], mon_pgrp);
683	} while (status == -1 && errno == EINTR);
684	killpg(pid, SIGCONT);
685	break;
686    case SIGKILL:
687	_exit(1); /* XXX */
688	/* NOTREACHED */
689    default:
690	/* Relay signal to command. */
691	killpg(pid, signo);
692	break;
693    }
694}
695
696/*
697 * Send status to parent over socketpair.
698 * Return value is the same as send(2).
699 */
700static int
701send_status(fd, cstat)
702    int fd;
703    struct command_status *cstat;
704{
705    int n = -1;
706
707    if (cstat->type != CMD_INVALID) {
708	do {
709	    n = send(fd, cstat, sizeof(*cstat), 0);
710	} while (n == -1 && errno == EINTR);
711	cstat->type = CMD_INVALID; /* prevent re-sending */
712    }
713    return n;
714}
715
716/*
717 * Wait for command status after receiving SIGCHLD.
718 * If the command was stopped, the status is send back to the parent.
719 * Otherwise, cstat is filled in but not sent.
720 * Returns TRUE if command is still alive, else FALSE.
721 */
722static int
723handle_sigchld(backchannel, cstat)
724    int backchannel;
725    struct command_status *cstat;
726{
727    int status, alive = TRUE;
728    pid_t pid;
729
730    /* read command status */
731    do {
732#ifdef sudo_waitpid
733	pid = sudo_waitpid(cmnd_pid, &status, WUNTRACED|WNOHANG);
734#else
735	pid = wait(&status);
736#endif
737    } while (pid == -1 && errno == EINTR);
738    if (pid == cmnd_pid) {
739	if (cstat->type != CMD_ERRNO) {
740	    cstat->type = CMD_WSTATUS;
741	    cstat->val = status;
742	    if (WIFSTOPPED(status)) {
743		/* Save the foreground pgid so we can restore it later. */
744		do {
745		    pid = tcgetpgrp(io_fds[SFD_SLAVE]);
746		} while (pid == -1 && errno == EINTR);
747		if (pid != mon_pgrp)
748		    cmnd_pgrp = pid;
749		if (send_status(backchannel, cstat) == -1)
750		    return alive; /* XXX */
751	    }
752	}
753	if (!WIFSTOPPED(status))
754	    alive = FALSE;
755    }
756    return alive;
757}
758
759/*
760 * Monitor process that creates a new session with the controlling tty,
761 * resets signal handlers and forks a child to call exec_pty().
762 * Waits for status changes from the command and relays them to the
763 * parent and relays signals from the parent to the command.
764 * Returns an error if fork(2) fails, else calls _exit(2).
765 */
766static int
767exec_monitor(path, argv, envp, backchannel, rbac)
768    const char *path;
769    char *argv[];
770    char *envp[];
771    int backchannel;
772    int rbac;
773{
774    struct command_status cstat;
775    struct timeval tv;
776    fd_set *fdsr;
777    sigaction_t sa;
778    int errpipe[2], maxfd, n;
779    int alive = TRUE;
780    unsigned char signo;
781
782    /* Close unused fds. */
783    if (io_fds[SFD_MASTER] != -1)
784	close(io_fds[SFD_MASTER]);
785    if (io_fds[SFD_USERTTY] != -1)
786	close(io_fds[SFD_USERTTY]);
787
788    /*
789     * We use a pipe to atomically handle signal notification within
790     * the select() loop.
791     */
792    if (pipe_nonblock(signal_pipe) != 0)
793	error(1, "cannot create pipe");
794
795    /* Reset SIGWINCH. */
796    zero_bytes(&sa, sizeof(sa));
797    sigemptyset(&sa.sa_mask);
798    sa.sa_flags = SA_RESTART;
799    sa.sa_handler = SIG_DFL;
800    sigaction(SIGWINCH, &sa, NULL);
801
802    /* Ignore any SIGTTIN or SIGTTOU we get. */
803    sa.sa_handler = SIG_IGN;
804    sigaction(SIGTTIN, &sa, NULL);
805    sigaction(SIGTTOU, &sa, NULL);
806
807    /* Note: HP-UX select() will not be interrupted if SA_RESTART set */
808    sa.sa_flags = SA_INTERRUPT;
809#ifdef SA_SIGINFO
810    sa.sa_flags |= SA_SIGINFO;
811    sa.sa_sigaction = mon_handler;
812#else
813    sa.sa_handler = mon_handler;
814#endif
815    sigaction(SIGCHLD, &sa, NULL);
816
817    /* Catch common signals so we can cleanup properly. */
818    sa.sa_flags = SA_RESTART;
819#ifdef SA_SIGINFO
820    sa.sa_flags |= SA_SIGINFO;
821    sa.sa_sigaction = mon_handler;
822#else
823    sa.sa_handler = mon_handler;
824#endif
825    sigaction(SIGHUP, &sa, NULL);
826    sigaction(SIGINT, &sa, NULL);
827    sigaction(SIGQUIT, &sa, NULL);
828    sigaction(SIGTERM, &sa, NULL);
829    sigaction(SIGTSTP, &sa, NULL);
830    sigaction(SIGUSR1, &sa, NULL);
831    sigaction(SIGUSR2, &sa, NULL);
832
833    /*
834     * Start a new session with the parent as the session leader
835     * and the slave pty as the controlling terminal.
836     * This allows us to be notified when the command has been suspended.
837     */
838    if (setsid() == -1) {
839	warning("setsid");
840	goto bad;
841    }
842    if (io_fds[SFD_SLAVE] != -1) {
843#ifdef TIOCSCTTY
844	if (ioctl(io_fds[SFD_SLAVE], TIOCSCTTY, NULL) != 0)
845	    error(1, "unable to set controlling tty");
846#else
847	/* Set controlling tty by reopening slave. */
848	if ((n = open(slavename, O_RDWR)) >= 0)
849	    close(n);
850#endif
851    }
852
853    mon_pgrp = getpgrp();	/* save a copy of our process group */
854
855    /*
856     * If stdin/stdout is not a tty, start command in the background
857     * since it might be part of a pipeline that reads from /dev/tty.
858     * In this case, we rely on the command receiving SIGTTOU or SIGTTIN
859     * when it needs access to the controlling tty.
860     */
861    if (pipeline)
862	foreground = 0;
863
864    /* Start command and wait for it to stop or exit */
865    if (pipe(errpipe) == -1)
866	error(1, "unable to create pipe");
867    cmnd_pid = fork();
868    if (cmnd_pid == -1) {
869	warning("Can't fork");
870	goto bad;
871    }
872    if (cmnd_pid == 0) {
873	/* We pass errno back to our parent via pipe on exec failure. */
874	close(backchannel);
875	close(signal_pipe[0]);
876	close(signal_pipe[1]);
877	close(errpipe[0]);
878	fcntl(errpipe[1], F_SETFD, FD_CLOEXEC);
879	restore_signals();
880
881	/* setup tty and exec command */
882	exec_pty(path, argv, envp, rbac, &errpipe[1]);
883	cstat.type = CMD_ERRNO;
884	cstat.val = errno;
885	ignore_result(write(errpipe[1], &cstat, sizeof(cstat)));
886	_exit(1);
887    }
888    close(errpipe[1]);
889
890    /* Send the command's pid to main sudo process. */
891    cstat.type = CMD_PID;
892    cstat.val = cmnd_pid;
893    ignore_result(send(backchannel, &cstat, sizeof(cstat), 0));
894
895    /* If any of stdin/stdout/stderr are pipes, close them in parent. */
896    if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
897	close(io_fds[SFD_STDIN]);
898    if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
899	close(io_fds[SFD_STDOUT]);
900    if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
901	close(io_fds[SFD_STDERR]);
902
903    /*
904     * Put command in its own process group.  If we are starting the command
905     * in the foreground, assign its pgrp to the tty.
906     */
907    cmnd_pgrp = cmnd_pid;
908    setpgid(cmnd_pid, cmnd_pgrp);
909    if (foreground) {
910	do {
911	    n = tcsetpgrp(io_fds[SFD_SLAVE], cmnd_pgrp);
912	} while (n == -1 && errno == EINTR);
913    }
914
915    /* Wait for errno on pipe, signal on backchannel or for SIGCHLD */
916    maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
917    fdsr = ecalloc(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
918    tv.tv_sec = 0;
919    tv.tv_usec = 0;
920    for (;;) {
921	/* Check for signal on backchannel or errno on errpipe. */
922	FD_SET(backchannel, fdsr);
923	FD_SET(signal_pipe[0], fdsr);
924	if (errpipe[0] != -1)
925	    FD_SET(errpipe[0], fdsr);
926	maxfd = MAX(MAX(errpipe[0], signal_pipe[0]), backchannel);
927
928	/* If command exited we just poll, there may be data on errpipe. */
929	n = select(maxfd + 1, fdsr, NULL, NULL, alive ? NULL : &tv);
930	if (n <= 0) {
931	    if (n == 0)
932		goto done;
933	    if (errno == EINTR || errno == ENOMEM)
934		continue;
935	    warning("monitor: select failed");
936	    break;
937	}
938
939	if (FD_ISSET(signal_pipe[0], fdsr)) {
940	    n = read(signal_pipe[0], &signo, sizeof(signo));
941	    if (n == -1) {
942		if (errno == EINTR || errno == EAGAIN)
943		    continue;
944		warning("error reading from signal pipe");
945		goto done;
946	    }
947	    /*
948	     * Handle SIGCHLD specially and deliver other signals
949	     * directly to the command.
950	     */
951	    if (signo == SIGCHLD) {
952		if (!handle_sigchld(backchannel, &cstat))
953		    alive = FALSE;
954	    } else {
955		deliver_signal(cmnd_pid, signo);
956	    }
957	    continue;
958	}
959	if (errpipe[0] != -1 && FD_ISSET(errpipe[0], fdsr)) {
960	    /* read errno or EOF from command pipe */
961	    n = read(errpipe[0], &cstat, sizeof(cstat));
962	    if (n == -1) {
963		if (errno == EINTR)
964		    continue;
965		warning("error reading from pipe");
966		goto done;
967	    }
968	    /* Got errno or EOF, either way we are done with errpipe. */
969	    FD_CLR(errpipe[0], fdsr);
970	    close(errpipe[0]);
971	    errpipe[0] = -1;
972	}
973	if (FD_ISSET(backchannel, fdsr)) {
974	    struct command_status cstmp;
975
976	    /* read command from backchannel, should be a signal */
977	    n = recv(backchannel, &cstmp, sizeof(cstmp), 0);
978	    if (n == -1) {
979		if (errno == EINTR)
980		    continue;
981		warning("error reading from socketpair");
982		goto done;
983	    }
984	    if (cstmp.type != CMD_SIGNO) {
985		warningx("unexpected reply type on backchannel: %d", cstmp.type);
986		continue;
987	    }
988	    deliver_signal(cmnd_pid, cstmp.val);
989	}
990    }
991
992done:
993    if (alive) {
994	/* XXX An error occurred, should send an error back. */
995	kill(cmnd_pid, SIGKILL);
996    } else {
997	/* Send parent status. */
998	send_status(backchannel, &cstat);
999    }
1000    _exit(1);
1001
1002bad:
1003    return errno;
1004}
1005
1006/*
1007 * Flush any output buffered in iobufs or readable from the fds.
1008 * Does not read from /dev/tty.
1009 */
1010static void
1011flush_output()
1012{
1013    struct io_buffer *iob;
1014    struct timeval tv;
1015    fd_set *fdsr, *fdsw;
1016    int nready, nwriters, maxfd = -1;
1017
1018    /* Determine maxfd */
1019    for (iob = iobufs; iob; iob = iob->next) {
1020	if (iob->rfd > maxfd)
1021	    maxfd = iob->rfd;
1022	if (iob->wfd > maxfd)
1023	    maxfd = iob->wfd;
1024    }
1025    if (maxfd == -1)
1026	return;
1027
1028    fdsr = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1029    fdsw = emalloc2(howmany(maxfd + 1, NFDBITS), sizeof(fd_mask));
1030    for (;;) {
1031	memset(fdsw, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1032	memset(fdsr, 0, howmany(maxfd + 1, NFDBITS) * sizeof(fd_mask));
1033
1034	nwriters = 0;
1035	for (iob = iobufs; iob; iob = iob->next) {
1036	    /* Don't read from /dev/tty while flushing. */
1037	    if (io_fds[SFD_USERTTY] != -1 && iob->rfd == io_fds[SFD_USERTTY])
1038		continue;
1039	    if (iob->rfd == -1 && iob->wfd == -1)
1040	    	continue;
1041	    if (iob->off == iob->len) {
1042		iob->off = iob->len = 0;
1043		/* Forward the EOF from reader to writer. */
1044		if (iob->rfd == -1) {
1045		    safe_close(iob->wfd);
1046		    iob->wfd = -1;
1047		}
1048	    }
1049	    if (iob->rfd != -1) {
1050		if (iob->len != sizeof(iob->buf))
1051		    FD_SET(iob->rfd, fdsr);
1052	    }
1053	    if (iob->wfd != -1) {
1054		if (iob->len > iob->off) {
1055		    nwriters++;
1056		    FD_SET(iob->wfd, fdsw);
1057		}
1058	    }
1059	}
1060
1061	/* Don't sleep in select if there are no buffers that need writing. */
1062	tv.tv_sec = 0;
1063	tv.tv_usec = 0;
1064	nready = select(maxfd + 1, fdsr, fdsw, NULL, nwriters ? NULL : &tv);
1065	if (nready <= 0) {
1066	    if (nready == 0)
1067		break; /* all I/O flushed */
1068	    if (errno == EINTR || errno == ENOMEM)
1069		continue;
1070	    warning("select failed");
1071	}
1072	if (perform_io(fdsr, fdsw, NULL) != 0 || nready == -1)
1073	    break;
1074    }
1075    efree(fdsr);
1076    efree(fdsw);
1077}
1078
1079/*
1080 * Sets up std{in,out,err} and executes the actual command.
1081 * Returns only if execve() fails.
1082 */
1083static void
1084exec_pty(path, argv, envp, rbac_enabled, errfd)
1085    const char *path;
1086    char *argv[];
1087    char *envp[];
1088    int rbac_enabled;
1089    int *errfd;
1090{
1091    int maxfd = def_closefrom;
1092    pid_t self = getpid();
1093
1094    /* Set command process group here too to avoid a race. */
1095    setpgid(0, self);
1096
1097    /* Wire up standard fds, note that stdout/stderr may be pipes. */
1098    if (dup2(io_fds[SFD_STDIN], STDIN_FILENO) == -1 ||
1099	dup2(io_fds[SFD_STDOUT], STDOUT_FILENO) == -1 ||
1100	dup2(io_fds[SFD_STDERR], STDERR_FILENO) == -1)
1101	error(1, "dup2");
1102
1103    /* Wait for parent to grant us the tty if we are foreground. */
1104    if (foreground) {
1105	while (tcgetpgrp(io_fds[SFD_SLAVE]) != self)
1106	    ; /* spin */
1107    }
1108
1109    /* We have guaranteed that the slave fd is > 2 */
1110    if (io_fds[SFD_SLAVE] != -1)
1111	close(io_fds[SFD_SLAVE]);
1112    if (io_fds[SFD_STDIN] != io_fds[SFD_SLAVE])
1113	close(io_fds[SFD_STDIN]);
1114    if (io_fds[SFD_STDOUT] != io_fds[SFD_SLAVE])
1115	close(io_fds[SFD_STDOUT]);
1116    if (io_fds[SFD_STDERR] != io_fds[SFD_SLAVE])
1117	close(io_fds[SFD_STDERR]);
1118
1119    dup2(*errfd, maxfd);
1120    (void)fcntl(maxfd, F_SETFD, FD_CLOEXEC);
1121    *errfd = maxfd++;
1122    closefrom(maxfd);
1123#ifdef HAVE_SELINUX
1124    if (rbac_enabled)
1125	selinux_execve(path, argv, envp);
1126    else
1127#endif
1128	my_execve(path, argv, envp);
1129}
1130
1131/*
1132 * Propagates tty size change signals to pty being used by the command.
1133 */
1134static void
1135sync_ttysize(src, dst)
1136    int src;
1137    int dst;
1138{
1139#ifdef TIOCGWINSZ
1140    struct winsize wsize;
1141    pid_t pgrp;
1142
1143    if (ioctl(src, TIOCGWINSZ, &wsize) == 0) {
1144	    ioctl(dst, TIOCSWINSZ, &wsize);
1145	    if ((pgrp = tcgetpgrp(dst)) != -1)
1146		killpg(pgrp, SIGWINCH);
1147    }
1148#endif
1149}
1150
1151/*
1152 * Handler for SIGWINCH in parent.
1153 */
1154static void
1155sigwinch(s)
1156    int s;
1157{
1158    int serrno = errno;
1159
1160    sync_ttysize(io_fds[SFD_USERTTY], io_fds[SFD_SLAVE]);
1161    errno = serrno;
1162}
1163
1164/*
1165 * Only close the fd if it is not /dev/tty or std{in,out,err}.
1166 * Return value is the same as send(2).
1167 */
1168static int
1169safe_close(fd)
1170    int fd;
1171{
1172    /* Avoid closing /dev/tty or std{in,out,err}. */
1173    if (fd < 3 || fd == io_fds[SFD_USERTTY]) {
1174	errno = EINVAL;
1175	return -1;
1176    }
1177    return close(fd);
1178}
1179
1180void
1181cleanup_pty(gotsignal)
1182    int gotsignal;
1183{
1184    if (io_fds[SFD_USERTTY] != -1) {
1185	check_foreground();
1186	if (foreground)
1187	    term_restore(io_fds[SFD_USERTTY], 0);
1188    }
1189}
1190