]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/script.c
6569c98f4907321787aaeef6e8c9cc0542d33942
[thirdparty/util-linux.git] / term-utils / script.c
1 /*
2 * Copyright (c) 1980 Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
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.
20 *
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
31 * SUCH DAMAGE.
32 */
33
34 /*
35 * 1999-02-22 Arkadiusz Miƛkiewicz <misiek@pld.ORG.PL>
36 * - added Native Language Support
37 *
38 * 2000-07-30 Per Andreas Buer <per@linpro.no> - added "q"-option
39 *
40 * 2014-05-30 Csaba Kos <csaba.kos@gmail.com>
41 * - fixed a rare deadlock after child termination
42 */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <paths.h>
47 #include <time.h>
48 #include <sys/stat.h>
49 #include <termios.h>
50 #include <sys/ioctl.h>
51 #include <sys/time.h>
52 #include <signal.h>
53 #include <errno.h>
54 #include <string.h>
55 #include <getopt.h>
56 #include <unistd.h>
57 #include <fcntl.h>
58 #include <limits.h>
59 #include <locale.h>
60 #include <stddef.h>
61 #include <sys/wait.h>
62 #include <poll.h>
63 #include <sys/signalfd.h>
64 #include <assert.h>
65 #include <inttypes.h>
66
67 #include "closestream.h"
68 #include "nls.h"
69 #include "c.h"
70 #include "ttyutils.h"
71 #include "all-io.h"
72 #include "monotonic.h"
73 #include "timeutils.h"
74 #include "strutils.h"
75 #include "xalloc.h"
76 #include "optutils.h"
77
78 #include "debug.h"
79
80 static UL_DEBUG_DEFINE_MASK(script);
81 UL_DEBUG_DEFINE_MASKNAMES(script) = UL_DEBUG_EMPTY_MASKNAMES;
82
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
89
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)
92
93 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
94 # include <pty.h>
95 #endif
96
97 #ifdef HAVE_LIBUTEMPTER
98 # include <utempter.h>
99 #endif
100
101 #define DEFAULT_TYPESCRIPT_FILENAME "typescript"
102
103 /*
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"
107 * (raw).
108 *
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.
111 */
112 enum {
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> */
116 };
117
118 struct script_log {
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) */
123
124 unsigned int initialized : 1;
125 };
126
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 */
131 };
132
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 */
138
139 int master; /* pseudoterminal master file descriptor */
140 int slave; /* pseudoterminal slave file descriptor */
141
142 struct script_stream out; /* output */
143 struct script_stream in; /* input */
144
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 */
152 #endif
153 unsigned int
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 */
161
162 sigset_t sigset; /* catch SIGCHLD and SIGWINCH with signalfd() */
163 sigset_t sigorg; /* original signal mask */
164 int sigfd; /* file descriptor for signalfd() */
165 };
166
167 static void restore_tty(struct script_control *ctl, int mode);
168 static void __attribute__((__noreturn__)) fail(struct script_control *ctl);
169
170 static void script_init_debug(void)
171 {
172 __UL_INIT_DEBUG_FROM_ENV(script, SCRIPT_DEBUG_, 0, SCRIPT_DEBUG);
173 }
174
175 /*
176 * For tests we want to be able to control time output
177 */
178 #ifdef TEST_SCRIPT
179 static inline time_t script_time(time_t *t)
180 {
181 const char *str = getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
182 int64_t sec;
183
184 if (!str || sscanf(str, "%"SCNi64, &sec) != 1)
185 return time(t);
186 if (t)
187 *t = (time_t)sec;
188 return (time_t)sec;
189 }
190 #else /* !TEST_SCRIPT */
191 # define script_time(x) time(x)
192 #endif
193
194 static void __attribute__((__noreturn__)) usage(void)
195 {
196 FILE *out = stdout;
197 fputs(USAGE_HEADER, out);
198 fprintf(out, _(" %s [options] [file]\n"), program_invocation_short_name);
199
200 fputs(USAGE_SEPARATOR, out);
201 fputs(_("Make a typescript of a terminal session.\n"), out);
202
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);
208
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);
213
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);
221
222 fputs(USAGE_SEPARATOR, out);
223 printf(USAGE_HELP_OPTIONS(31));
224 printf(USAGE_MAN_TAIL("script(1)"));
225
226 exit(EXIT_SUCCESS);
227 }
228
229 static struct script_log *get_log_by_name(struct script_stream *stream,
230 const char *name)
231 {
232 size_t i;
233
234 for (i = 0; i < stream->nlogs; i++) {
235 struct script_log *log = stream->logs[i];
236 if (strcmp(log->filename, name) == 0)
237 return log;
238 }
239 return NULL;
240 }
241
242 static struct script_log *log_associate(struct script_control *ctl,
243 struct script_stream *stream,
244 const char *filename, int format)
245 {
246 struct script_log *log;
247
248 DBG(MISC, ul_debug("associate %s with stream", filename));
249
250 assert(ctl);
251 assert(filename);
252 assert(stream);
253
254 log = get_log_by_name(stream, filename);
255 if (log)
256 return log; /* already defined */
257
258 log = get_log_by_name(stream == &ctl->out ? &ctl->in : &ctl->out, filename);
259 if (!log) {
260 /* create a new log */
261 log = xcalloc(1, sizeof(*log));
262 log->filename = xstrdup(filename);
263 log->format = format;
264 }
265
266 /* add log to the stream */
267 stream->logs = xrealloc(stream->logs,
268 (stream->nlogs + 1) * sizeof(log));
269 stream->logs[stream->nlogs] = log;
270 stream->nlogs++;
271
272 return log;
273 }
274
275 static void log_close(struct script_control *ctl __attribute__((unused)),
276 struct script_log *log,
277 const char *msg,
278 int status)
279 {
280 if (!log->initialized)
281 return;
282
283 DBG(MISC, ul_debug("closing %s", log->filename));
284
285 switch (log->format) {
286 case SCRIPT_FMT_RAW:
287 {
288 char buf[FORMAT_TIMESTAMP_MAX];
289 time_t tvec = script_time((time_t *)NULL);
290
291 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
292 if (msg)
293 fprintf(log->fp, _("\nScript done on %s [<%s>]\n"), buf, msg);
294 else
295 fprintf(log->fp, _("\nScript done on %s [COMMAND_EXIT_CODE=\"%d\"]\n"), buf, status);
296 break;
297 }
298 case SCRIPT_FMT_TIMING_SIMPLE:
299 break;
300 }
301
302 if (close_stream(log->fp) != 0)
303 err(EXIT_FAILURE, "write failed: %s", log->filename);
304
305 log->fp = NULL;
306 log->initialized = 0;
307 }
308
309 static void log_start(struct script_control *ctl,
310 struct script_log *log)
311 {
312 if (log->initialized)
313 return;
314
315 DBG(MISC, ul_debug("opening %s", log->filename));
316
317 assert(log->fp == NULL);
318
319 /* open the log */
320 log->fp = fopen(log->filename,
321 ctl->append && log->format == SCRIPT_FMT_RAW ?
322 "a" UL_CLOEXECSTR :
323 "w" UL_CLOEXECSTR);
324 if (!log->fp) {
325 restore_tty(ctl, TCSANOW);
326 warn(_("cannot open %s"), log->filename);
327 fail(ctl);
328 }
329
330 /* write header, etc. */
331 switch (log->format) {
332 case SCRIPT_FMT_RAW:
333 {
334 char buf[FORMAT_TIMESTAMP_MAX];
335 time_t tvec = script_time((time_t *)NULL);
336
337 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
338 fprintf(log->fp, _("Script started on %s ["), buf);
339
340 if (ctl->isterm) {
341 int cols = 0, lines = 0;
342 const char *tty = NULL, *term = NULL;
343
344 get_terminal_dimension(&cols, &lines);
345 get_terminal_name(&tty, NULL, NULL);
346 get_terminal_type(&term);
347
348 if (term)
349 fprintf(log->fp, "TERM=\"%s\" ", term);
350 if (tty)
351 fprintf(log->fp, "TTY=\"%s\" ", tty);
352
353 fprintf(log->fp, "COLUMNS=\"%d\" LINES=\"%d\"", cols, lines);
354 } else
355 fprintf(log->fp, _("<not executed on terminal>"));
356
357 fputs("]\n", log->fp);
358 break;
359 }
360 case SCRIPT_FMT_TIMING_SIMPLE:
361 case SCRIPT_FMT_TIMING_MULTI:
362 gettime_monotonic(&log->oldtime);
363 break;
364 }
365
366 log->initialized = 1;
367 }
368
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)
373 {
374 if (!log->fp)
375 return 0;
376
377 DBG(IO, ul_debug(" writining %s", log->filename));
378
379 switch (log->format) {
380 case SCRIPT_FMT_RAW:
381 if (fwrite_all(obuf, 1, bytes, log->fp)) {
382 warn(_("cannot write %s"), log->filename);
383 fail(ctl);
384 }
385 break;
386 case SCRIPT_FMT_TIMING_SIMPLE:
387 {
388 struct timeval now, delta;
389 int sz;
390
391 DBG(IO, ul_debug(" writing timing info"));
392
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);
397 log->oldtime = now;
398 bytes = sz > 0 ? sz : 0;
399 break;
400 }
401 case SCRIPT_FMT_TIMING_MULTI:
402 {
403 struct timeval now, delta;
404 int sz;
405
406 DBG(IO, ul_debug(" writing multi-stream timing info"));
407
408 gettime_monotonic(&now);
409 timersub(&now, &log->oldtime, &delta);
410 sz = fprintf(log->fp, "%c %ld.%06ld %zd\n",
411 stream->ident,
412 (long)delta.tv_sec, (long)delta.tv_usec, bytes);
413 log->oldtime = now;
414 bytes = sz > 0 ? sz : 0;
415 }
416 default:
417 break;
418 }
419
420 if (ctl->flush)
421 fflush(log->fp);
422
423 return bytes;
424 }
425
426 static uint64_t log_stream_activity(
427 struct script_control *ctl,
428 struct script_stream *stream,
429 char *buf, size_t bytes)
430 {
431 size_t i;
432 uint64_t outsz = 0;
433
434 for (i = 0; i < stream->nlogs; i++)
435 outsz += log_write(ctl, stream, stream->logs[i], buf, bytes);
436
437 return outsz;
438 }
439
440
441 static void die_if_link(struct script_control *ctl, const char *filename)
442 {
443 struct stat s;
444
445 if (ctl->force)
446 return;
447 if (lstat(filename, &s) == 0 && (S_ISLNK(s.st_mode) || s.st_nlink > 1))
448 errx(EXIT_FAILURE,
449 _("output file `%s' is a link\n"
450 "Use --force if you really want to use it.\n"
451 "Program not started."), filename);
452 }
453
454 static void restore_tty(struct script_control *ctl, int mode)
455 {
456 struct termios rtt;
457
458 if (!ctl->isterm)
459 return;
460
461 rtt = ctl->attrs;
462 tcsetattr(STDIN_FILENO, mode, &rtt);
463 }
464
465 static void enable_rawmode_tty(struct script_control *ctl)
466 {
467 struct termios rtt;
468
469 if (!ctl->isterm)
470 return;
471
472 rtt = ctl->attrs;
473 cfmakeraw(&rtt);
474 rtt.c_lflag &= ~ECHO;
475 tcsetattr(STDIN_FILENO, TCSANOW, &rtt);
476 }
477
478 static void __attribute__((__noreturn__)) done_log(struct script_control *ctl, const char *msg)
479 {
480 int status;
481 size_t i;
482
483 DBG(MISC, ul_debug("done!"));
484
485 restore_tty(ctl, TCSADRAIN);
486
487 if (WIFSIGNALED(ctl->childstatus))
488 status = WTERMSIG(ctl->childstatus) + 0x80;
489 else
490 status = WEXITSTATUS(ctl->childstatus);
491
492
493 DBG(MISC, ul_debug(" status=%d", status));
494
495 /* close all output logs */
496 for (i = 0; i < ctl->out.nlogs; i++)
497 log_close(ctl, ctl->out.logs[i], msg, status);
498
499 /* close all input logs */
500 for (i = 0; i < ctl->in.nlogs; i++)
501 log_close(ctl, ctl->in.logs[i], msg, status);
502
503 if (!ctl->quiet)
504 printf(_("Script done.\n"));
505
506 #ifdef HAVE_LIBUTEMPTER
507 if (ctl->master >= 0)
508 utempter_remove_record(ctl->master);
509 #endif
510 kill(ctl->child, SIGTERM); /* make sure we don't create orphans */
511 exit(ctl->rc_wanted ? status : EXIT_SUCCESS);
512 }
513
514 static void __attribute__((__noreturn__)) done(struct script_control *ctl)
515 {
516 done_log(ctl, NULL);
517 }
518
519 static void __attribute__((__noreturn__)) fail(struct script_control *ctl)
520 {
521 DBG(MISC, ul_debug("fail!"));
522 kill(0, SIGTERM);
523 done(ctl);
524 }
525
526 static void wait_for_child(struct script_control *ctl, int wait)
527 {
528 int status;
529 pid_t pid;
530 int options = wait ? 0 : WNOHANG;
531
532 DBG(MISC, ul_debug("waiting for child"));
533
534 while ((pid = wait3(&status, options, NULL)) > 0)
535 if (pid == ctl->child)
536 ctl->childstatus = status;
537 }
538
539 /* data from master to stdout */
540 static void write_output(struct script_control *ctl, char *obuf,
541 ssize_t bytes)
542 {
543 DBG(IO, ul_debug(" writing to output"));
544
545 if (write_all(STDOUT_FILENO, obuf, bytes)) {
546 DBG(IO, ul_debug(" writing output *failed*"));
547 warn(_("write failed"));
548 fail(ctl);
549 }
550 }
551
552 static int write_to_shell(struct script_control *ctl,
553 char *buf, size_t bufsz)
554 {
555 return write_all(ctl->master, buf, bufsz);
556 }
557
558 /*
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:
564 *
565 * echo "date" | script
566 *
567 * Unfortunately, the child (usually shell) can ignore stdin at all, so we
568 * don't wait forever to avoid dead locks...
569 *
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
573 * supported.
574 */
575 static void write_eof_to_shell(struct script_control *ctl)
576 {
577 unsigned int tries = 0;
578 struct pollfd fds[] = {
579 { .fd = ctl->slave, .events = POLLIN }
580 };
581 char c = DEF_EOF;
582
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"));
586 xusleep(250000);
587 tries++;
588 }
589 if (tries < 8)
590 DBG(IO, ul_debug(" slave is empty now"));
591
592 DBG(IO, ul_debug(" sending EOF to master"));
593 write_to_shell(ctl, &c, sizeof(char));
594 }
595
596 static void handle_io(struct script_control *ctl, int fd, int *eof)
597 {
598 char buf[BUFSIZ];
599 ssize_t bytes;
600 DBG(IO, ul_debug("%d FD active", fd));
601 *eof = 0;
602
603 /* read from active FD */
604 bytes = read(fd, buf, sizeof(buf));
605 if (bytes < 0) {
606 if (errno == EAGAIN || errno == EINTR)
607 return;
608 fail(ctl);
609 }
610
611 if (bytes == 0) {
612 *eof = 1;
613 return;
614 }
615
616 /* from stdin (user) to command */
617 if (fd == STDIN_FILENO) {
618 DBG(IO, ul_debug(" stdin --> master %zd bytes", bytes));
619
620 if (write_to_shell(ctl, buf, bytes)) {
621 warn(_("write failed"));
622 fail(ctl);
623 }
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);
628
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);
634 }
635
636 /* check output limit */
637 if (ctl->maxsz != 0 && ctl->outsz >= ctl->maxsz) {
638 if (!ctl->quiet)
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"));
642 }
643 }
644
645 static void handle_signal(struct script_control *ctl, int fd)
646 {
647 struct signalfd_siginfo info;
648 ssize_t bytes;
649
650 DBG(SIGNAL, ul_debug("signal FD %d active", fd));
651
652 bytes = read(fd, &info, sizeof(info));
653 if (bytes != sizeof(info)) {
654 if (bytes < 0 && (errno == EAGAIN || errno == EINTR))
655 return;
656 fail(ctl);
657 }
658
659 switch (info.ssi_signo) {
660 case SIGCHLD:
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;
668
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);
675 }
676 return;
677 case SIGWINCH:
678 DBG(SIGNAL, ul_debug(" get signal SIGWINCH"));
679 if (ctl->isterm) {
680 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ctl->win);
681 ioctl(ctl->slave, TIOCSWINSZ, (char *)&ctl->win);
682 }
683 break;
684 case SIGTERM:
685 /* fallthrough */
686 case SIGINT:
687 /* fallthrough */
688 case SIGQUIT:
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);
693 return;
694 default:
695 abort();
696 }
697 DBG(SIGNAL, ul_debug("signal handle on FD %d done", fd));
698 }
699
700 static void do_io(struct script_control *ctl)
701 {
702 int ret, eof = 0;
703 size_t i;
704 enum {
705 POLLFD_SIGNAL = 0,
706 POLLFD_MASTER,
707 POLLFD_STDIN
708
709 };
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 }
714 };
715
716
717 /* start all output logs */
718 for (i = 0; i < ctl->out.nlogs; i++)
719 log_start(ctl, ctl->out.logs[i]);
720
721 /* start all input logs */
722 for (i = 0; i < ctl->in.nlogs; i++)
723 log_start(ctl, ctl->in.logs[i]);
724
725 while (!ctl->die) {
726 size_t i;
727 int errsv;
728
729 DBG(POLL, ul_debug("calling poll()"));
730
731 /* wait for input or signal */
732 ret = poll(pfd, ARRAY_SIZE(pfd), ctl->poll_timeout);
733 errsv = errno;
734 DBG(POLL, ul_debug("poll() rc=%d", ret));
735
736 if (ret < 0) {
737 if (errsv == EAGAIN)
738 continue;
739 warn(_("poll failed"));
740 fail(ctl);
741 }
742 if (ret == 0) {
743 DBG(POLL, ul_debug("setting die=1"));
744 ctl->die = 1;
745 break;
746 }
747
748 for (i = 0; i < ARRAY_SIZE(pfd); i++) {
749 if (pfd[i].revents == 0)
750 continue;
751
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" : "???",
756 pfd[i].fd,
757 pfd[i].revents & POLLIN ? "POLLIN" : "",
758 pfd[i].revents & POLLHUP ? "POLLHUP" : "",
759 pfd[i].revents & POLLERR ? "POLLERR" : ""));
760 switch (i) {
761 case POLLFD_STDIN:
762 case POLLFD_MASTER:
763 /* data */
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"));
771 pfd[i].fd = -1;
772 if (i == POLLFD_STDIN) {
773 write_eof_to_shell(ctl);
774 DBG(POLL, ul_debug(" ignore STDIN"));
775 }
776 }
777 continue;
778 case POLLFD_SIGNAL:
779 handle_signal(ctl, pfd[i].fd);
780 break;
781 }
782 }
783 }
784
785 DBG(POLL, ul_debug("poll() done"));
786
787 if (!ctl->die)
788 wait_for_child(ctl, 1);
789
790 done(ctl);
791 }
792
793 static void getslave(struct script_control *ctl)
794 {
795 #ifndef HAVE_LIBUTIL
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);
800 fail(ctl);
801 }
802 if (ctl->isterm) {
803 tcsetattr(ctl->slave, TCSANOW, &ctl->attrs);
804 ioctl(ctl->slave, TIOCSWINSZ, (char *)&ctl->win);
805 }
806 #endif
807 setsid();
808 ioctl(ctl->slave, TIOCSCTTY, 0);
809 }
810
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)
813 {
814 char *shname;
815
816 getslave(ctl);
817
818 /* close things irrelevant for this process */
819 close(ctl->master);
820 close(ctl->sigfd);
821
822 dup2(ctl->slave, STDIN_FILENO);
823 dup2(ctl->slave, STDOUT_FILENO);
824 dup2(ctl->slave, STDERR_FILENO);
825 close(ctl->slave);
826
827 ctl->master = -1;
828
829 shname = strrchr(ctl->shell, '/');
830 if (shname)
831 shname++;
832 else
833 shname = ctl->shell;
834
835 sigprocmask(SIG_SETMASK, &ctl->sigorg, NULL);
836
837 /*
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.
842 *
843 * Let's restore the default behavior.
844 */
845 signal(SIGTERM, SIG_DFL);
846
847 if (access(ctl->shell, X_OK) == 0) {
848 if (ctl->command)
849 execl(ctl->shell, shname, "-c", ctl->command, NULL);
850 else
851 execl(ctl->shell, shname, "-i", NULL);
852 } else {
853 if (ctl->command)
854 execlp(shname, "-c", ctl->command, NULL);
855 else
856 execlp(shname, "-i", NULL);
857 }
858 warn(_("failed to execute %s"), ctl->shell);
859 fail(ctl);
860 }
861
862
863 static void getmaster(struct script_control *ctl)
864 {
865 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
866 int rc;
867
868 ctl->isterm = isatty(STDIN_FILENO);
869
870 if (ctl->isterm) {
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);
875 } else
876 rc = openpty(&ctl->master, &ctl->slave, NULL, NULL, NULL);
877
878 if (rc < 0) {
879 warn(_("openpty failed"));
880 fail(ctl);
881 }
882 #else
883 char *pty, *bank, *cp;
884
885 ctl->isterm = isatty(STDIN_FILENO);
886
887 pty = &ctl->line[strlen("/dev/ptyp")];
888 for (bank = "pqrs"; *bank; bank++) {
889 ctl->line[strlen("/dev/pty")] = *bank;
890 *pty = '0';
891 if (access(ctl->line, F_OK) != 0)
892 break;
893 for (cp = "0123456789abcdef"; *cp; cp++) {
894 *pty = *cp;
895 ctl->master = open(ctl->line, O_RDWR | O_CLOEXEC);
896 if (ctl->master >= 0) {
897 char *tp = &ctl->line[strlen("/dev/")];
898 int ok;
899
900 /* verify slave side is usable */
901 *tp = 't';
902 ok = access(ctl->line, R_OK | W_OK) == 0;
903 *tp = 'p';
904 if (ok) {
905 if (ctl->isterm) {
906 tcgetattr(STDIN_FILENO, &ctl->attrs);
907 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ctl->win);
908 }
909 return;
910 }
911 close(ctl->master);
912 ctl->master = -1;
913 }
914 }
915 }
916 ctl->master = -1;
917 warn(_("out of pty's"));
918 fail(ctl);
919 #endif /* not HAVE_LIBUTIL */
920
921 DBG(IO, ul_debug("master fd: %d", ctl->master));
922 }
923
924 int main(int argc, char **argv)
925 {
926 struct script_control ctl = {
927 #if !HAVE_LIBUTIL || !HAVE_PTY_H
928 .line = "/dev/ptyXX",
929 #endif
930 .master = -1,
931 .slave = -1,
932
933 .out = { .ident = 'O' },
934 .in = { .ident = 'I' },
935
936 .poll_timeout = -1
937 };
938 int ch, format = 0;
939 const char *outfile = NULL, *infile = NULL;
940 const char *timingfile = NULL;
941
942 enum { FORCE_OPTION = CHAR_MAX + 1 };
943
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'},
960 {NULL, 0, NULL, 0}
961 };
962 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
963 { 'T', 't' },
964 { 0 }
965 };
966 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
967 setlocale(LC_ALL, "");
968 /*
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.
974 */
975 setlocale(LC_NUMERIC, "C");
976 bindtextdomain(PACKAGE, LOCALEDIR);
977 textdomain(PACKAGE);
978 close_stdout_atexit();
979
980 script_init_debug();
981
982 while ((ch = getopt_long(argc, argv, "aB:c:efI:O:o:qm:T:t::Vh", longopts, NULL)) != -1) {
983
984 err_exclusive_options(ch, longopts, excl, excl_st);
985
986 switch (ch) {
987 case 'a':
988 ctl.append = 1;
989 break;
990 case 'c':
991 ctl.command = optarg;
992 break;
993 case 'e':
994 ctl.rc_wanted = 1;
995 break;
996 case 'f':
997 ctl.flush = 1;
998 break;
999 case FORCE_OPTION:
1000 ctl.force = 1;
1001 break;
1002 case 'B':
1003 log_associate(&ctl, &ctl.in, optarg, SCRIPT_FMT_RAW);
1004 log_associate(&ctl, &ctl.out, optarg, SCRIPT_FMT_RAW);
1005 infile = outfile = optarg;
1006 break;
1007 case 'I':
1008 log_associate(&ctl, &ctl.in, optarg, SCRIPT_FMT_RAW);
1009 infile = optarg;
1010 break;
1011 case 'O':
1012 log_associate(&ctl, &ctl.out, optarg, SCRIPT_FMT_RAW);
1013 outfile = optarg;
1014 break;
1015 case 'o':
1016 ctl.maxsz = strtosize_or_err(optarg, _("failed to parse output limit size"));
1017 break;
1018 case 'q':
1019 ctl.quiet = 1;
1020 break;
1021 case 'm':
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;
1026 else
1027 errx(EXIT_FAILURE, _("unssuported logging format: '%s'"), optarg);
1028 break;
1029 case 't':
1030 if (optarg && *optarg == '=')
1031 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";
1037 break;
1038 case 'T' :
1039 timingfile = optarg;
1040 break;
1041 case 'V':
1042 print_version(EXIT_SUCCESS);
1043 case 'h':
1044 usage();
1045 default:
1046 errtryhelp(EXIT_FAILURE);
1047 }
1048 }
1049 argc -= optind;
1050 argv += optind;
1051
1052 /* default if no --log-* specified */
1053 if (!outfile && !infile) {
1054 if (argc > 0)
1055 outfile = argv[0];
1056 else {
1057 die_if_link(&ctl, DEFAULT_TYPESCRIPT_FILENAME);
1058 outfile = DEFAULT_TYPESCRIPT_FILENAME;
1059 }
1060
1061 /* associate stdout with typescript file */
1062 log_associate(&ctl, &ctl.out, outfile, SCRIPT_FMT_RAW);
1063 }
1064
1065 if (timingfile) {
1066 if (!format)
1067 format = outfile && infile ?
1068 SCRIPT_FMT_TIMING_MULTI :
1069 SCRIPT_FMT_TIMING_SIMPLE;
1070
1071 else if (format == SCRIPT_FMT_TIMING_SIMPLE && outfile && infile)
1072 errx(EXIT_FAILURE, _("log multiple streams is mutually "
1073 "exclusive with 'classic' format"));
1074 if (outfile)
1075 log_associate(&ctl, &ctl.out, timingfile, format);
1076 if (infile)
1077 log_associate(&ctl, &ctl.in, timingfile, format);
1078 }
1079
1080 ctl.shell = getenv("SHELL");
1081 if (ctl.shell == NULL)
1082 ctl.shell = _PATH_BSHELL;
1083
1084 getmaster(&ctl);
1085 if (!ctl.quiet) {
1086 printf(_("Script started"));
1087 if (outfile)
1088 printf(_(", output log file is '%s'"), outfile);
1089 if (infile)
1090 printf(_(", input log file is '%s'"), infile);
1091 if (timingfile)
1092 printf(_(", timing file is '%s'"), timingfile);
1093 printf(_(".\n"));
1094 }
1095 enable_rawmode_tty(&ctl);
1096
1097 #ifdef HAVE_LIBUTEMPTER
1098 utempter_add_record(ctl.master, NULL);
1099 #endif
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);
1107
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);
1111
1112 if ((ctl.sigfd = signalfd(-1, &ctl.sigset, SFD_CLOEXEC)) < 0)
1113 err(EXIT_FAILURE, _("cannot set signal handler"));
1114
1115 DBG(SIGNAL, ul_debug("signal fd=%d", ctl.sigfd));
1116
1117 fflush(stdout);
1118 ctl.child = fork();
1119
1120 switch (ctl.child) {
1121 case -1: /* error */
1122 warn(_("fork failed"));
1123 fail(&ctl);
1124 break;
1125 case 0: /* child */
1126 do_shell(&ctl);
1127 break;
1128 default: /* parent */
1129 do_io(&ctl);
1130 break;
1131 }
1132
1133 /* should not happen, all used functions are non-return */
1134 return EXIT_FAILURE;
1135 }