Annotation of embedaddon/sudo/src/exec_pty.c, revision 1.1.1.2

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

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