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