script: make -t independent of scriptreplay
[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:       "[-afqt] [-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:     "\n        -t      Send timing to stderr"
31
32 //util-linux-2.28:
33 //-t[FILE]
34 //-e: return exit code of the child
35
36 //FYI (reported as bbox bug #2749):
37 // > script -q -c 'echo -e -n "1\n2\n3\n"' /dev/null </dev/null >123.txt
38 // > The output file on full-blown ubuntu system contains 6 bytes.
39 // > Output on Busybox system (arm-linux) contains extra '\r' byte in each line.
40 //however, in my test, "script" from util-linux-2.28 seems to also add '\r' bytes.
41
42 #include "libbb.h"
43 #include "common_bufsiz.h"
44
45 int script_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
46 int script_main(int argc UNUSED_PARAM, char **argv)
47 {
48         int opt;
49         int mode;
50         int child_pid;
51         int attr_ok; /* NB: 0: ok */
52         int winsz_ok;
53         int pty;
54         char pty_line[GETPTY_BUFSIZE];
55         struct termios tt, rtt;
56         struct winsize win;
57         const char *fname = "typescript";
58         const char *shell;
59         char shell_opt[] = "-i";
60         char *shell_arg = NULL;
61         enum {
62                 OPT_a = (1 << 0),
63                 OPT_c = (1 << 1),
64                 OPT_f = (1 << 2),
65                 OPT_q = (1 << 3),
66                 OPT_t = (1 << 4),
67         };
68
69 #if ENABLE_LONG_OPTS
70         static const char getopt_longopts[] ALIGN1 =
71                 "append\0"  No_argument       "a"
72                 "command\0" Required_argument "c"
73                 "flush\0"   No_argument       "f"
74                 "quiet\0"   No_argument       "q"
75                 "timing\0"  No_argument       "t"
76                 ;
77
78         applet_long_options = getopt_longopts;
79 #endif
80
81         opt_complementary = "?1"; /* max one arg */
82         opt = getopt32(argv, "ac:fqt", &shell_arg);
83         //argc -= optind;
84         argv += optind;
85         if (argv[0]) {
86                 fname = argv[0];
87         }
88         mode = O_CREAT|O_TRUNC|O_WRONLY;
89         if (opt & OPT_a) {
90                 mode = O_CREAT|O_APPEND|O_WRONLY;
91         }
92         if (opt & OPT_c) {
93                 shell_opt[1] = 'c';
94         }
95         if (!(opt & OPT_q)) {
96                 printf("Script started, file is %s\n", fname);
97         }
98
99         shell = get_shell_name();
100
101         /* Some people run "script ... 0>&-".
102          * Our code assumes that STDIN_FILENO != pty.
103          * Ensure STDIN_FILENO is not closed:
104          */
105         bb_sanitize_stdio();
106
107         pty = xgetpty(pty_line);
108
109         /* get current stdin's tty params */
110         attr_ok = tcgetattr(0, &tt);
111         winsz_ok = ioctl(0, TIOCGWINSZ, (char *)&win);
112
113         rtt = tt;
114         cfmakeraw(&rtt);
115         rtt.c_lflag &= ~ECHO;
116         tcsetattr(0, TCSAFLUSH, &rtt);
117
118         /* "script" from util-linux exits when child exits,
119          * we wouldn't wait for EOF from slave pty
120          * (output may be produced by grandchildren of child) */
121         signal(SIGCHLD, record_signo);
122
123         /* TODO: SIGWINCH? pass window size changes down to slave? */
124
125         child_pid = xvfork();
126
127         if (child_pid) {
128                 /* parent */
129                 struct pollfd pfd[2];
130                 int outfd, count, loop;
131                 double oldtime = time(NULL);
132                 smallint fd_count = 2;
133 #define buf bb_common_bufsiz1
134                 setup_common_bufsiz();
135
136                 outfd = xopen(fname, mode);
137                 pfd[0].fd = pty;
138                 pfd[0].events = POLLIN;
139                 pfd[1].fd = STDIN_FILENO;
140                 pfd[1].events = POLLIN;
141                 ndelay_on(pty); /* this descriptor is not shared, can do this */
142                 /* ndelay_on(STDIN_FILENO); - NO, stdin can be shared! Pity :( */
143
144                 /* copy stdin to pty master input,
145                  * copy pty master output to stdout and file */
146                 /* TODO: don't use full_write's, use proper write buffering */
147                 while (fd_count && !bb_got_signal) {
148                         /* not safe_poll! we want SIGCHLD to EINTR poll */
149                         if (poll(pfd, fd_count, -1) < 0 && errno != EINTR) {
150                                 /* If child exits too quickly, we may get EIO:
151                                  * for example, try "script -c true" */
152                                 break;
153                         }
154                         if (pfd[0].revents) {
155                                 errno = 0;
156                                 count = safe_read(pty, buf, COMMON_BUFSIZE);
157                                 if (count <= 0 && errno != EAGAIN) {
158                                         /* err/eof from pty: exit */
159                                         goto restore;
160                                 }
161                                 if (count > 0) {
162                                         if (opt & OPT_t) {
163                                                 struct timeval tv;
164                                                 double newtime;
165
166                                                 gettimeofday(&tv, NULL);
167                                                 newtime = tv.tv_sec + (double) tv.tv_usec / 1000000;
168                                                 fprintf(stderr, "%f %u\n", newtime - oldtime, count);
169                                                 oldtime = newtime;
170                                         }
171                                         full_write(STDOUT_FILENO, buf, count);
172                                         full_write(outfd, buf, count);
173                                         if (opt & OPT_f) {
174                                                 fsync(outfd);
175                                         }
176                                 }
177                         }
178                         if (pfd[1].revents) {
179                                 count = safe_read(STDIN_FILENO, buf, COMMON_BUFSIZE);
180                                 if (count <= 0) {
181                                         /* err/eof from stdin: don't read stdin anymore */
182                                         pfd[1].revents = 0;
183                                         fd_count--;
184                                 } else {
185                                         full_write(pty, buf, count);
186                                 }
187                         }
188                 }
189                 /* If loop was exited because SIGCHLD handler set bb_got_signal,
190                  * there still can be some buffered output. But dont loop forever:
191                  * we won't pump orphaned grandchildren's output indefinitely.
192                  * Testcase: running this in script:
193                  *      exec dd if=/dev/zero bs=1M count=1
194                  * must have "1+0 records in, 1+0 records out" captured too.
195                  * (util-linux's script doesn't do this. buggy :) */
196                 loop = 999;
197                 /* pty is in O_NONBLOCK mode, we exit as soon as buffer is empty */
198                 while (--loop && (count = safe_read(pty, buf, COMMON_BUFSIZE)) > 0) {
199                         full_write(STDOUT_FILENO, buf, count);
200                         full_write(outfd, buf, count);
201                 }
202  restore:
203                 if (attr_ok == 0)
204                         tcsetattr(0, TCSAFLUSH, &tt);
205                 if (!(opt & OPT_q))
206                         printf("Script done, file is %s\n", fname);
207                 return EXIT_SUCCESS;
208         }
209
210         /* child: make pty slave to be input, output, error; run shell */
211         close(pty); /* close pty master */
212         /* open pty slave to fd 0,1,2 */
213         close(0);
214         xopen(pty_line, O_RDWR); /* uses fd 0 */
215         xdup2(0, 1);
216         xdup2(0, 2);
217         /* copy our original stdin tty's parameters to pty */
218         if (attr_ok == 0)
219                 tcsetattr(0, TCSAFLUSH, &tt);
220         if (winsz_ok == 0)
221                 ioctl(0, TIOCSWINSZ, (char *)&win);
222         /* set pty as a controlling tty */
223         setsid();
224         ioctl(0, TIOCSCTTY, 0 /* 0: don't forcibly steal */);
225
226         /* Non-ignored signals revert to SIG_DFL on exec anyway */
227         /*signal(SIGCHLD, SIG_DFL);*/
228         execl(shell, shell, shell_opt, shell_arg, (char *) NULL);
229         bb_simple_perror_msg_and_die(shell);
230 }