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