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