Update menuconfig items with approximate applet sizes
[oweals/busybox.git] / util-linux / script.c
1 /* vi: set sw=4 ts=4: */
2 /*
3  * script implementation for busybox
4  *
5  * pascal.bellard@ads-lu.com
6  *
7  * Based on code from util-linux v 2.12r
8  * Copyright (c) 1980
9  * The Regents of the University of California.  All rights reserved.
10  *
11  * Licensed under GPLv2 or later, see file LICENSE in this source tree.
12  */
13 //config:config SCRIPT
14 //config:       bool "script (8 kb)"
15 //config:       default y
16 //config:       help
17 //config:         The script makes typescript of terminal session.
18
19 //applet:IF_SCRIPT(APPLET(script, BB_DIR_USR_BIN, BB_SUID_DROP))
20
21 //kbuild:lib-$(CONFIG_SCRIPT) += script.o
22
23 //usage:#define script_trivial_usage
24 //usage:       "[-afq" IF_SCRIPTREPLAY("t") "] [-c PROG] [OUTFILE]"
25 //usage:#define script_full_usage "\n\n"
26 //usage:       "        -a      Append output"
27 //usage:     "\n        -c PROG Run PROG, not shell"
28 //usage:     "\n        -f      Flush output after each write"
29 //usage:     "\n        -q      Quiet"
30 //usage:        IF_SCRIPTREPLAY(
31 //usage:     "\n        -t      Send timing to stderr"
32 //usage:        )
33
34 #include "libbb.h"
35 #include "common_bufsiz.h"
36
37 int script_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
38 int script_main(int argc UNUSED_PARAM, char **argv)
39 {
40         int opt;
41         int mode;
42         int child_pid;
43         int attr_ok; /* NB: 0: ok */
44         int winsz_ok;
45         int pty;
46         char pty_line[GETPTY_BUFSIZE];
47         struct termios tt, rtt;
48         struct winsize win;
49         const char *fname = "typescript";
50         const char *shell;
51         char shell_opt[] = "-i";
52         char *shell_arg = NULL;
53         enum {
54                 OPT_a = (1 << 0),
55                 OPT_c = (1 << 1),
56                 OPT_f = (1 << 2),
57                 OPT_q = (1 << 3),
58                 OPT_t = (1 << 4),
59         };
60
61 #if ENABLE_LONG_OPTS
62         static const char getopt_longopts[] ALIGN1 =
63                 "append\0"  No_argument       "a"
64                 "command\0" Required_argument "c"
65                 "flush\0"   No_argument       "f"
66                 "quiet\0"   No_argument       "q"
67                 IF_SCRIPTREPLAY("timing\0" No_argument "t")
68                 ;
69
70         applet_long_options = getopt_longopts;
71 #endif
72
73         opt_complementary = "?1"; /* max one arg */
74         opt = getopt32(argv, "ac:fq" IF_SCRIPTREPLAY("t") , &shell_arg);
75         //argc -= optind;
76         argv += optind;
77         if (argv[0]) {
78                 fname = argv[0];
79         }
80         mode = O_CREAT|O_TRUNC|O_WRONLY;
81         if (opt & OPT_a) {
82                 mode = O_CREAT|O_APPEND|O_WRONLY;
83         }
84         if (opt & OPT_c) {
85                 shell_opt[1] = 'c';
86         }
87         if (!(opt & OPT_q)) {
88                 printf("Script started, file is %s\n", fname);
89         }
90
91         shell = get_shell_name();
92
93         /* Some people run "script ... 0>&-".
94          * Our code assumes that STDIN_FILENO != pty.
95          * Ensure STDIN_FILENO is not closed:
96          */
97         bb_sanitize_stdio();
98
99         pty = xgetpty(pty_line);
100
101         /* get current stdin's tty params */
102         attr_ok = tcgetattr(0, &tt);
103         winsz_ok = ioctl(0, TIOCGWINSZ, (char *)&win);
104
105         rtt = tt;
106         cfmakeraw(&rtt);
107         rtt.c_lflag &= ~ECHO;
108         tcsetattr(0, TCSAFLUSH, &rtt);
109
110         /* "script" from util-linux exits when child exits,
111          * we wouldn't wait for EOF from slave pty
112          * (output may be produced by grandchildren of child) */
113         signal(SIGCHLD, record_signo);
114
115         /* TODO: SIGWINCH? pass window size changes down to slave? */
116
117         child_pid = xvfork();
118
119         if (child_pid) {
120                 /* parent */
121                 struct pollfd pfd[2];
122                 int outfd, count, loop;
123                 double oldtime = ENABLE_SCRIPTREPLAY ? time(NULL) : 0;
124                 smallint fd_count = 2;
125 #define buf bb_common_bufsiz1
126                 setup_common_bufsiz();
127
128                 outfd = xopen(fname, mode);
129                 pfd[0].fd = pty;
130                 pfd[0].events = POLLIN;
131                 pfd[1].fd = STDIN_FILENO;
132                 pfd[1].events = POLLIN;
133                 ndelay_on(pty); /* this descriptor is not shared, can do this */
134                 /* ndelay_on(STDIN_FILENO); - NO, stdin can be shared! Pity :( */
135
136                 /* copy stdin to pty master input,
137                  * copy pty master output to stdout and file */
138                 /* TODO: don't use full_write's, use proper write buffering */
139                 while (fd_count && !bb_got_signal) {
140                         /* not safe_poll! we want SIGCHLD to EINTR poll */
141                         if (poll(pfd, fd_count, -1) < 0 && errno != EINTR) {
142                                 /* If child exits too quickly, we may get EIO:
143                                  * for example, try "script -c true" */
144                                 break;
145                         }
146                         if (pfd[0].revents) {
147                                 errno = 0;
148                                 count = safe_read(pty, buf, COMMON_BUFSIZE);
149                                 if (count <= 0 && errno != EAGAIN) {
150                                         /* err/eof from pty: exit */
151                                         goto restore;
152                                 }
153                                 if (count > 0) {
154                                         if (ENABLE_SCRIPTREPLAY && (opt & OPT_t)) {
155                                                 struct timeval tv;
156                                                 double newtime;
157
158                                                 gettimeofday(&tv, NULL);
159                                                 newtime = tv.tv_sec + (double) tv.tv_usec / 1000000;
160                                                 fprintf(stderr, "%f %u\n", newtime - oldtime, count);
161                                                 oldtime = newtime;
162                                         }
163                                         full_write(STDOUT_FILENO, buf, count);
164                                         full_write(outfd, buf, count);
165                                         if (opt & OPT_f) {
166                                                 fsync(outfd);
167                                         }
168                                 }
169                         }
170                         if (pfd[1].revents) {
171                                 count = safe_read(STDIN_FILENO, buf, COMMON_BUFSIZE);
172                                 if (count <= 0) {
173                                         /* err/eof from stdin: don't read stdin anymore */
174                                         pfd[1].revents = 0;
175                                         fd_count--;
176                                 } else {
177                                         full_write(pty, buf, count);
178                                 }
179                         }
180                 }
181                 /* If loop was exited because SIGCHLD handler set bb_got_signal,
182                  * there still can be some buffered output. But dont loop forever:
183                  * we won't pump orphaned grandchildren's output indefinitely.
184                  * Testcase: running this in script:
185                  *      exec dd if=/dev/zero bs=1M count=1
186                  * must have "1+0 records in, 1+0 records out" captured too.
187                  * (util-linux's script doesn't do this. buggy :) */
188                 loop = 999;
189                 /* pty is in O_NONBLOCK mode, we exit as soon as buffer is empty */
190                 while (--loop && (count = safe_read(pty, buf, COMMON_BUFSIZE)) > 0) {
191                         full_write(STDOUT_FILENO, buf, count);
192                         full_write(outfd, buf, count);
193                 }
194  restore:
195                 if (attr_ok == 0)
196                         tcsetattr(0, TCSAFLUSH, &tt);
197                 if (!(opt & OPT_q))
198                         printf("Script done, file is %s\n", fname);
199                 return EXIT_SUCCESS;
200         }
201
202         /* child: make pty slave to be input, output, error; run shell */
203         close(pty); /* close pty master */
204         /* open pty slave to fd 0,1,2 */
205         close(0);
206         xopen(pty_line, O_RDWR); /* uses fd 0 */
207         xdup2(0, 1);
208         xdup2(0, 2);
209         /* copy our original stdin tty's parameters to pty */
210         if (attr_ok == 0)
211                 tcsetattr(0, TCSAFLUSH, &tt);
212         if (winsz_ok == 0)
213                 ioctl(0, TIOCSWINSZ, (char *)&win);
214         /* set pty as a controlling tty */
215         setsid();
216         ioctl(0, TIOCSCTTY, 0 /* 0: don't forcibly steal */);
217
218         /* Non-ignored signals revert to SIG_DFL on exec anyway */
219         /*signal(SIGCHLD, SIG_DFL);*/
220         execl(shell, shell, shell_opt, shell_arg, (char *) NULL);
221         bb_simple_perror_msg_and_die(shell);
222 }