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"
80 static UL_DEBUG_DEFINE_MASK(script
);
81 UL_DEBUG_DEFINE_MASKNAMES(script
) = UL_DEBUG_EMPTY_MASKNAMES
;
83 #define SCRIPT_DEBUG_INIT (1 << 1)
84 #define SCRIPT_DEBUG_POLL (1 << 2)
85 #define SCRIPT_DEBUG_SIGNAL (1 << 3)
86 #define SCRIPT_DEBUG_IO (1 << 4)
87 #define SCRIPT_DEBUG_MISC (1 << 5)
88 #define SCRIPT_DEBUG_ALL 0xFFFF
90 #define DBG(m, x) __UL_DBG(script, SCRIPT_DEBUG_, m, x)
91 #define ON_DBG(m, x) __UL_DBG_CALL(script, SCRIPT_DEBUG_, m, x)
93 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
97 #ifdef HAVE_LIBUTEMPTER
98 # include <utempter.h>
101 #define DEFAULT_TYPESCRIPT_FILENAME "typescript"
104 * Script is driven by stream (stdout/stdin) activity. It's possible to
105 * associate arbitrary number of log files with the stream. We have two basic
106 * types of log files: "timing file" (simple or multistream) and "data file"
109 * The same log file maybe be shared between both streams. For exmaple
110 * multi-stream timing file is possible to use for stdin as well as for stdout.
113 SCRIPT_FMT_RAW
= 1, /* raw slave/master data */
114 SCRIPT_FMT_TIMING_SIMPLE
, /* (classic) in format "<delta> <offset>" */
115 SCRIPT_FMT_TIMING_MULTI
, /* (advanced) multiple streams in format "<type> <delta> <offset|etc> */
119 FILE *fp
; /* file pointer (handler) */
120 int format
; /* SCRIPT_FMT_* */
121 char *filename
; /* on command line specified name */
122 struct timeval oldtime
; /* previous entry log time (SCRIPT_FMT_TIMING_* only) */
124 unsigned int initialized
: 1;
127 struct script_stream
{
128 struct script_log
**logs
; /* logs where to write data from stream */
129 size_t nlogs
; /* number of logs */
130 char ident
; /* stream identifier */
133 struct script_control
{
134 char *shell
; /* shell to be executed */
135 char *command
; /* command to be executed */
136 uint64_t outsz
; /* current output files size */
137 uint64_t maxsz
; /* maximum output files size */
139 int master
; /* pseudoterminal master file descriptor */
140 int slave
; /* pseudoterminal slave file descriptor */
142 struct script_stream out
; /* output */
143 struct script_stream in
; /* input */
145 int poll_timeout
; /* poll() timeout, used in end of execution */
146 pid_t child
; /* child pid */
147 int childstatus
; /* child process exit value */
148 struct termios attrs
; /* slave terminal runtime attributes */
149 struct winsize win
; /* terminal window size */
150 #if !HAVE_LIBUTIL || !HAVE_PTY_H
151 char *line
; /* terminal line */
154 append
:1, /* append output */
155 rc_wanted
:1, /* return child exit value */
156 flush
:1, /* flush after each write */
157 quiet
:1, /* suppress most output */
158 force
:1, /* write output to links */
159 isterm
:1, /* is child process running as terminal */
160 die
:1; /* terminate program */
162 sigset_t sigset
; /* catch SIGCHLD and SIGWINCH with signalfd() */
163 sigset_t sigorg
; /* original signal mask */
164 int sigfd
; /* file descriptor for signalfd() */
167 static void restore_tty(struct script_control
*ctl
, int mode
);
168 static void __attribute__((__noreturn__
)) fail(struct script_control
*ctl
);
170 static void script_init_debug(void)
172 __UL_INIT_DEBUG_FROM_ENV(script
, SCRIPT_DEBUG_
, 0, SCRIPT_DEBUG
);
176 * For tests we want to be able to control time output
179 static inline time_t script_time(time_t *t
)
181 const char *str
= getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
184 if (!str
|| sscanf(str
, "%"SCNi64
, &sec
) != 1)
190 #else /* !TEST_SCRIPT */
191 # define script_time(x) time(x)
194 static void __attribute__((__noreturn__
)) usage(void)
197 fputs(USAGE_HEADER
, out
);
198 fprintf(out
, _(" %s [options] [file]\n"), program_invocation_short_name
);
200 fputs(USAGE_SEPARATOR
, out
);
201 fputs(_("Make a typescript of a terminal session.\n"), out
);
203 fputs(USAGE_OPTIONS
, out
);
204 fputs(_(" -I, --log-in <file> log stdin to file\n"), out
);
205 fputs(_(" -O, --log-out <file> log stdout to file (default)\n"), out
);
206 fputs(_(" -B, --log-io <file> log stdin and stdout to file\n"), out
);
207 fputs(USAGE_SEPARATOR
, out
);
209 fputs(_(" -T, --log-timing <file> log timing information to file\n"), out
);
210 fputs(_(" -t[<file>], --timing[=<file>] deprecated alias to -T (default file is stderr)\n"), out
);
211 fputs(_(" -m, --logging-format <name> force to 'classic' or 'advanced' format\n"), out
);
212 fputs(USAGE_SEPARATOR
, out
);
214 fputs(_(" -a, --append append to the log file\n"), out
);
215 fputs(_(" -c, --command <command> run command rather than interactive shell\n"), out
);
216 fputs(_(" -e, --return return exit code of the child process\n"), out
);
217 fputs(_(" -f, --flush run flush after each write\n"), out
);
218 fputs(_(" --force use output file even when it is a link\n"), out
);
219 fputs(_(" -o, --output-limit <size> terminate if output files exceed size\n"), out
);
220 fputs(_(" -q, --quiet be quiet\n"), out
);
222 fputs(USAGE_SEPARATOR
, out
);
223 printf(USAGE_HELP_OPTIONS(31));
224 printf(USAGE_MAN_TAIL("script(1)"));
229 static struct script_log
*get_log_by_name(struct script_stream
*stream
,
234 for (i
= 0; i
< stream
->nlogs
; i
++) {
235 struct script_log
*log
= stream
->logs
[i
];
236 if (strcmp(log
->filename
, name
) == 0)
242 static struct script_log
*log_associate(struct script_control
*ctl
,
243 struct script_stream
*stream
,
244 const char *filename
, int format
)
246 struct script_log
*log
;
248 DBG(MISC
, ul_debug("associate %s with stream", filename
));
254 log
= get_log_by_name(stream
, filename
);
256 return log
; /* already defined */
258 log
= get_log_by_name(stream
== &ctl
->out
? &ctl
->in
: &ctl
->out
, filename
);
260 /* create a new log */
261 log
= xcalloc(1, sizeof(*log
));
262 log
->filename
= xstrdup(filename
);
263 log
->format
= format
;
266 /* add log to the stream */
267 stream
->logs
= xrealloc(stream
->logs
,
268 (stream
->nlogs
+ 1) * sizeof(log
));
269 stream
->logs
[stream
->nlogs
] = log
;
275 static void log_close(struct script_control
*ctl
__attribute__((unused
)),
276 struct script_log
*log
,
280 if (!log
->initialized
)
283 DBG(MISC
, ul_debug("closing %s", log
->filename
));
285 switch (log
->format
) {
288 char buf
[FORMAT_TIMESTAMP_MAX
];
289 time_t tvec
= script_time((time_t *)NULL
);
291 strtime_iso(&tvec
, ISO_TIMESTAMP
, buf
, sizeof(buf
));
293 fprintf(log
->fp
, _("\nScript done on %s [<%s>]\n"), buf
, msg
);
295 fprintf(log
->fp
, _("\nScript done on %s [COMMAND_EXIT_CODE=\"%d\"]\n"), buf
, status
);
298 case SCRIPT_FMT_TIMING_SIMPLE
:
302 if (close_stream(log
->fp
) != 0)
303 err(EXIT_FAILURE
, "write failed: %s", log
->filename
);
306 log
->initialized
= 0;
309 static void log_start(struct script_control
*ctl
,
310 struct script_log
*log
)
312 if (log
->initialized
)
315 DBG(MISC
, ul_debug("opening %s", log
->filename
));
317 assert(log
->fp
== NULL
);
320 log
->fp
= fopen(log
->filename
,
321 ctl
->append
&& log
->format
== SCRIPT_FMT_RAW
?
325 restore_tty(ctl
, TCSANOW
);
326 warn(_("cannot open %s"), log
->filename
);
330 /* write header, etc. */
331 switch (log
->format
) {
334 char buf
[FORMAT_TIMESTAMP_MAX
];
335 time_t tvec
= script_time((time_t *)NULL
);
337 strtime_iso(&tvec
, ISO_TIMESTAMP
, buf
, sizeof(buf
));
338 fprintf(log
->fp
, _("Script started on %s ["), buf
);
341 int cols
= 0, lines
= 0;
342 const char *tty
= NULL
, *term
= NULL
;
344 get_terminal_dimension(&cols
, &lines
);
345 get_terminal_name(&tty
, NULL
, NULL
);
346 get_terminal_type(&term
);
349 fprintf(log
->fp
, "TERM=\"%s\" ", term
);
351 fprintf(log
->fp
, "TTY=\"%s\" ", tty
);
353 fprintf(log
->fp
, "COLUMNS=\"%d\" LINES=\"%d\"", cols
, lines
);
355 fprintf(log
->fp
, _("<not executed on terminal>"));
357 fputs("]\n", log
->fp
);
360 case SCRIPT_FMT_TIMING_SIMPLE
:
361 case SCRIPT_FMT_TIMING_MULTI
:
362 gettime_monotonic(&log
->oldtime
);
366 log
->initialized
= 1;
369 static size_t log_write(struct script_control
*ctl
,
370 struct script_stream
*stream
,
371 struct script_log
*log
,
372 char *obuf
, size_t bytes
)
377 DBG(IO
, ul_debug(" writining %s", log
->filename
));
379 switch (log
->format
) {
381 if (fwrite_all(obuf
, 1, bytes
, log
->fp
)) {
382 warn(_("cannot write %s"), log
->filename
);
386 case SCRIPT_FMT_TIMING_SIMPLE
:
388 struct timeval now
, delta
;
391 DBG(IO
, ul_debug(" writing timing info"));
393 gettime_monotonic(&now
);
394 timersub(&now
, &log
->oldtime
, &delta
);
395 sz
= fprintf(log
->fp
, "%ld.%06ld %zd\n",
396 (long)delta
.tv_sec
, (long)delta
.tv_usec
, bytes
);
398 bytes
= sz
> 0 ? sz
: 0;
401 case SCRIPT_FMT_TIMING_MULTI
:
403 struct timeval now
, delta
;
406 DBG(IO
, ul_debug(" writing multi-stream timing info"));
408 gettime_monotonic(&now
);
409 timersub(&now
, &log
->oldtime
, &delta
);
410 sz
= fprintf(log
->fp
, "%c %ld.%06ld %zd\n",
412 (long)delta
.tv_sec
, (long)delta
.tv_usec
, bytes
);
414 bytes
= sz
> 0 ? sz
: 0;
426 static uint64_t log_stream_activity(
427 struct script_control
*ctl
,
428 struct script_stream
*stream
,
429 char *buf
, size_t bytes
)
434 for (i
= 0; i
< stream
->nlogs
; i
++)
435 outsz
+= log_write(ctl
, stream
, stream
->logs
[i
], buf
, bytes
);
441 static void die_if_link(struct script_control
*ctl
, const char *filename
)
447 if (lstat(filename
, &s
) == 0 && (S_ISLNK(s
.st_mode
) || s
.st_nlink
> 1))
449 _("output file `%s' is a link\n"
450 "Use --force if you really want to use it.\n"
451 "Program not started."), filename
);
454 static void restore_tty(struct script_control
*ctl
, int mode
)
462 tcsetattr(STDIN_FILENO
, mode
, &rtt
);
465 static void enable_rawmode_tty(struct script_control
*ctl
)
474 rtt
.c_lflag
&= ~ECHO
;
475 tcsetattr(STDIN_FILENO
, TCSANOW
, &rtt
);
478 static void __attribute__((__noreturn__
)) done_log(struct script_control
*ctl
, const char *msg
)
483 DBG(MISC
, ul_debug("done!"));
485 restore_tty(ctl
, TCSADRAIN
);
487 if (WIFSIGNALED(ctl
->childstatus
))
488 status
= WTERMSIG(ctl
->childstatus
) + 0x80;
490 status
= WEXITSTATUS(ctl
->childstatus
);
493 DBG(MISC
, ul_debug(" status=%d", status
));
495 /* close all output logs */
496 for (i
= 0; i
< ctl
->out
.nlogs
; i
++)
497 log_close(ctl
, ctl
->out
.logs
[i
], msg
, status
);
499 /* close all input logs */
500 for (i
= 0; i
< ctl
->in
.nlogs
; i
++)
501 log_close(ctl
, ctl
->in
.logs
[i
], msg
, status
);
504 printf(_("Script done.\n"));
506 #ifdef HAVE_LIBUTEMPTER
507 if (ctl
->master
>= 0)
508 utempter_remove_record(ctl
->master
);
510 kill(ctl
->child
, SIGTERM
); /* make sure we don't create orphans */
511 exit(ctl
->rc_wanted
? status
: EXIT_SUCCESS
);
514 static void __attribute__((__noreturn__
)) done(struct script_control
*ctl
)
519 static void __attribute__((__noreturn__
)) fail(struct script_control
*ctl
)
521 DBG(MISC
, ul_debug("fail!"));
526 static void wait_for_child(struct script_control
*ctl
, int wait
)
530 int options
= wait
? 0 : WNOHANG
;
532 DBG(MISC
, ul_debug("waiting for child"));
534 while ((pid
= wait3(&status
, options
, NULL
)) > 0)
535 if (pid
== ctl
->child
)
536 ctl
->childstatus
= status
;
539 /* data from master to stdout */
540 static void write_output(struct script_control
*ctl
, char *obuf
,
543 DBG(IO
, ul_debug(" writing to output"));
545 if (write_all(STDOUT_FILENO
, obuf
, bytes
)) {
546 DBG(IO
, ul_debug(" writing output *failed*"));
547 warn(_("write failed"));
552 static int write_to_shell(struct script_control
*ctl
,
553 char *buf
, size_t bufsz
)
555 return write_all(ctl
->master
, buf
, bufsz
);
559 * The script(1) is usually faster than shell, so it's a good idea to wait until
560 * the previous message has been already read by shell from slave before we
561 * write to master. This is necessary especially for EOF situation when we can
562 * send EOF to master before shell is fully initialized, to workaround this
563 * problem we wait until slave is empty. For example:
565 * echo "date" | script
567 * Unfortunately, the child (usually shell) can ignore stdin at all, so we
568 * don't wait forever to avoid dead locks...
570 * Note that script is primarily designed for interactive sessions as it
571 * maintains master+slave tty stuff within the session. Use pipe to write to
572 * script(1) and assume non-interactive (tee-like) behavior is NOT well
575 static void write_eof_to_shell(struct script_control
*ctl
)
577 unsigned int tries
= 0;
578 struct pollfd fds
[] = {
579 { .fd
= ctl
->slave
, .events
= POLLIN
}
583 DBG(IO
, ul_debug(" waiting for empty slave"));
584 while (poll(fds
, 1, 10) == 1 && tries
< 8) {
585 DBG(IO
, ul_debug(" slave is not empty"));
590 DBG(IO
, ul_debug(" slave is empty now"));
592 DBG(IO
, ul_debug(" sending EOF to master"));
593 write_to_shell(ctl
, &c
, sizeof(char));
596 static void handle_io(struct script_control
*ctl
, int fd
, int *eof
)
600 DBG(IO
, ul_debug("%d FD active", fd
));
603 /* read from active FD */
604 bytes
= read(fd
, buf
, sizeof(buf
));
606 if (errno
== EAGAIN
|| errno
== EINTR
)
616 /* from stdin (user) to command */
617 if (fd
== STDIN_FILENO
) {
618 DBG(IO
, ul_debug(" stdin --> master %zd bytes", bytes
));
620 if (write_to_shell(ctl
, buf
, bytes
)) {
621 warn(_("write failed"));
624 /* without sync write_output() will write both input &
625 * shell output that looks like double echoing */
626 fdatasync(ctl
->master
);
627 ctl
->outsz
+= log_stream_activity(ctl
, &ctl
->in
, buf
, (size_t) bytes
);
629 /* from command (master) to stdout and log */
630 } else if (fd
== ctl
->master
) {
631 DBG(IO
, ul_debug(" master --> stdout %zd bytes", bytes
));
632 write_output(ctl
, buf
, bytes
);
633 ctl
->outsz
+= log_stream_activity(ctl
, &ctl
->out
, buf
, (size_t) bytes
);
636 /* check output limit */
637 if (ctl
->maxsz
!= 0 && ctl
->outsz
>= ctl
->maxsz
) {
639 printf(_("Script terminated, max output files size %"PRIu64
" exceeded.\n"), ctl
->maxsz
);
640 DBG(IO
, ul_debug("output size %"PRIu64
", exceeded limit %"PRIu64
, ctl
->outsz
, ctl
->maxsz
));
641 done_log(ctl
, _("max output size exceeded"));
645 static void handle_signal(struct script_control
*ctl
, int fd
)
647 struct signalfd_siginfo info
;
650 DBG(SIGNAL
, ul_debug("signal FD %d active", fd
));
652 bytes
= read(fd
, &info
, sizeof(info
));
653 if (bytes
!= sizeof(info
)) {
654 if (bytes
< 0 && (errno
== EAGAIN
|| errno
== EINTR
))
659 switch (info
.ssi_signo
) {
661 DBG(SIGNAL
, ul_debug(" get signal SIGCHLD [ssi_code=%d, ssi_status=%d]",
662 info
.ssi_code
, info
.ssi_status
));
663 if (info
.ssi_code
== CLD_EXITED
664 || info
.ssi_code
== CLD_KILLED
665 || info
.ssi_code
== CLD_DUMPED
) {
666 wait_for_child(ctl
, 0);
667 ctl
->poll_timeout
= 10;
669 /* In case of ssi_code is CLD_TRAPPED, CLD_STOPPED, or CLD_CONTINUED */
670 } else if (info
.ssi_status
== SIGSTOP
&& ctl
->child
) {
671 DBG(SIGNAL
, ul_debug(" child stop by SIGSTOP -- stop parent too"));
672 kill(getpid(), SIGSTOP
);
673 DBG(SIGNAL
, ul_debug(" resume"));
674 kill(ctl
->child
, SIGCONT
);
678 DBG(SIGNAL
, ul_debug(" get signal SIGWINCH"));
680 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
681 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
689 DBG(SIGNAL
, ul_debug(" get signal SIG{TERM,INT,QUIT}"));
690 fprintf(stderr
, _("\nSession terminated.\n"));
691 /* Child termination is going to generate SIGCHILD (see above) */
692 kill(ctl
->child
, SIGTERM
);
697 DBG(SIGNAL
, ul_debug("signal handle on FD %d done", fd
));
700 static void do_io(struct script_control
*ctl
)
710 struct pollfd pfd
[] = {
711 [POLLFD_SIGNAL
] = { .fd
= ctl
->sigfd
, .events
= POLLIN
| POLLERR
| POLLHUP
},
712 [POLLFD_MASTER
] = { .fd
= ctl
->master
, .events
= POLLIN
| POLLERR
| POLLHUP
},
713 [POLLFD_STDIN
] = { .fd
= STDIN_FILENO
, .events
= POLLIN
| POLLERR
| POLLHUP
}
717 /* start all output logs */
718 for (i
= 0; i
< ctl
->out
.nlogs
; i
++)
719 log_start(ctl
, ctl
->out
.logs
[i
]);
721 /* start all input logs */
722 for (i
= 0; i
< ctl
->in
.nlogs
; i
++)
723 log_start(ctl
, ctl
->in
.logs
[i
]);
729 DBG(POLL
, ul_debug("calling poll()"));
731 /* wait for input or signal */
732 ret
= poll(pfd
, ARRAY_SIZE(pfd
), ctl
->poll_timeout
);
734 DBG(POLL
, ul_debug("poll() rc=%d", ret
));
739 warn(_("poll failed"));
743 DBG(POLL
, ul_debug("setting die=1"));
748 for (i
= 0; i
< ARRAY_SIZE(pfd
); i
++) {
749 if (pfd
[i
].revents
== 0)
752 DBG(POLL
, ul_debug(" active pfd[%s].fd=%d %s %s %s",
753 i
== POLLFD_STDIN
? "stdin" :
754 i
== POLLFD_MASTER
? "master" :
755 i
== POLLFD_SIGNAL
? "signal" : "???",
757 pfd
[i
].revents
& POLLIN
? "POLLIN" : "",
758 pfd
[i
].revents
& POLLHUP
? "POLLHUP" : "",
759 pfd
[i
].revents
& POLLERR
? "POLLERR" : ""));
764 if (pfd
[i
].revents
& POLLIN
)
765 handle_io(ctl
, pfd
[i
].fd
, &eof
);
766 /* EOF maybe detected by two ways:
767 * A) poll() return POLLHUP event after close()
768 * B) read() returns 0 (no data) */
769 if ((pfd
[i
].revents
& POLLHUP
) || eof
) {
770 DBG(POLL
, ul_debug(" ignore FD"));
772 if (i
== POLLFD_STDIN
) {
773 write_eof_to_shell(ctl
);
774 DBG(POLL
, ul_debug(" ignore STDIN"));
779 handle_signal(ctl
, pfd
[i
].fd
);
785 DBG(POLL
, ul_debug("poll() done"));
788 wait_for_child(ctl
, 1);
793 static void getslave(struct script_control
*ctl
)
796 ctl
->line
[strlen("/dev/")] = 't';
797 ctl
->slave
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
798 if (ctl
->slave
< 0) {
799 warn(_("cannot open %s"), ctl
->line
);
803 tcsetattr(ctl
->slave
, TCSANOW
, &ctl
->attrs
);
804 ioctl(ctl
->slave
, TIOCSWINSZ
, (char *)&ctl
->win
);
808 ioctl(ctl
->slave
, TIOCSCTTY
, 0);
811 /* don't use DBG() stuff here otherwise it will be in the typescript file */
812 static void __attribute__((__noreturn__
)) do_shell(struct script_control
*ctl
)
818 /* close things irrelevant for this process */
822 dup2(ctl
->slave
, STDIN_FILENO
);
823 dup2(ctl
->slave
, STDOUT_FILENO
);
824 dup2(ctl
->slave
, STDERR_FILENO
);
829 shname
= strrchr(ctl
->shell
, '/');
835 sigprocmask(SIG_SETMASK
, &ctl
->sigorg
, NULL
);
838 * When invoked from within /etc/csh.login, script spawns a csh shell
839 * that spawns programs that cannot be killed with a SIGTERM. This is
840 * because csh has a documented behavior wherein it disables all
841 * signals when processing the /etc/csh.* files.
843 * Let's restore the default behavior.
845 signal(SIGTERM
, SIG_DFL
);
847 if (access(ctl
->shell
, X_OK
) == 0) {
849 execl(ctl
->shell
, shname
, "-c", ctl
->command
, NULL
);
851 execl(ctl
->shell
, shname
, "-i", NULL
);
854 execlp(shname
, "-c", ctl
->command
, NULL
);
856 execlp(shname
, "-i", NULL
);
858 warn(_("failed to execute %s"), ctl
->shell
);
863 static void getmaster(struct script_control
*ctl
)
865 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
868 ctl
->isterm
= isatty(STDIN_FILENO
);
871 if (tcgetattr(STDIN_FILENO
, &ctl
->attrs
) != 0)
872 err(EXIT_FAILURE
, _("failed to get terminal attributes"));
873 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
874 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, &ctl
->attrs
, &ctl
->win
);
876 rc
= openpty(&ctl
->master
, &ctl
->slave
, NULL
, NULL
, NULL
);
879 warn(_("openpty failed"));
883 char *pty
, *bank
, *cp
;
885 ctl
->isterm
= isatty(STDIN_FILENO
);
887 pty
= &ctl
->line
[strlen("/dev/ptyp")];
888 for (bank
= "pqrs"; *bank
; bank
++) {
889 ctl
->line
[strlen("/dev/pty")] = *bank
;
891 if (access(ctl
->line
, F_OK
) != 0)
893 for (cp
= "0123456789abcdef"; *cp
; cp
++) {
895 ctl
->master
= open(ctl
->line
, O_RDWR
| O_CLOEXEC
);
896 if (ctl
->master
>= 0) {
897 char *tp
= &ctl
->line
[strlen("/dev/")];
900 /* verify slave side is usable */
902 ok
= access(ctl
->line
, R_OK
| W_OK
) == 0;
906 tcgetattr(STDIN_FILENO
, &ctl
->attrs
);
907 ioctl(STDIN_FILENO
, TIOCGWINSZ
, (char *)&ctl
->win
);
917 warn(_("out of pty's"));
919 #endif /* not HAVE_LIBUTIL */
921 DBG(IO
, ul_debug("master fd: %d", ctl
->master
));
924 int main(int argc
, char **argv
)
926 struct script_control ctl
= {
927 #if !HAVE_LIBUTIL || !HAVE_PTY_H
928 .line
= "/dev/ptyXX",
933 .out
= { .ident
= 'O' },
934 .in
= { .ident
= 'I' },
939 const char *outfile
= NULL
, *infile
= NULL
;
940 const char *timingfile
= NULL
;
942 enum { FORCE_OPTION
= CHAR_MAX
+ 1 };
944 static const struct option longopts
[] = {
945 {"append", no_argument
, NULL
, 'a'},
946 {"command", required_argument
, NULL
, 'c'},
947 {"return", no_argument
, NULL
, 'e'},
948 {"flush", no_argument
, NULL
, 'f'},
949 {"force", no_argument
, NULL
, FORCE_OPTION
,},
950 {"log-in", required_argument
, NULL
, 'I'},
951 {"log-out", required_argument
, NULL
, 'O'},
952 {"log-io", required_argument
, NULL
, 'B'},
953 {"log-timing", required_argument
, NULL
, 'T'},
954 {"logging-format", required_argument
, NULL
, 'm'},
955 {"output-limit", required_argument
, NULL
, 'o'},
956 {"quiet", no_argument
, NULL
, 'q'},
957 {"timing", optional_argument
, NULL
, 't'},
958 {"version", no_argument
, NULL
, 'V'},
959 {"help", no_argument
, NULL
, 'h'},
962 static const ul_excl_t excl
[] = { /* rows and cols in ASCII order */
966 int excl_st
[ARRAY_SIZE(excl
)] = UL_EXCL_STATUS_INIT
;
967 setlocale(LC_ALL
, "");
969 * script -t prints time delays as floating point numbers. The example
970 * program (scriptreplay) that we provide to handle this timing output
971 * is a perl script, and does not handle numbers in locale format (not
972 * even when "use locale;" is added). So, since these numbers are not
973 * for human consumption, it seems easiest to set LC_NUMERIC here.
975 setlocale(LC_NUMERIC
, "C");
976 bindtextdomain(PACKAGE
, LOCALEDIR
);
978 close_stdout_atexit();
982 while ((ch
= getopt_long(argc
, argv
, "aB:c:efI:O:o:qm:T:t::Vh", longopts
, NULL
)) != -1) {
984 err_exclusive_options(ch
, longopts
, excl
, excl_st
);
991 ctl
.command
= optarg
;
1003 log_associate(&ctl
, &ctl
.in
, optarg
, SCRIPT_FMT_RAW
);
1004 log_associate(&ctl
, &ctl
.out
, optarg
, SCRIPT_FMT_RAW
);
1005 infile
= outfile
= optarg
;
1008 log_associate(&ctl
, &ctl
.in
, optarg
, SCRIPT_FMT_RAW
);
1012 log_associate(&ctl
, &ctl
.out
, optarg
, SCRIPT_FMT_RAW
);
1016 ctl
.maxsz
= strtosize_or_err(optarg
, _("failed to parse output limit size"));
1022 if (strcasecmp(optarg
, "classic") == 0)
1023 format
= SCRIPT_FMT_TIMING_SIMPLE
;
1024 else if (strcasecmp(optarg
, "advanced") == 0)
1025 format
= SCRIPT_FMT_TIMING_MULTI
;
1027 errx(EXIT_FAILURE
, _("unssuported logging format: '%s'"), optarg
);
1030 if (optarg
&& *optarg
== '=')
1032 log_associate(&ctl
, &ctl
.out
,
1033 optarg
? optarg
: "/dev/stderr",
1034 SCRIPT_FMT_TIMING_SIMPLE
);
1035 /* used for message only */
1036 timingfile
= optarg
? optarg
: "stderr";
1039 timingfile
= optarg
;
1042 print_version(EXIT_SUCCESS
);
1046 errtryhelp(EXIT_FAILURE
);
1052 /* default if no --log-* specified */
1053 if (!outfile
&& !infile
) {
1057 die_if_link(&ctl
, DEFAULT_TYPESCRIPT_FILENAME
);
1058 outfile
= DEFAULT_TYPESCRIPT_FILENAME
;
1061 /* associate stdout with typescript file */
1062 log_associate(&ctl
, &ctl
.out
, outfile
, SCRIPT_FMT_RAW
);
1067 format
= outfile
&& infile
?
1068 SCRIPT_FMT_TIMING_MULTI
:
1069 SCRIPT_FMT_TIMING_SIMPLE
;
1071 else if (format
== SCRIPT_FMT_TIMING_SIMPLE
&& outfile
&& infile
)
1072 errx(EXIT_FAILURE
, _("log multiple streams is mutually "
1073 "exclusive with 'classic' format"));
1075 log_associate(&ctl
, &ctl
.out
, timingfile
, format
);
1077 log_associate(&ctl
, &ctl
.in
, timingfile
, format
);
1080 ctl
.shell
= getenv("SHELL");
1081 if (ctl
.shell
== NULL
)
1082 ctl
.shell
= _PATH_BSHELL
;
1086 printf(_("Script started"));
1088 printf(_(", output log file is '%s'"), outfile
);
1090 printf(_(", input log file is '%s'"), infile
);
1092 printf(_(", timing file is '%s'"), timingfile
);
1095 enable_rawmode_tty(&ctl
);
1097 #ifdef HAVE_LIBUTEMPTER
1098 utempter_add_record(ctl
.master
, NULL
);
1100 /* setup signal handler */
1101 sigemptyset(&ctl
.sigset
);
1102 sigaddset(&ctl
.sigset
, SIGCHLD
);
1103 sigaddset(&ctl
.sigset
, SIGWINCH
);
1104 sigaddset(&ctl
.sigset
, SIGTERM
);
1105 sigaddset(&ctl
.sigset
, SIGINT
);
1106 sigaddset(&ctl
.sigset
, SIGQUIT
);
1108 /* block signals used for signalfd() to prevent the signals being
1109 * handled according to their default dispositions */
1110 sigprocmask(SIG_BLOCK
, &ctl
.sigset
, &ctl
.sigorg
);
1112 if ((ctl
.sigfd
= signalfd(-1, &ctl
.sigset
, SFD_CLOEXEC
)) < 0)
1113 err(EXIT_FAILURE
, _("cannot set signal handler"));
1115 DBG(SIGNAL
, ul_debug("signal fd=%d", ctl
.sigfd
));
1120 switch (ctl
.child
) {
1121 case -1: /* error */
1122 warn(_("fork failed"));
1128 default: /* parent */
1133 /* should not happen, all used functions are non-return */
1134 return EXIT_FAILURE
;