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
);
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 */
207 if (close_stream(ctl
->timingfp
) != 0)
208 err(EXIT_FAILURE
, "write failed: %s", ctl
->tname
);
209 if (ctl
->typescriptfp
)
210 if (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 strftime(buf
, sizeof buf
, "%c\n", localtime(&tvec
));
440 fprintf(ctl
->typescriptfp
, _("Script started on %s"), buf
);
441 gettime_monotonic(&ctl
->oldtime
);
447 DBG(POLL
, ul_debug("calling poll()"));
449 /* wait for input or signal */
450 ret
= poll(pfd
, ARRAY_SIZE(pfd
) - ignore_stdin
, ctl
->poll_timeout
);
452 DBG(POLL
, ul_debug("poll() rc=%d", ret
));
457 warn(_("poll failed"));
461 DBG(POLL
, ul_debug("setting die=1"));
466 for (i
= 0; i
< ARRAY_SIZE(pfd
) - ignore_stdin
; i
++) {
467 if (pfd
[i
].revents
== 0)
470 DBG(POLL
, ul_debug(" active pfd[%s].fd=%d %s %s %s",
471 i
== POLLFD_STDIN
? "stdin" :
472 i
== POLLFD_MASTER
? "master" :
473 i
== POLLFD_SIGNAL
? "signal" : "???",
475 pfd
[i
].revents
& POLLIN
? "POLLIN" : "",
476 pfd
[i
].revents
& POLLHUP
? "POLLHUP" : "",
477 pfd
[i
].revents
& POLLERR
? "POLLERR" : ""));
482 if (pfd
[i
].revents
& POLLIN
)
483 handle_io(ctl
, pfd
[i
].fd
, &eof
);
484 /* EOF maybe detected by two ways:
485 * A) poll() return POLLHUP event after close()
486 * B) read() returns 0 (no data) */
487 if ((pfd
[i
].revents
& POLLHUP
) || eof
) {
488 DBG(POLL
, ul_debug(" ignore FD"));
490 /* according to man poll() set FD to -1 can't be used to ignore
491 * STDIN, so let's remove the FD from pool at all */
492 if (i
== POLLFD_STDIN
) {
494 write_eof_to_shell(ctl
);
495 DBG(POLL
, ul_debug(" ignore STDIN"));
500 handle_signal(ctl
, pfd
[i
].fd
);
506 DBG(POLL
, ul_debug("poll() done"));
509 wait_for_child(ctl
, 1);
510 if (!ctl
->quiet
&& ctl
->typescriptfp
) {
511 tvec
= script_time((time_t *)NULL
);
512 strftime(buf
, sizeof buf
, "%c\n", localtime(&tvec
));
513 fprintf(ctl
->typescriptfp
, _("\nScript done on %s"), buf
);
518 static void getslave(struct script_control
*ctl
)
521 ctl
->line
[strlen("/dev/")] = 't';
522 ctl
->slave
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
523 if (ctl
->slave
< 0) {
524 warn(_("cannot open %s"), ctl
->line
);
528 tcsetattr(ctl
->slave
, TCSANOW
, &ctl
->attrs
);
529 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
533 ioctl(ctl
->slave
, TIOCSCTTY
, 0);
536 /* don't use DBG() stuff here otherwise it will be in the typescript file */
537 static void __attribute__((__noreturn__
)) do_shell(struct script_control
*ctl
)
543 /* close things irrelevant for this process */
547 dup2(ctl
->slave
, STDIN_FILENO
);
548 dup2(ctl
->slave
, STDOUT_FILENO
);
549 dup2(ctl
->slave
, STDERR_FILENO
);
554 shname
= strrchr(ctl
->shell
, '/');
560 sigprocmask(SIG_SETMASK
, &ctl
->sigorg
, NULL
);
563 * When invoked from within /etc/csh.login, script spawns a csh shell
564 * that spawns programs that cannot be killed with a SIGTERM. This is
565 * because csh has a documented behavior wherein it disables all
566 * signals when processing the /etc/csh.* files.
568 * Let's restore the default behavior.
570 signal(SIGTERM
, SIG_DFL
);
572 if (access(ctl
->shell
, X_OK
) == 0) {
574 execl(ctl
->shell
, shname
, "-c", ctl
->command
, NULL
);
576 execl(ctl
->shell
, shname
, "-i", NULL
);
579 execlp(shname
, "-c", ctl
->command
, NULL
);
581 execlp(shname
, "-i", NULL
);
583 warn(_("failed to execute %s"), ctl
->shell
);
587 static void fixtty(struct script_control
*ctl
)
596 rtt
.c_lflag
&= ~ECHO
;
597 tcsetattr(STDIN_FILENO
, TCSANOW
, &rtt
);
600 static void getmaster(struct script_control
*ctl
)
602 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
605 ctl
->isterm
= isatty(STDIN_FILENO
);
608 if (tcgetattr(STDIN_FILENO
, &ctl
->attrs
) != 0)
609 err(EXIT_FAILURE
, _("failed to get terminal attributes"));
610 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
611 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, &ctl
->attrs
, &ctl
->win
);
613 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, NULL
, NULL
);
616 warn(_("openpty failed"));
620 char *pty
, *bank
, *cp
;
622 ctl
->isterm
= isatty(STDIN_FILENO
);
624 pty
= &ctl
->line
[strlen("/dev/ptyp")];
625 for (bank
= "pqrs"; *bank
; bank
++) {
626 ctl
->line
[strlen("/dev/pty")] = *bank
;
628 if (access(ctl
->line
, F_OK
) != 0)
630 for (cp
= "0123456789abcdef"; *cp
; cp
++) {
632 ctl
->master
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
633 if (ctl
->master
>= 0) {
634 char *tp
= &ctl
->line
[strlen("/dev/")];
637 /* verify slave side is usable */
639 ok
= access(ctl
->line
, R_OK
| W_OK
) == 0;
643 tcgetattr(STDIN_FILENO
, &ctl
->attrs
);
644 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
654 warn(_("out of pty's"));
656 #endif /* not HAVE_LIBUTIL */
658 DBG(IO
, ul_debug("master fd: %d", ctl
->master
));
661 int main(int argc
, char **argv
)
663 struct script_control ctl
= {
664 #if !HAVE_LIBUTIL || !HAVE_PTY_H
665 .line
= "/dev/ptyXX",
673 enum { FORCE_OPTION
= CHAR_MAX
+ 1 };
675 static const struct option longopts
[] = {
676 {"append", no_argument
, NULL
, 'a'},
677 {"command", required_argument
, NULL
, 'c'},
678 {"return", no_argument
, NULL
, 'e'},
679 {"flush", no_argument
, NULL
, 'f'},
680 {"force", no_argument
, NULL
, FORCE_OPTION
,},
681 {"quiet", no_argument
, NULL
, 'q'},
682 {"timing", optional_argument
, NULL
, 't'},
683 {"version", no_argument
, NULL
, 'V'},
684 {"help", no_argument
, NULL
, 'h'},
688 setlocale(LC_ALL
, "");
690 * script -t prints time delays as floating point numbers. The example
691 * program (scriptreplay) that we provide to handle this timing output
692 * is a perl script, and does not handle numbers in locale format (not
693 * even when "use locale;" is added). So, since these numbers are not
694 * for human consumption, it seems easiest to set LC_NUMERIC here.
696 setlocale(LC_NUMERIC
, "C");
697 bindtextdomain(PACKAGE
, LOCALEDIR
);
699 atexit(close_stdout
);
703 while ((ch
= getopt_long(argc
, argv
, "ac:efqt::Vh", longopts
, NULL
)) != -1)
709 ctl
.command
= optarg
;
729 printf(UTIL_LINUX_VERSION
);
744 ctl
.fname
= DEFAULT_TYPESCRIPT_FILENAME
;
748 ctl
.shell
= getenv("SHELL");
749 if (ctl
.shell
== NULL
)
750 ctl
.shell
= _PATH_BSHELL
;
754 printf(_("Script started, file is %s\n"), ctl
.fname
);
757 #ifdef HAVE_LIBUTEMPTER
758 utempter_add_record(ctl
.master
, NULL
);
760 /* setup signal handler */
761 sigemptyset(&ctl
.sigset
);
762 sigaddset(&ctl
.sigset
, SIGCHLD
);
763 sigaddset(&ctl
.sigset
, SIGWINCH
);
764 sigaddset(&ctl
.sigset
, SIGTERM
);
765 sigaddset(&ctl
.sigset
, SIGINT
);
766 sigaddset(&ctl
.sigset
, SIGQUIT
);
768 /* block signals used for signalfd() to prevent the signals being
769 * handled according to their default dispositions */
770 sigprocmask(SIG_BLOCK
, &ctl
.sigset
, &ctl
.sigorg
);
772 if ((ctl
.sigfd
= signalfd(-1, &ctl
.sigset
, SFD_CLOEXEC
)) < 0)
773 err(EXIT_FAILURE
, _("cannot set signal handler"));
775 DBG(SIGNAL
, ul_debug("signal fd=%d", ctl
.sigfd
));
782 warn(_("fork failed"));
788 default: /* parent */
793 /* should not happen, all used functions are non-return */