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