2 * Copyright (c) 1980 Regents of the University of California.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * 1999-02-22 Arkadiusz MiĆkiewicz <misiek@pld.ORG.PL>
36 * - added Native Language Support
38 * 2000-07-30 Per Andreas Buer <per@linpro.no> - added "q"-option
40 * 2014-05-30 Csaba Kos <csaba.kos@gmail.com>
41 * - fixed a rare deadlock after child termination
50 #include <sys/ioctl.h>
63 #include <sys/signalfd.h>
67 #include "closestream.h"
72 #include "monotonic.h"
73 #include "timeutils.h"
77 static UL_DEBUG_DEFINE_MASK(script
);
78 UL_DEBUG_DEFINE_MASKNAMES(script
) = UL_DEBUG_EMPTY_MASKNAMES
;
80 #define SCRIPT_DEBUG_INIT (1 << 1)
81 #define SCRIPT_DEBUG_POLL (1 << 2)
82 #define SCRIPT_DEBUG_SIGNAL (1 << 3)
83 #define SCRIPT_DEBUG_IO (1 << 4)
84 #define SCRIPT_DEBUG_MISC (1 << 5)
85 #define SCRIPT_DEBUG_ALL 0xFFFF
87 #define DBG(m, x) __UL_DBG(script, SCRIPT_DEBUG_, m, x)
88 #define ON_DBG(m, x) __UL_DBG_CALL(script, SCRIPT_DEBUG_, m, x)
90 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
94 #ifdef HAVE_LIBUTEMPTER
95 # include <utempter.h>
98 #define DEFAULT_TYPESCRIPT_FILENAME "typescript"
100 struct script_control
{
101 char *shell
; /* shell to be executed */
102 char *command
; /* command to be executed */
103 char *fname
; /* output file path */
104 FILE *typescriptfp
; /* output file pointer */
105 char *tname
; /* timing file path */
106 FILE *timingfp
; /* timing file pointer */
107 struct timeval oldtime
; /* previous write or command start time */
108 int master
; /* pseudoterminal master file descriptor */
109 int slave
; /* pseudoterminal slave file descriptor */
110 int poll_timeout
; /* poll() timeout, used in end of execution */
111 pid_t child
; /* child pid */
112 int childstatus
; /* child process exit value */
113 struct termios attrs
; /* slave terminal runtime attributes */
114 struct winsize win
; /* terminal window size */
115 #if !HAVE_LIBUTIL || !HAVE_PTY_H
116 char *line
; /* terminal line */
119 append
:1, /* append output */
120 rc_wanted
:1, /* return child exit value */
121 flush
:1, /* flush after each write */
122 quiet
:1, /* suppress most output */
123 timing
:1, /* include timing file */
124 force
:1, /* write output to links */
125 isterm
:1, /* is child process running as terminal */
126 die
:1; /* terminate program */
128 sigset_t sigset
; /* catch SIGCHLD and SIGWINCH with signalfd() */
129 sigset_t sigorg
; /* original signal mask */
130 int sigfd
; /* file descriptor for signalfd() */
133 static void script_init_debug(void)
135 __UL_INIT_DEBUG(script
, SCRIPT_DEBUG_
, 0, SCRIPT_DEBUG
);
139 * For tests we want to be able to control time output
142 static inline time_t script_time(time_t *t
)
144 const char *str
= getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
147 if (!str
|| sscanf(str
, "%"SCNi64
, &sec
) != 1)
153 #else /* !TEST_SCRIPT */
154 # define script_time(x) time(x)
157 static void __attribute__((__noreturn__
)) usage(void)
160 fputs(USAGE_HEADER
, out
);
161 fprintf(out
, _(" %s [options] [file]\n"), program_invocation_short_name
);
163 fputs(USAGE_SEPARATOR
, out
);
164 fputs(_("Make a typescript of a terminal session.\n"), out
);
166 fputs(USAGE_OPTIONS
, out
);
167 fputs(_(" -a, --append append the output\n"
168 " -c, --command <command> run command rather than interactive shell\n"
169 " -e, --return return exit code of the child process\n"
170 " -f, --flush run flush after each write\n"
171 " --force use output file even when it is a link\n"
172 " -q, --quiet be quiet\n"
173 " -t, --timing[=<file>] output timing data to stderr (or to FILE)\n"
174 " -V, --version output version information and exit\n"
175 " -h, --help display this help and exit\n\n"), out
);
177 fprintf(out
, USAGE_MAN_TAIL("script(1)"));
181 static void die_if_link(const struct script_control
*ctl
)
187 if (lstat(ctl
->fname
, &s
) == 0 && (S_ISLNK(s
.st_mode
) || s
.st_nlink
> 1))
189 _("output file `%s' is a link\n"
190 "Use --force if you really want to use it.\n"
191 "Program not started."), ctl
->fname
);
194 static void __attribute__((__noreturn__
)) done(struct script_control
*ctl
)
196 DBG(MISC
, ul_debug("done!"));
199 tcsetattr(STDIN_FILENO
, TCSADRAIN
, &ctl
->attrs
);
200 if (!ctl
->quiet
&& ctl
->typescriptfp
)
201 printf(_("Script done, file is %s\n"), ctl
->fname
);
202 #ifdef HAVE_LIBUTEMPTER
203 if (ctl
->master
>= 0)
204 utempter_remove_record(ctl
->master
);
206 kill(ctl
->child
, SIGTERM
); /* make sure we don't create orphans */
208 if (ctl
->timingfp
&& close_stream(ctl
->timingfp
) != 0)
209 err(EXIT_FAILURE
, "write failed: %s", ctl
->tname
);
210 if (ctl
->typescriptfp
&& close_stream(ctl
->typescriptfp
) != 0)
211 err(EXIT_FAILURE
, "write failed: %s", ctl
->fname
);
213 if (ctl
->rc_wanted
) {
214 if (WIFSIGNALED(ctl
->childstatus
))
215 exit(WTERMSIG(ctl
->childstatus
) + 0x80);
217 exit(WEXITSTATUS(ctl
->childstatus
));
222 static void __attribute__((__noreturn__
)) fail(struct script_control
*ctl
)
224 DBG(MISC
, ul_debug("fail!"));
229 static void wait_for_child(struct script_control
*ctl
, int wait
)
233 int options
= wait
? 0 : WNOHANG
;
235 DBG(MISC
, ul_debug("waiting for child"));
237 while ((pid
= wait3(&status
, options
, NULL
)) > 0)
238 if (pid
== ctl
->child
)
239 ctl
->childstatus
= status
;
242 static void write_output(struct script_control
*ctl
, char *obuf
,
245 DBG(IO
, ul_debug(" writing output"));
247 if (ctl
->timing
&& ctl
->timingfp
) {
248 struct timeval now
, delta
;
250 DBG(IO
, ul_debug(" writing timing info"));
252 gettime_monotonic(&now
);
253 timersub(&now
, &ctl
->oldtime
, &delta
);
254 fprintf(ctl
->timingfp
, "%ld.%06ld %zd\n",
255 (long)delta
.tv_sec
, (long)delta
.tv_usec
, bytes
);
257 fflush(ctl
->timingfp
);
261 DBG(IO
, ul_debug(" writing to script file"));
263 if (fwrite_all(obuf
, 1, bytes
, ctl
->typescriptfp
)) {
264 warn(_("cannot write script file"));
268 fflush(ctl
->typescriptfp
);
270 DBG(IO
, ul_debug(" writing to output"));
272 if (write_all(STDOUT_FILENO
, obuf
, bytes
)) {
273 DBG(IO
, ul_debug(" writing output *failed*"));
274 warn(_("write failed"));
278 DBG(IO
, ul_debug(" writing output *done*"));
281 static int write_to_shell(struct script_control
*ctl
,
282 char *buf
, size_t bufsz
)
284 return write_all(ctl
->master
, buf
, bufsz
);
288 * The script(1) is usually faster than shell, so it's a good idea to wait until
289 * the previous message has been already read by shell from slave before we
290 * write to master. This is necessary especially for EOF situation when we can
291 * send EOF to master before shell is fully initialized, to workaround this
292 * problem we wait until slave is empty. For example:
294 * echo "date" | script
296 * Unfortunately, the child (usually shell) can ignore stdin at all, so we
297 * don't wait forever to avoid dead locks...
299 * Note that script is primarily designed for interactive sessions as it
300 * maintains master+slave tty stuff within the session. Use pipe to write to
301 * script(1) and assume non-interactive (tee-like) behavior is NOT well
304 static void write_eof_to_shell(struct script_control
*ctl
)
306 unsigned int tries
= 0;
307 struct pollfd fds
[] = {
308 { .fd
= ctl
->slave
, .events
= POLLIN
}
312 DBG(IO
, ul_debug(" waiting for empty slave"));
313 while (poll(fds
, 1, 10) == 1 && tries
< 8) {
314 DBG(IO
, ul_debug(" slave is not empty"));
319 DBG(IO
, ul_debug(" slave is empty now"));
321 DBG(IO
, ul_debug(" sending EOF to master"));
322 write_to_shell(ctl
, &c
, sizeof(char));
325 static void handle_io(struct script_control
*ctl
, int fd
, int *eof
)
330 DBG(IO
, ul_debug("%d FD active", fd
));
333 /* read from active FD */
334 bytes
= read(fd
, buf
, sizeof(buf
));
336 if (errno
== EAGAIN
|| errno
== EINTR
)
346 /* from stdin (user) to command */
347 if (fd
== STDIN_FILENO
) {
348 DBG(IO
, ul_debug(" stdin --> master %zd bytes", bytes
));
350 if (write_to_shell(ctl
, buf
, bytes
)) {
351 warn(_("write failed"));
354 /* without sync write_output() will write both input &
355 * shell output that looks like double echoing */
356 fdatasync(ctl
->master
);
358 /* from command (master) to stdout */
359 } else if (fd
== ctl
->master
) {
360 DBG(IO
, ul_debug(" master --> stdout %zd bytes", bytes
));
361 write_output(ctl
, buf
, bytes
);
365 static void handle_signal(struct script_control
*ctl
, int fd
)
367 struct signalfd_siginfo info
;
370 DBG(SIGNAL
, ul_debug("signal FD %d active", fd
));
372 bytes
= read(fd
, &info
, sizeof(info
));
373 if (bytes
!= sizeof(info
)) {
374 if (bytes
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
379 switch (info
.ssi_signo
) {
381 DBG(SIGNAL
, ul_debug(" get signal SIGCHLD"));
382 wait_for_child(ctl
, 0);
383 ctl
->poll_timeout
= 10;
386 DBG(SIGNAL
, ul_debug(" get signal SIGWINCH"));
388 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
389 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
397 DBG(SIGNAL
, ul_debug(" get signal SIG{TERM,INT,QUIT}"));
398 fprintf(stderr
, _("\nSession terminated.\n"));
399 /* Child termination is going to generate SIGCHILD (see above) */
400 kill(ctl
->child
, SIGTERM
);
407 static void do_io(struct script_control
*ctl
)
409 int ret
, ignore_stdin
= 0, eof
= 0;
410 time_t tvec
= script_time((time_t *)NULL
);
415 POLLFD_STDIN
/* optional; keep it last, see ignore_stdin */
418 struct pollfd pfd
[] = {
419 [POLLFD_SIGNAL
] = { .fd
= ctl
->sigfd
, .events
= POLLIN
| POLLERR
| POLLHUP
},
420 [POLLFD_MASTER
] = { .fd
= ctl
->master
, .events
= POLLIN
| POLLERR
| POLLHUP
},
421 [POLLFD_STDIN
] = { .fd
= STDIN_FILENO
, .events
= POLLIN
| POLLERR
| POLLHUP
}
425 if ((ctl
->typescriptfp
=
426 fopen(ctl
->fname
, ctl
->append
? "a" UL_CLOEXECSTR
: "w" UL_CLOEXECSTR
)) == NULL
) {
427 warn(_("cannot open %s"), ctl
->fname
);
432 if (!(ctl
->timingfp
= fopen("/dev/stderr", "w" UL_CLOEXECSTR
)))
433 err(EXIT_FAILURE
, _("cannot open %s"), "/dev/stderr");
434 } else if (!(ctl
->timingfp
= fopen(ctl
->tname
, "w" UL_CLOEXECSTR
)))
435 err(EXIT_FAILURE
, _("cannot open %s"), ctl
->tname
);
439 if (ctl
->typescriptfp
) {
440 strtime_iso(&tvec
, ISO_8601_DATE
| ISO_8601_TIME
|
441 ISO_8601_TIMEZONE
| ISO_8601_SPACE
,
443 fprintf(ctl
->typescriptfp
, _("Script started on %s\n"), buf
);
445 gettime_monotonic(&ctl
->oldtime
);
451 DBG(POLL
, ul_debug("calling poll()"));
453 /* wait for input or signal */
454 ret
= poll(pfd
, ARRAY_SIZE(pfd
) - ignore_stdin
, ctl
->poll_timeout
);
456 DBG(POLL
, ul_debug("poll() rc=%d", ret
));
461 warn(_("poll failed"));
465 DBG(POLL
, ul_debug("setting die=1"));
470 for (i
= 0; i
< ARRAY_SIZE(pfd
) - ignore_stdin
; i
++) {
471 if (pfd
[i
].revents
== 0)
474 DBG(POLL
, ul_debug(" active pfd[%s].fd=%d %s %s %s",
475 i
== POLLFD_STDIN
? "stdin" :
476 i
== POLLFD_MASTER
? "master" :
477 i
== POLLFD_SIGNAL
? "signal" : "???",
479 pfd
[i
].revents
& POLLIN
? "POLLIN" : "",
480 pfd
[i
].revents
& POLLHUP
? "POLLHUP" : "",
481 pfd
[i
].revents
& POLLERR
? "POLLERR" : ""));
486 if (pfd
[i
].revents
& POLLIN
)
487 handle_io(ctl
, pfd
[i
].fd
, &eof
);
488 /* EOF maybe detected by two ways:
489 * A) poll() return POLLHUP event after close()
490 * B) read() returns 0 (no data) */
491 if ((pfd
[i
].revents
& POLLHUP
) || eof
) {
492 DBG(POLL
, ul_debug(" ignore FD"));
494 /* according to man poll() set FD to -1 can't be used to ignore
495 * STDIN, so let's remove the FD from pool at all */
496 if (i
== POLLFD_STDIN
) {
498 write_eof_to_shell(ctl
);
499 DBG(POLL
, ul_debug(" ignore STDIN"));
504 handle_signal(ctl
, pfd
[i
].fd
);
510 DBG(POLL
, ul_debug("poll() done"));
513 wait_for_child(ctl
, 1);
515 if (ctl
->typescriptfp
) {
516 tvec
= script_time((time_t *)NULL
);
517 strtime_iso(&tvec
, ISO_8601_DATE
| ISO_8601_TIME
|
518 ISO_8601_TIMEZONE
| ISO_8601_SPACE
,
520 fprintf(ctl
->typescriptfp
, _("\nScript done on %s\n"), buf
);
525 static void getslave(struct script_control
*ctl
)
528 ctl
->line
[strlen("/dev/")] = 't';
529 ctl
->slave
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
530 if (ctl
->slave
< 0) {
531 warn(_("cannot open %s"), ctl
->line
);
535 tcsetattr(ctl
->slave
, TCSANOW
, &ctl
->attrs
);
536 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
540 ioctl(ctl
->slave
, TIOCSCTTY
, 0);
543 /* don't use DBG() stuff here otherwise it will be in the typescript file */
544 static void __attribute__((__noreturn__
)) do_shell(struct script_control
*ctl
)
550 /* close things irrelevant for this process */
554 dup2(ctl
->slave
, STDIN_FILENO
);
555 dup2(ctl
->slave
, STDOUT_FILENO
);
556 dup2(ctl
->slave
, STDERR_FILENO
);
561 shname
= strrchr(ctl
->shell
, '/');
567 sigprocmask(SIG_SETMASK
, &ctl
->sigorg
, NULL
);
570 * When invoked from within /etc/csh.login, script spawns a csh shell
571 * that spawns programs that cannot be killed with a SIGTERM. This is
572 * because csh has a documented behavior wherein it disables all
573 * signals when processing the /etc/csh.* files.
575 * Let's restore the default behavior.
577 signal(SIGTERM
, SIG_DFL
);
579 if (access(ctl
->shell
, X_OK
) == 0) {
581 execl(ctl
->shell
, shname
, "-c", ctl
->command
, NULL
);
583 execl(ctl
->shell
, shname
, "-i", NULL
);
586 execlp(shname
, "-c", ctl
->command
, NULL
);
588 execlp(shname
, "-i", NULL
);
590 warn(_("failed to execute %s"), ctl
->shell
);
594 static void fixtty(struct script_control
*ctl
)
603 rtt
.c_lflag
&= ~ECHO
;
604 tcsetattr(STDIN_FILENO
, TCSANOW
, &rtt
);
607 static void getmaster(struct script_control
*ctl
)
609 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
612 ctl
->isterm
= isatty(STDIN_FILENO
);
615 if (tcgetattr(STDIN_FILENO
, &ctl
->attrs
) != 0)
616 err(EXIT_FAILURE
, _("failed to get terminal attributes"));
617 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
618 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, &ctl
->attrs
, &ctl
->win
);
620 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, NULL
, NULL
);
623 warn(_("openpty failed"));
627 char *pty
, *bank
, *cp
;
629 ctl
->isterm
= isatty(STDIN_FILENO
);
631 pty
= &ctl
->line
[strlen("/dev/ptyp")];
632 for (bank
= "pqrs"; *bank
; bank
++) {
633 ctl
->line
[strlen("/dev/pty")] = *bank
;
635 if (access(ctl
->line
, F_OK
) != 0)
637 for (cp
= "0123456789abcdef"; *cp
; cp
++) {
639 ctl
->master
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
640 if (ctl
->master
>= 0) {
641 char *tp
= &ctl
->line
[strlen("/dev/")];
644 /* verify slave side is usable */
646 ok
= access(ctl
->line
, R_OK
| W_OK
) == 0;
650 tcgetattr(STDIN_FILENO
, &ctl
->attrs
);
651 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
661 warn(_("out of pty's"));
663 #endif /* not HAVE_LIBUTIL */
665 DBG(IO
, ul_debug("master fd: %d", ctl
->master
));
668 int main(int argc
, char **argv
)
670 struct script_control ctl
= {
671 #if !HAVE_LIBUTIL || !HAVE_PTY_H
672 .line
= "/dev/ptyXX",
680 enum { FORCE_OPTION
= CHAR_MAX
+ 1 };
682 static const struct option longopts
[] = {
683 {"append", no_argument
, NULL
, 'a'},
684 {"command", required_argument
, NULL
, 'c'},
685 {"return", no_argument
, NULL
, 'e'},
686 {"flush", no_argument
, NULL
, 'f'},
687 {"force", no_argument
, NULL
, FORCE_OPTION
,},
688 {"quiet", no_argument
, NULL
, 'q'},
689 {"timing", optional_argument
, NULL
, 't'},
690 {"version", no_argument
, NULL
, 'V'},
691 {"help", no_argument
, NULL
, 'h'},
695 setlocale(LC_ALL
, "");
697 * script -t prints time delays as floating point numbers. The example
698 * program (scriptreplay) that we provide to handle this timing output
699 * is a perl script, and does not handle numbers in locale format (not
700 * even when "use locale;" is added). So, since these numbers are not
701 * for human consumption, it seems easiest to set LC_NUMERIC here.
703 setlocale(LC_NUMERIC
, "C");
704 bindtextdomain(PACKAGE
, LOCALEDIR
);
706 atexit(close_stdout
);
710 while ((ch
= getopt_long(argc
, argv
, "ac:efqt::Vh", longopts
, NULL
)) != -1)
716 ctl
.command
= optarg
;
736 printf(UTIL_LINUX_VERSION
);
743 errtryhelp(EXIT_FAILURE
);
751 ctl
.fname
= DEFAULT_TYPESCRIPT_FILENAME
;
755 ctl
.shell
= getenv("SHELL");
756 if (ctl
.shell
== NULL
)
757 ctl
.shell
= _PATH_BSHELL
;
761 printf(_("Script started, file is %s\n"), ctl
.fname
);
764 #ifdef HAVE_LIBUTEMPTER
765 utempter_add_record(ctl
.master
, NULL
);
767 /* setup signal handler */
768 sigemptyset(&ctl
.sigset
);
769 sigaddset(&ctl
.sigset
, SIGCHLD
);
770 sigaddset(&ctl
.sigset
, SIGWINCH
);
771 sigaddset(&ctl
.sigset
, SIGTERM
);
772 sigaddset(&ctl
.sigset
, SIGINT
);
773 sigaddset(&ctl
.sigset
, SIGQUIT
);
775 /* block signals used for signalfd() to prevent the signals being
776 * handled according to their default dispositions */
777 sigprocmask(SIG_BLOCK
, &ctl
.sigset
, &ctl
.sigorg
);
779 if ((ctl
.sigfd
= signalfd(-1, &ctl
.sigset
, SFD_CLOEXEC
)) < 0)
780 err(EXIT_FAILURE
, _("cannot set signal handler"));
782 DBG(SIGNAL
, ul_debug("signal fd=%d", ctl
.sigfd
));
789 warn(_("fork failed"));
795 default: /* parent */
800 /* should not happen, all used functions are non-return */