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"
76 UL_DEBUG_DEFINE_MASK(script
);
77 UL_DEBUG_DEFINE_MASKNAMES(script
) = UL_DEBUG_EMPTY_MASKNAMES
;
79 #define SCRIPT_DEBUG_INIT (1 << 1)
80 #define SCRIPT_DEBUG_POLL (1 << 2)
81 #define SCRIPT_DEBUG_SIGNAL (1 << 3)
82 #define SCRIPT_DEBUG_IO (1 << 4)
83 #define SCRIPT_DEBUG_MISC (1 << 5)
84 #define SCRIPT_DEBUG_ALL 0xFFFF
86 #define DBG(m, x) __UL_DBG(script, SCRIPT_DEBUG_, m, x)
87 #define ON_DBG(m, x) __UL_DBG_CALL(script, SCRIPT_DEBUG_, m, x)
89 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
93 #ifdef HAVE_LIBUTEMPTER
94 # include <utempter.h>
97 #define DEFAULT_TYPESCRIPT_FILENAME "typescript"
99 struct script_control
{
100 char *shell
; /* shell to be executed */
101 char *command
; /* command to be executed */
102 char *fname
; /* output file path */
103 FILE *typescriptfp
; /* output file pointer */
104 char *tname
; /* timing file path */
105 FILE *timingfp
; /* timing file pointer */
106 struct timeval oldtime
; /* previous write or command start time */
107 int master
; /* pseudoterminal master file descriptor */
108 int slave
; /* pseudoterminal slave file descriptor */
109 int poll_timeout
; /* poll() timeout, used in end of execution */
110 pid_t child
; /* child pid */
111 int childstatus
; /* child process exit value */
112 struct termios attrs
; /* slave terminal runtime attributes */
113 struct winsize win
; /* terminal window size */
114 #if !HAVE_LIBUTIL || !HAVE_PTY_H
115 char line
*; /* terminal line */
118 append
:1, /* append output */
119 rc_wanted
:1, /* return child exit value */
120 flush
:1, /* flush after each write */
121 quiet
:1, /* suppress most output */
122 timing
:1, /* include timing file */
123 force
:1, /* write output to links */
124 isterm
:1, /* is child process running as terminal */
125 die
:1; /* terminate program */
127 sigset_t sigset
; /* catch SIGCHLD and SIGWINCH with signalfd() */
128 sigset_t sigorg
; /* original signal mask */
129 int sigfd
; /* file descriptor for signalfd() */
132 static void script_init_debug(void)
134 __UL_INIT_DEBUG(script
, SCRIPT_DEBUG_
, 0, SCRIPT_DEBUG
);
138 * For tests we want to be able to control time output
141 static inline time_t script_time(time_t *t
)
143 const char *str
= getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
146 if (!str
|| sscanf(str
, "%"SCNi64
, &sec
) != 1)
152 #else /* !TEST_SCRIPT */
153 # define script_time(x) time(x)
156 static void __attribute__((__noreturn__
)) usage(FILE *out
)
158 fputs(USAGE_HEADER
, out
);
159 fprintf(out
, _(" %s [options] [file]\n"), program_invocation_short_name
);
161 fputs(USAGE_SEPARATOR
, out
);
162 fputs(_("Make a typescript of a terminal session.\n"), out
);
164 fputs(USAGE_OPTIONS
, out
);
165 fputs(_(" -a, --append append the output\n"
166 " -c, --command <command> run command rather than interactive shell\n"
167 " -e, --return return exit code of the child process\n"
168 " -f, --flush run flush after each write\n"
169 " --force use output file even when it is a link\n"
170 " -q, --quiet be quiet\n"
171 " -t, --timing[=<file>] output timing data to stderr (or to FILE)\n"
172 " -V, --version output version information and exit\n"
173 " -h, --help display this help and exit\n\n"), out
);
175 fprintf(out
, USAGE_MAN_TAIL("script(1)"));
176 exit(out
== stderr
? EXIT_FAILURE
: EXIT_SUCCESS
);
179 static void die_if_link(const struct script_control
*ctl
)
185 if (lstat(ctl
->fname
, &s
) == 0 && (S_ISLNK(s
.st_mode
) || s
.st_nlink
> 1))
187 _("output file `%s' is a link\n"
188 "Use --force if you really want to use it.\n"
189 "Program not started."), ctl
->fname
);
192 static void __attribute__((__noreturn__
)) done(struct script_control
*ctl
)
194 DBG(MISC
, ul_debug("done!"));
197 tcsetattr(STDIN_FILENO
, TCSADRAIN
, &ctl
->attrs
);
198 if (!ctl
->quiet
&& ctl
->typescriptfp
)
199 printf(_("Script done, file is %s\n"), ctl
->fname
);
200 #ifdef HAVE_LIBUTEMPTER
201 if (ctl
->master
>= 0)
202 utempter_remove_record(ctl
->master
);
204 kill(ctl
->child
, SIGTERM
); /* make sure we don't create orphans */
206 if (ctl
->timingfp
&& close_stream(ctl
->timingfp
) != 0)
207 err(EXIT_FAILURE
, "write failed: %s", ctl
->tname
);
208 if (ctl
->typescriptfp
&& close_stream(ctl
->typescriptfp
) != 0)
209 err(EXIT_FAILURE
, "write failed: %s", ctl
->fname
);
211 if (ctl
->rc_wanted
) {
212 if (WIFSIGNALED(ctl
->childstatus
))
213 exit(WTERMSIG(ctl
->childstatus
) + 0x80);
215 exit(WEXITSTATUS(ctl
->childstatus
));
220 static void __attribute__((__noreturn__
)) fail(struct script_control
*ctl
)
222 DBG(MISC
, ul_debug("fail!"));
227 static void wait_for_child(struct script_control
*ctl
, int wait
)
231 int options
= wait
? 0 : WNOHANG
;
233 DBG(MISC
, ul_debug("waiting for child"));
235 while ((pid
= wait3(&status
, options
, NULL
)) > 0)
236 if (pid
== ctl
->child
)
237 ctl
->childstatus
= status
;
240 static void write_output(struct script_control
*ctl
, char *obuf
,
243 DBG(IO
, ul_debug(" writing output"));
245 if (ctl
->timing
&& ctl
->timingfp
) {
246 struct timeval now
, delta
;
248 DBG(IO
, ul_debug(" writing timing info"));
250 gettime_monotonic(&now
);
251 timersub(&now
, &ctl
->oldtime
, &delta
);
252 fprintf(ctl
->timingfp
, "%ld.%06ld %zd\n",
253 (long)delta
.tv_sec
, (long)delta
.tv_usec
, bytes
);
255 fflush(ctl
->timingfp
);
259 DBG(IO
, ul_debug(" writing to script file"));
261 if (fwrite_all(obuf
, 1, bytes
, ctl
->typescriptfp
)) {
262 warn(_("cannot write script file"));
266 fflush(ctl
->typescriptfp
);
268 DBG(IO
, ul_debug(" writing to output"));
270 if (write_all(STDOUT_FILENO
, obuf
, bytes
)) {
271 DBG(IO
, ul_debug(" writing output *failed*"));
272 warn(_("write failed"));
276 DBG(IO
, ul_debug(" writing output *done*"));
279 static int write_to_shell(struct script_control
*ctl
,
280 char *buf
, size_t bufsz
)
282 return write_all(ctl
->master
, buf
, bufsz
);
286 * The script(1) is usually faster than shell, so it's a good idea to wait until
287 * the previous message has been already read by shell from slave before we
288 * write to master. This is necessary especially for EOF situation when we can
289 * send EOF to master before shell is fully initialized, to workaround this
290 * problem we wait until slave is empty. For example:
292 * echo "date" | script
294 * Unfortunately, the child (usually shell) can ignore stdin at all, so we
295 * don't wait forever to avoid dead locks...
297 * Note that script is primarily designed for interactive sessions as it
298 * maintains master+slave tty stuff within the session. Use pipe to write to
299 * script(1) and assume non-interactive (tee-like) behavior is NOT well
302 static void write_eof_to_shell(struct script_control
*ctl
)
304 unsigned int tries
= 0;
305 struct pollfd fds
[] = {
306 { .fd
= ctl
->slave
, .events
= POLLIN
}
310 DBG(IO
, ul_debug(" waiting for empty slave"));
311 while (poll(fds
, 1, 10) == 1 && tries
< 8) {
312 DBG(IO
, ul_debug(" slave is not empty"));
317 DBG(IO
, ul_debug(" slave is empty now"));
319 DBG(IO
, ul_debug(" sending EOF to master"));
320 write_to_shell(ctl
, &c
, sizeof(char));
323 static void handle_io(struct script_control
*ctl
, int fd
, int *eof
)
328 DBG(IO
, ul_debug("%d FD active", fd
));
331 /* read from active FD */
332 bytes
= read(fd
, buf
, sizeof(buf
));
334 if (errno
== EAGAIN
|| errno
== EINTR
)
344 /* from stdin (user) to command */
345 if (fd
== STDIN_FILENO
) {
346 DBG(IO
, ul_debug(" stdin --> master %zd bytes", bytes
));
348 if (write_to_shell(ctl
, buf
, bytes
)) {
349 warn(_("write failed"));
352 /* without sync write_output() will write both input &
353 * shell output that looks like double echoing */
354 fdatasync(ctl
->master
);
356 /* from command (master) to stdout */
357 } else if (fd
== ctl
->master
) {
358 DBG(IO
, ul_debug(" master --> stdout %zd bytes", bytes
));
359 write_output(ctl
, buf
, bytes
);
363 static void handle_signal(struct script_control
*ctl
, int fd
)
365 struct signalfd_siginfo info
;
368 DBG(SIGNAL
, ul_debug("signal FD %d active", fd
));
370 bytes
= read(fd
, &info
, sizeof(info
));
371 if (bytes
!= sizeof(info
)) {
372 if (bytes
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
377 switch (info
.ssi_signo
) {
379 DBG(SIGNAL
, ul_debug(" get signal SIGCHLD"));
380 wait_for_child(ctl
, 0);
381 ctl
->poll_timeout
= 10;
384 DBG(SIGNAL
, ul_debug(" get signal SIGWINCH"));
386 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
387 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
395 DBG(SIGNAL
, ul_debug(" get signal SIG{TERM,INT,QUIT}"));
396 fprintf(stderr
, _("\nSession terminated.\n"));
397 /* Child termination is going to generate SIGCHILD (see above) */
398 kill(ctl
->child
, SIGTERM
);
405 static void do_io(struct script_control
*ctl
)
407 int ret
, ignore_stdin
= 0, eof
= 0;
408 time_t tvec
= script_time((time_t *)NULL
);
413 POLLFD_STDIN
/* optional; keep it last, see ignore_stdin */
416 struct pollfd pfd
[] = {
417 [POLLFD_SIGNAL
] = { .fd
= ctl
->sigfd
, .events
= POLLIN
| POLLERR
| POLLHUP
},
418 [POLLFD_MASTER
] = { .fd
= ctl
->master
, .events
= POLLIN
| POLLERR
| POLLHUP
},
419 [POLLFD_STDIN
] = { .fd
= STDIN_FILENO
, .events
= POLLIN
| POLLERR
| POLLHUP
}
423 if ((ctl
->typescriptfp
=
424 fopen(ctl
->fname
, ctl
->append
? "a" UL_CLOEXECSTR
: "w" UL_CLOEXECSTR
)) == NULL
) {
425 warn(_("cannot open %s"), ctl
->fname
);
430 if (!(ctl
->timingfp
= fopen("/dev/stderr", "w" UL_CLOEXECSTR
)))
431 err(EXIT_FAILURE
, _("cannot open %s"), "/dev/stderr");
432 } else if (!(ctl
->timingfp
= fopen(ctl
->tname
, "w" UL_CLOEXECSTR
)))
433 err(EXIT_FAILURE
, _("cannot open %s"), ctl
->tname
);
437 strftime(buf
, sizeof buf
, "%c\n", localtime(&tvec
));
438 fprintf(ctl
->typescriptfp
, _("Script started on %s"), buf
);
439 gettime_monotonic(&ctl
->oldtime
);
445 DBG(POLL
, ul_debug("calling poll()"));
447 /* wait for input or signal */
448 ret
= poll(pfd
, ARRAY_SIZE(pfd
) - ignore_stdin
, ctl
->poll_timeout
);
450 DBG(POLL
, ul_debug("poll() rc=%d", ret
));
455 warn(_("poll failed"));
459 DBG(POLL
, ul_debug("setting die=1"));
464 for (i
= 0; i
< ARRAY_SIZE(pfd
) - ignore_stdin
; i
++) {
465 if (pfd
[i
].revents
== 0)
468 DBG(POLL
, ul_debug(" active pfd[%s].fd=%d %s %s %s",
469 i
== POLLFD_STDIN
? "stdin" :
470 i
== POLLFD_MASTER
? "master" :
471 i
== POLLFD_SIGNAL
? "signal" : "???",
473 pfd
[i
].revents
& POLLIN
? "POLLIN" : "",
474 pfd
[i
].revents
& POLLHUP
? "POLLHUP" : "",
475 pfd
[i
].revents
& POLLERR
? "POLLERR" : ""));
480 if (pfd
[i
].revents
& POLLIN
)
481 handle_io(ctl
, pfd
[i
].fd
, &eof
);
482 /* EOF maybe detected by two ways:
483 * A) poll() return POLLHUP event after close()
484 * B) read() returns 0 (no data) */
485 if ((pfd
[i
].revents
& POLLHUP
) || eof
) {
486 DBG(POLL
, ul_debug(" ignore FD"));
488 /* according to man poll() set FD to -1 can't be used to ignore
489 * STDIN, so let's remove the FD from pool at all */
490 if (i
== POLLFD_STDIN
) {
492 write_eof_to_shell(ctl
);
493 DBG(POLL
, ul_debug(" ignore STDIN"));
498 handle_signal(ctl
, pfd
[i
].fd
);
504 DBG(POLL
, ul_debug("poll() done"));
507 wait_for_child(ctl
, 1);
508 if (!ctl
->quiet
&& ctl
->typescriptfp
) {
509 tvec
= script_time((time_t *)NULL
);
510 strftime(buf
, sizeof buf
, "%c\n", localtime(&tvec
));
511 fprintf(ctl
->typescriptfp
, _("\nScript done on %s"), buf
);
516 static void getslave(struct script_control
*ctl
)
519 ctl
->line
[strlen("/dev/")] = 't';
520 ctl
->slave
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
521 if (ctl
->slave
< 0) {
522 warn(_("cannot open %s"), ctl
->line
);
526 tcsetattr(ctl
->slave
, TCSANOW
, &ctl
->attrs
);
527 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
531 ioctl(ctl
->slave
, TIOCSCTTY
, 0);
534 /* don't use DBG() stuff here otherwise it will be in the typescript file */
535 static void __attribute__((__noreturn__
)) do_shell(struct script_control
*ctl
)
541 /* close things irrelevant for this process */
545 dup2(ctl
->slave
, STDIN_FILENO
);
546 dup2(ctl
->slave
, STDOUT_FILENO
);
547 dup2(ctl
->slave
, STDERR_FILENO
);
552 shname
= strrchr(ctl
->shell
, '/');
558 sigprocmask(SIG_SETMASK
, &ctl
->sigorg
, NULL
);
561 * When invoked from within /etc/csh.login, script spawns a csh shell
562 * that spawns programs that cannot be killed with a SIGTERM. This is
563 * because csh has a documented behavior wherein it disables all
564 * signals when processing the /etc/csh.* files.
566 * Let's restore the default behavior.
568 signal(SIGTERM
, SIG_DFL
);
570 if (access(ctl
->shell
, X_OK
) == 0) {
572 execl(ctl
->shell
, shname
, "-c", ctl
->command
, NULL
);
574 execl(ctl
->shell
, shname
, "-i", NULL
);
577 execlp(shname
, "-c", ctl
->command
, NULL
);
579 execlp(shname
, "-i", NULL
);
581 warn(_("failed to execute %s"), ctl
->shell
);
585 static void fixtty(struct script_control
*ctl
)
594 rtt
.c_lflag
&= ~ECHO
;
595 tcsetattr(STDIN_FILENO
, TCSANOW
, &rtt
);
598 static void getmaster(struct script_control
*ctl
)
600 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
603 ctl
->isterm
= isatty(STDIN_FILENO
);
606 if (tcgetattr(STDIN_FILENO
, &ctl
->attrs
) != 0)
607 err(EXIT_FAILURE
, _("failed to get terminal attributes"));
608 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
609 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, &ctl
->attrs
, &ctl
->win
);
611 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, NULL
, NULL
);
614 warn(_("openpty failed"));
618 char *pty
, *bank
, *cp
;
620 ctl
->isterm
= isatty(STDIN_FILENO
);
622 pty
= &ctl
->line
[strlen("/dev/ptyp")];
623 for (bank
= "pqrs"; *bank
; bank
++) {
624 ctl
->line
[strlen("/dev/pty")] = *bank
;
626 if (access(ctl
->line
, F_OK
) != 0)
628 for (cp
= "0123456789abcdef"; *cp
; cp
++) {
630 ctl
->master
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
631 if (ctl
->master
>= 0) {
632 char *tp
= &ctl
->line
[strlen("/dev/")];
635 /* verify slave side is usable */
637 ok
= access(ctl
->line
, R_OK
| W_OK
) == 0;
641 tcgetattr(STDIN_FILENO
, &ctl
->attrs
);
642 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
652 warn(_("out of pty's"));
654 #endif /* not HAVE_LIBUTIL */
656 DBG(IO
, ul_debug("master fd: %d", ctl
->master
));
659 int main(int argc
, char **argv
)
661 struct script_control ctl
= {
662 #if !HAVE_LIBUTIL || !HAVE_PTY_H
663 .line
= "/dev/ptyXX",
671 enum { FORCE_OPTION
= CHAR_MAX
+ 1 };
673 static const struct option longopts
[] = {
674 {"append", no_argument
, NULL
, 'a'},
675 {"command", required_argument
, NULL
, 'c'},
676 {"return", no_argument
, NULL
, 'e'},
677 {"flush", no_argument
, NULL
, 'f'},
678 {"force", no_argument
, NULL
, FORCE_OPTION
,},
679 {"quiet", no_argument
, NULL
, 'q'},
680 {"timing", optional_argument
, NULL
, 't'},
681 {"version", no_argument
, NULL
, 'V'},
682 {"help", no_argument
, NULL
, 'h'},
686 setlocale(LC_ALL
, "");
688 * script -t prints time delays as floating point numbers. The example
689 * program (scriptreplay) that we provide to handle this timing output
690 * is a perl script, and does not handle numbers in locale format (not
691 * even when "use locale;" is added). So, since these numbers are not
692 * for human consumption, it seems easiest to set LC_NUMERIC here.
694 setlocale(LC_NUMERIC
, "C");
695 bindtextdomain(PACKAGE
, LOCALEDIR
);
697 atexit(close_stdout
);
701 while ((ch
= getopt_long(argc
, argv
, "ac:efqt::Vh", longopts
, NULL
)) != -1)
707 ctl
.command
= optarg
;
727 printf(UTIL_LINUX_VERSION
);
742 ctl
.fname
= DEFAULT_TYPESCRIPT_FILENAME
;
746 ctl
.shell
= getenv("SHELL");
747 if (ctl
.shell
== NULL
)
748 ctl
.shell
= _PATH_BSHELL
;
752 printf(_("Script started, file is %s\n"), ctl
.fname
);
755 #ifdef HAVE_LIBUTEMPTER
756 utempter_add_record(ctl
.master
, NULL
);
758 /* setup signal handler */
759 sigemptyset(&ctl
.sigset
);
760 sigaddset(&ctl
.sigset
, SIGCHLD
);
761 sigaddset(&ctl
.sigset
, SIGWINCH
);
762 sigaddset(&ctl
.sigset
, SIGTERM
);
763 sigaddset(&ctl
.sigset
, SIGINT
);
764 sigaddset(&ctl
.sigset
, SIGQUIT
);
766 /* block signals used for signalfd() to prevent the signals being
767 * handled according to their default dispositions */
768 sigprocmask(SIG_BLOCK
, &ctl
.sigset
, &ctl
.sigorg
);
770 if ((ctl
.sigfd
= signalfd(-1, &ctl
.sigset
, SFD_CLOEXEC
)) < 0)
771 err(EXIT_FAILURE
, _("cannot set signal handler"));
773 DBG(SIGNAL
, ul_debug("signal fd=%d", ctl
.sigfd
));
780 warn(_("fork failed"));
786 default: /* parent */
791 /* should not happen, all used functions are non-return */