]> git.ipfire.org Git - thirdparty/util-linux.git/blame - term-utils/script.c
script: fix signalfd use
[thirdparty/util-linux.git] / term-utils / script.c
CommitLineData
6dbe3af9 1/*
ec10634e
KZ
2 * Copyright (C) 1980 Regents of the University of California.
3 * Copyright (C) 2013-2019 Karel Zak <kzak@redhat.com>
4 *
6dbe3af9
KZ
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. All advertising materials mentioning features or use of this software
16 * must display the following acknowledgement:
edc7e420
SK
17 * This product includes software developed by the University of
18 * California, Berkeley and its contributors.
6dbe3af9
KZ
19 * 4. Neither the name of the University nor the names of its contributors
20 * may be used to endorse or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
22853e4a
KZ
35#include <stdio.h>
36#include <stdlib.h>
37#include <paths.h>
38#include <time.h>
6dbe3af9
KZ
39#include <sys/stat.h>
40#include <termios.h>
41#include <sys/ioctl.h>
42#include <sys/time.h>
172b3c27 43#include <signal.h>
1f58c445 44#include <errno.h>
2b7ff0d9
ST
45#include <string.h>
46#include <getopt.h>
47#include <unistd.h>
8fb810ff 48#include <fcntl.h>
8fb810ff
SK
49#include <limits.h>
50#include <locale.h>
51#include <stddef.h>
3822032d
KZ
52#include <sys/wait.h>
53#include <poll.h>
cc1a88fb
SK
54#include <sys/signalfd.h>
55#include <assert.h>
c2f03da9 56#include <inttypes.h>
2b7ff0d9 57
cdd2a8c3 58#include "closestream.h"
7eda085c 59#include "nls.h"
91239874 60#include "c.h"
3822032d 61#include "ttyutils.h"
c6fca22e 62#include "all-io.h"
04639805 63#include "monotonic.h"
bdef362d 64#include "timeutils.h"
aefe9893 65#include "strutils.h"
596f4202 66#include "xalloc.h"
fc58044f 67#include "optutils.h"
fbed5507 68#include "signames.h"
ec10634e 69#include "pty-session.h"
a2b4dec5
KZ
70#include "debug.h"
71
2ba641e5 72static UL_DEBUG_DEFINE_MASK(script);
a2b4dec5
KZ
73UL_DEBUG_DEFINE_MASKNAMES(script) = UL_DEBUG_EMPTY_MASKNAMES;
74
75#define SCRIPT_DEBUG_INIT (1 << 1)
ec10634e
KZ
76#define SCRIPT_DEBUG_PTY (1 << 2)
77#define SCRIPT_DEBUG_IO (1 << 3)
78#define SCRIPT_DEBUG_SIGNAL (1 << 4)
a2b4dec5
KZ
79#define SCRIPT_DEBUG_MISC (1 << 5)
80#define SCRIPT_DEBUG_ALL 0xFFFF
81
82#define DBG(m, x) __UL_DBG(script, SCRIPT_DEBUG_, m, x)
83#define ON_DBG(m, x) __UL_DBG_CALL(script, SCRIPT_DEBUG_, m, x)
84
f0bc3fa0 85#ifdef HAVE_LIBUTEMPTER
e11a5e63 86# include <utempter.h>
f0bc3fa0
KZ
87#endif
88
7e5796c9 89#define DEFAULT_TYPESCRIPT_FILENAME "typescript"
05644dab 90
fec06a06
KZ
91/*
92 * Script is driven by stream (stdout/stdin) activity. It's possible to
93 * associate arbitrary number of log files with the stream. We have two basic
94 * types of log files: "timing file" (simple or multistream) and "data file"
95 * (raw).
96 *
97 * The same log file maybe be shared between both streams. For exmaple
98 * multi-stream timing file is possible to use for stdin as well as for stdout.
99 */
596f4202
KZ
100enum {
101 SCRIPT_FMT_RAW = 1, /* raw slave/master data */
daee4d95
KZ
102 SCRIPT_FMT_TIMING_SIMPLE, /* (classic) in format "<delta> <offset>" */
103 SCRIPT_FMT_TIMING_MULTI, /* (advanced) multiple streams in format "<type> <delta> <offset|etc> */
596f4202
KZ
104};
105
106struct script_log {
107 FILE *fp; /* file pointer (handler) */
108 int format; /* SCRIPT_FMT_* */
109 char *filename; /* on command line specified name */
88025c74 110 struct timeval oldtime; /* previous entry log time (SCRIPT_FMT_TIMING_* only) */
70c2cd9a 111 struct timeval starttime;
c1c2ee0b
KZ
112
113 unsigned int initialized : 1;
596f4202
KZ
114};
115
116struct script_stream {
9f822648 117 struct script_log **logs; /* logs where to write data from stream */
596f4202 118 size_t nlogs; /* number of logs */
c1c2ee0b 119 char ident; /* stream identifier */
596f4202
KZ
120};
121
edc7e420 122struct script_control {
596f4202
KZ
123 uint64_t outsz; /* current output files size */
124 uint64_t maxsz; /* maximum output files size */
125
596f4202
KZ
126 struct script_stream out; /* output */
127 struct script_stream in; /* input */
128
3cecd176
KZ
129 struct script_log *siglog; /* log for signal entries */
130 struct script_log *infolog; /* log for info entries */
3cecd176
KZ
131
132 const char *ttyname;
133 const char *ttytype;
134 int ttycols;
135 int ttylines;
fbed5507 136
bdd43357 137 struct ul_pty *pty; /* pseudo-terminal */
edc7e420 138 pid_t child; /* child pid */
edc7e420 139 int childstatus; /* child process exit value */
ec10634e 140
edc7e420 141 unsigned int
3f19b85f 142 append:1, /* append output */
7e5796c9 143 rc_wanted:1, /* return child exit value */
3f19b85f
KZ
144 flush:1, /* flush after each write */
145 quiet:1, /* suppress most output */
3f19b85f 146 force:1, /* write output to links */
ec10634e 147 isterm:1; /* is child process running as terminal */
edc7e420 148};
1f58c445 149
ec10634e 150static ssize_t log_info(struct script_control *ctl, const char *name, const char *msgfmt, ...);
596f4202 151
a2b4dec5
KZ
152static void script_init_debug(void)
153{
a15dca2f 154 __UL_INIT_DEBUG_FROM_ENV(script, SCRIPT_DEBUG_, 0, SCRIPT_DEBUG);
a2b4dec5
KZ
155}
156
3cecd176
KZ
157static void init_terminal_info(struct script_control *ctl)
158{
159 if (ctl->ttyname || !ctl->isterm)
160 return; /* already initialized */
161
162 get_terminal_dimension(&ctl->ttycols, &ctl->ttylines);
163 get_terminal_name(&ctl->ttyname, NULL, NULL);
164 get_terminal_type(&ctl->ttytype);
165}
166
6a40c65f
SK
167/*
168 * For tests we want to be able to control time output
169 */
170#ifdef TEST_SCRIPT
171static inline time_t script_time(time_t *t)
172{
173 const char *str = getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
345208a5 174 int64_t sec;
6a40c65f 175
c2f03da9 176 if (!str || sscanf(str, "%"SCNi64, &sec) != 1)
345208a5
ID
177 return time(t);
178 if (t)
179 *t = (time_t)sec;
180 return (time_t)sec;
6a40c65f
SK
181}
182#else /* !TEST_SCRIPT */
183# define script_time(x) time(x)
184#endif
185
86be6a32 186static void __attribute__((__noreturn__)) usage(void)
3ff52639 187{
86be6a32 188 FILE *out = stdout;
db433bf7 189 fputs(USAGE_HEADER, out);
edc7e420 190 fprintf(out, _(" %s [options] [file]\n"), program_invocation_short_name);
87d6050b 191
451dbcfa
BS
192 fputs(USAGE_SEPARATOR, out);
193 fputs(_("Make a typescript of a terminal session.\n"), out);
194
db433bf7 195 fputs(USAGE_OPTIONS, out);
70062aad 196 fputs(_(" -I, --log-in <file> log stdin to file\n"), out);
ddbdb792 197 fputs(_(" -O, --log-out <file> log stdout to file (default)\n"), out);
c1c2ee0b 198 fputs(_(" -B, --log-io <file> log stdin and stdout to file\n"), out);
65dc24ab
KZ
199 fputs(USAGE_SEPARATOR, out);
200
fc58044f 201 fputs(_(" -T, --log-timing <file> log timing information to file\n"), out);
65dc24ab 202 fputs(_(" -t[<file>], --timing[=<file>] deprecated alias to -T (default file is stderr)\n"), out);
daee4d95 203 fputs(_(" -m, --logging-format <name> force to 'classic' or 'advanced' format\n"), out);
65dc24ab
KZ
204 fputs(USAGE_SEPARATOR, out);
205
206 fputs(_(" -a, --append append to the log file\n"), out);
c64963f8
KZ
207 fputs(_(" -c, --command <command> run command rather than interactive shell\n"), out);
208 fputs(_(" -e, --return return exit code of the child process\n"), out);
209 fputs(_(" -f, --flush run flush after each write\n"), out);
210 fputs(_(" --force use output file even when it is a link\n"), out);
211 fputs(_(" -o, --output-limit <size> terminate if output files exceed size\n"), out);
212 fputs(_(" -q, --quiet be quiet\n"), out);
3ff52639 213
c64963f8
KZ
214 fputs(USAGE_SEPARATOR, out);
215 printf(USAGE_HELP_OPTIONS(31));
f45f3ec3 216 printf(USAGE_MAN_TAIL("script(1)"));
c64963f8 217
86be6a32 218 exit(EXIT_SUCCESS);
3ff52639
SK
219}
220
596f4202
KZ
221static struct script_log *get_log_by_name(struct script_stream *stream,
222 const char *name)
4d9b788d 223{
596f4202 224 size_t i;
4d9b788d 225
596f4202 226 for (i = 0; i < stream->nlogs; i++) {
9f822648
KZ
227 struct script_log *log = stream->logs[i];
228 if (strcmp(log->filename, name) == 0)
596f4202
KZ
229 return log;
230 }
231 return NULL;
232}
4d9b788d 233
596f4202
KZ
234static struct script_log *log_associate(struct script_control *ctl,
235 struct script_stream *stream,
236 const char *filename, int format)
237{
238 struct script_log *log;
239
c1c2ee0b
KZ
240 DBG(MISC, ul_debug("associate %s with stream", filename));
241
9f822648
KZ
242 assert(ctl);
243 assert(filename);
244 assert(stream);
245
246 log = get_log_by_name(stream, filename);
247 if (log)
248 return log; /* already defined */
249
250 log = get_log_by_name(stream == &ctl->out ? &ctl->in : &ctl->out, filename);
596f4202
KZ
251 if (!log) {
252 /* create a new log */
9f822648
KZ
253 log = xcalloc(1, sizeof(*log));
254 log->filename = xstrdup(filename);
596f4202
KZ
255 log->format = format;
256 }
4d9b788d 257
9f822648
KZ
258 /* add log to the stream */
259 stream->logs = xrealloc(stream->logs,
260 (stream->nlogs + 1) * sizeof(log));
261 stream->logs[stream->nlogs] = log;
262 stream->nlogs++;
263
fbed5507 264 /* remember where to write info about signals */
3cecd176
KZ
265 if (format == SCRIPT_FMT_TIMING_MULTI) {
266 if (!ctl->siglog)
267 ctl->siglog = log;
268 if (!ctl->infolog)
269 ctl->infolog = log;
3cecd176 270 }
fbed5507 271
596f4202
KZ
272 return log;
273}
4d9b788d 274
ec10634e 275static int log_close(struct script_control *ctl,
596f4202
KZ
276 struct script_log *log,
277 const char *msg,
278 int status)
279{
ec10634e
KZ
280 int rc = 0;
281
9e9b3d65 282 if (!log || !log->initialized)
ec10634e 283 return 0;
c1c2ee0b 284
596f4202 285 DBG(MISC, ul_debug("closing %s", log->filename));
4d9b788d 286
596f4202
KZ
287 switch (log->format) {
288 case SCRIPT_FMT_RAW:
289 {
290 char buf[FORMAT_TIMESTAMP_MAX];
291 time_t tvec = script_time((time_t *)NULL);
4d9b788d 292
596f4202
KZ
293 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
294 if (msg)
295 fprintf(log->fp, _("\nScript done on %s [<%s>]\n"), buf, msg);
296 else
297 fprintf(log->fp, _("\nScript done on %s [COMMAND_EXIT_CODE=\"%d\"]\n"), buf, status);
596f4202
KZ
298 break;
299 }
70c2cd9a
KZ
300 case SCRIPT_FMT_TIMING_MULTI:
301 {
302 struct timeval now, delta;
303
304 gettime_monotonic(&now);
305 timersub(&now, &log->starttime, &delta);
306
307 log_info(ctl, "DURATION", "%ld.%06ld",
308 (long)delta.tv_sec, (long)delta.tv_usec);
309 log_info(ctl, "EXIT_CODE", "%d", status);
310 break;
311 }
596f4202
KZ
312 case SCRIPT_FMT_TIMING_SIMPLE:
313 break;
314 }
315
ec10634e
KZ
316 if (close_stream(log->fp) != 0) {
317 warn(_("write failed: %s"), log->filename);
318 rc = -errno;
319 }
4d9b788d 320
9e9b3d65
KZ
321 free(log->filename);
322 memset(log, 0, sizeof(*log));
ec10634e
KZ
323
324 return rc;
4d9b788d
KZ
325}
326
9e9b3d65
KZ
327static void log_free(struct script_control *ctl, struct script_log *log)
328{
329 size_t i;
330
331 if (!log)
332 return;
333
334 /* the same log is possible to reference from more places, remove all
335 * (TODO: maybe use include/list.h to make it more elegant)
336 */
337 if (ctl->siglog == log)
338 ctl->siglog = NULL;
339 else if (ctl->infolog == log)
340 ctl->infolog = NULL;
341
342 for (i = 0; i < ctl->out.nlogs; i++) {
343 if (ctl->out.logs[i] == log)
344 ctl->out.logs[i] = NULL;
345 }
346 for (i = 0; i < ctl->in.nlogs; i++) {
347 if (ctl->in.logs[i] == log)
348 ctl->in.logs[i] = NULL;
349 }
350 free(log);
351}
352
ec10634e 353static int log_start(struct script_control *ctl,
596f4202 354 struct script_log *log)
6343ee8c 355{
c1c2ee0b 356 if (log->initialized)
ec10634e 357 return 0;
6343ee8c 358
596f4202 359 DBG(MISC, ul_debug("opening %s", log->filename));
6343ee8c 360
c1c2ee0b
KZ
361 assert(log->fp == NULL);
362
596f4202
KZ
363 /* open the log */
364 log->fp = fopen(log->filename,
365 ctl->append && log->format == SCRIPT_FMT_RAW ?
c1c2ee0b
KZ
366 "a" UL_CLOEXECSTR :
367 "w" UL_CLOEXECSTR);
596f4202 368 if (!log->fp) {
596f4202 369 warn(_("cannot open %s"), log->filename);
ec10634e 370 return -errno;
596f4202 371 }
6343ee8c 372
596f4202
KZ
373 /* write header, etc. */
374 switch (log->format) {
375 case SCRIPT_FMT_RAW:
376 {
377 char buf[FORMAT_TIMESTAMP_MAX];
378 time_t tvec = script_time((time_t *)NULL);
379
380 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
381 fprintf(log->fp, _("Script started on %s ["), buf);
382
383 if (ctl->isterm) {
3cecd176 384 init_terminal_info(ctl);
596f4202 385
3cecd176
KZ
386 if (ctl->ttytype)
387 fprintf(log->fp, "TERM=\"%s\" ", ctl->ttytype);
388 if (ctl->ttyname)
389 fprintf(log->fp, "TTY=\"%s\" ", ctl->ttyname);
596f4202 390
3cecd176 391 fprintf(log->fp, "COLUMNS=\"%d\" LINES=\"%d\"", ctl->ttycols, ctl->ttylines);
596f4202
KZ
392 } else
393 fprintf(log->fp, _("<not executed on terminal>"));
394
395 fputs("]\n", log->fp);
396 break;
397 }
398 case SCRIPT_FMT_TIMING_SIMPLE:
36b1369b 399 case SCRIPT_FMT_TIMING_MULTI:
596f4202 400 gettime_monotonic(&log->oldtime);
70c2cd9a 401 gettime_monotonic(&log->starttime);
596f4202
KZ
402 break;
403 }
c1c2ee0b
KZ
404
405 log->initialized = 1;
ec10634e 406 return 0;
596f4202
KZ
407}
408
9e9b3d65 409static int logging_start(struct script_control *ctl)
fd42a45b
KZ
410{
411 size_t i;
412
413 /* start all output logs */
ec10634e
KZ
414 for (i = 0; i < ctl->out.nlogs; i++) {
415 int rc = log_start(ctl, ctl->out.logs[i]);
416 if (rc)
417 return rc;
418 }
fd42a45b
KZ
419
420 /* start all input logs */
ec10634e
KZ
421 for (i = 0; i < ctl->in.nlogs; i++) {
422 int rc = log_start(ctl, ctl->in.logs[i]);
423 if (rc)
424 return rc;
425 }
426 return 0;
fd42a45b
KZ
427}
428
ec10634e 429static ssize_t log_write(struct script_control *ctl,
c1c2ee0b 430 struct script_stream *stream,
596f4202
KZ
431 struct script_log *log,
432 char *obuf, size_t bytes)
433{
ec10634e
KZ
434 int rc;
435 ssize_t ssz = 0;
436 struct timeval now, delta;
437
596f4202
KZ
438 if (!log->fp)
439 return 0;
440
ec10634e 441 DBG(IO, ul_debug(" writing [file=%s]", log->filename));
596f4202
KZ
442
443 switch (log->format) {
444 case SCRIPT_FMT_RAW:
ec10634e
KZ
445 DBG(IO, ul_debug(" log raw data"));
446 rc = fwrite_all(obuf, 1, bytes, log->fp);
447 if (rc) {
596f4202 448 warn(_("cannot write %s"), log->filename);
ec10634e 449 return rc;
596f4202 450 }
ec10634e 451 ssz = bytes;
596f4202 452 break;
596f4202 453
ec10634e
KZ
454 case SCRIPT_FMT_TIMING_SIMPLE:
455 DBG(IO, ul_debug(" log timing info"));
596f4202
KZ
456
457 gettime_monotonic(&now);
458 timersub(&now, &log->oldtime, &delta);
ec10634e 459 ssz = fprintf(log->fp, "%ld.%06ld %zd\n",
596f4202 460 (long)delta.tv_sec, (long)delta.tv_usec, bytes);
ec10634e
KZ
461 if (ssz < 0)
462 return -errno;
463
596f4202 464 log->oldtime = now;
596f4202 465 break;
c1c2ee0b 466
ec10634e
KZ
467 case SCRIPT_FMT_TIMING_MULTI:
468 DBG(IO, ul_debug(" log multi-stream timing info"));
c1c2ee0b
KZ
469
470 gettime_monotonic(&now);
471 timersub(&now, &log->oldtime, &delta);
ec10634e 472 ssz = fprintf(log->fp, "%c %ld.%06ld %zd\n",
c1c2ee0b
KZ
473 stream->ident,
474 (long)delta.tv_sec, (long)delta.tv_usec, bytes);
ec10634e
KZ
475 if (ssz < 0)
476 return -errno;
477
c1c2ee0b 478 log->oldtime = now;
ec10634e 479 break;
596f4202
KZ
480 default:
481 break;
482 }
483
484 if (ctl->flush)
485 fflush(log->fp);
ec10634e 486 return ssz;
6343ee8c
KZ
487}
488
ec10634e 489static ssize_t log_stream_activity(
596f4202
KZ
490 struct script_control *ctl,
491 struct script_stream *stream,
492 char *buf, size_t bytes)
493{
494 size_t i;
ec10634e 495 ssize_t outsz = 0;
596f4202 496
ec10634e
KZ
497 for (i = 0; i < stream->nlogs; i++) {
498 ssize_t ssz = log_write(ctl, stream, stream->logs[i], buf, bytes);
499
500 if (ssz < 0)
501 return ssz;
502 outsz += ssz;
503 }
596f4202
KZ
504
505 return outsz;
506}
507
ec10634e 508static ssize_t log_signal(struct script_control *ctl, int signum, char *msgfmt, ...)
fbed5507
KZ
509{
510 struct script_log *log;
511 struct timeval now, delta;
512 char msg[BUFSIZ] = {0};
513 va_list ap;
ec10634e 514 ssize_t sz;
fbed5507
KZ
515
516 assert(ctl);
517
518 log = ctl->siglog;
519 if (!log)
520 return 0;
521
522 assert(log->format == SCRIPT_FMT_TIMING_MULTI);
fbed5507
KZ
523 DBG(IO, ul_debug(" writing signal to multi-stream timing"));
524
525 gettime_monotonic(&now);
526 timersub(&now, &log->oldtime, &delta);
527
528 if (msgfmt) {
529 int rc;
530 va_start(ap, msgfmt);
531 rc = vsnprintf(msg, sizeof(msg), msgfmt, ap);
532 va_end(ap);
533 if (rc < 0)
534 *msg = '\0';;
535 }
536
537 if (*msg)
fd42a45b 538 sz = fprintf(log->fp, "S %ld.%06ld SIG%s %s\n",
fbed5507
KZ
539 (long)delta.tv_sec, (long)delta.tv_usec,
540 signum_to_signame(signum), msg);
541 else
542 sz = fprintf(log->fp, "S %ld.%06ld SIG%s\n",
543 (long)delta.tv_sec, (long)delta.tv_usec,
544 signum_to_signame(signum));
545
546 log->oldtime = now;
ec10634e 547 return sz;
fbed5507 548}
596f4202 549
ec10634e 550static ssize_t log_info(struct script_control *ctl, const char *name, const char *msgfmt, ...)
3cecd176
KZ
551{
552 struct script_log *log;
553 char msg[BUFSIZ] = {0};
554 va_list ap;
ec10634e 555 ssize_t sz;
3cecd176
KZ
556
557 assert(ctl);
558
559 log = ctl->infolog;
560 if (!log)
561 return 0;
562
563 assert(log->format == SCRIPT_FMT_TIMING_MULTI);
564 DBG(IO, ul_debug(" writing info to multi-stream log"));
565
566 if (msgfmt) {
567 int rc;
568 va_start(ap, msgfmt);
569 rc = vsnprintf(msg, sizeof(msg), msgfmt, ap);
570 va_end(ap);
571 if (rc < 0)
572 *msg = '\0';;
573 }
574
575 if (*msg)
a1cc831b 576 sz = fprintf(log->fp, "H %f %s %s\n", 0.0, name, msg);
3cecd176 577 else
a1cc831b 578 sz = fprintf(log->fp, "H %f %s\n", 0.0, name);
3cecd176 579
ec10634e 580 return sz;
8198052c
SK
581}
582
7fb65db1 583
9e9b3d65 584static void logging_done(struct script_control *ctl, const char *msg)
93af8d8b 585{
596f4202
KZ
586 int status;
587 size_t i;
6343ee8c 588
ec10634e 589 DBG(MISC, ul_debug("stop logging"));
8198052c 590
6343ee8c 591 if (WIFSIGNALED(ctl->childstatus))
596f4202 592 status = WTERMSIG(ctl->childstatus) + 0x80;
6343ee8c 593 else
596f4202
KZ
594 status = WEXITSTATUS(ctl->childstatus);
595
596f4202
KZ
596 DBG(MISC, ul_debug(" status=%d", status));
597
598 /* close all output logs */
9e9b3d65
KZ
599 for (i = 0; i < ctl->out.nlogs; i++) {
600 struct script_log *log = ctl->out.logs[i];
601 log_close(ctl, log, msg, status);
602 log_free(ctl, log);
603 }
604 free(ctl->out.logs);
605 ctl->out.logs = NULL;
606 ctl->out.nlogs = 0;
596f4202
KZ
607
608 /* close all input logs */
9e9b3d65
KZ
609 for (i = 0; i < ctl->in.nlogs; i++) {
610 struct script_log *log = ctl->in.logs[i];
611 log_close(ctl, log, msg, status);
612 log_free(ctl, log);
613 }
614 free(ctl->in.logs);
615 ctl->in.logs = NULL;
616 ctl->in.nlogs = 0;
93af8d8b 617}
5c36a0eb 618
bdd43357
KZ
619static void callback_child_die(
620 void *data,
621 pid_t child __attribute__((__unused__)),
622 int status)
93af8d8b 623{
ec10634e 624 struct script_control *ctl = (struct script_control *) data;
93af8d8b 625
bdd43357
KZ
626 ctl->child = (pid_t) -1;
627 ctl->childstatus = status;
54c6611d
KZ
628}
629
bdd43357
KZ
630static void callback_child_sigstop(
631 void *data __attribute__((__unused__)),
632 pid_t child)
54c6611d 633{
ec10634e
KZ
634 DBG(SIGNAL, ul_debug(" child stop by SIGSTOP -- stop parent too"));
635 kill(getpid(), SIGSTOP);
636 DBG(SIGNAL, ul_debug(" resume"));
bdd43357 637 kill(child, SIGCONT);
54c6611d
KZ
638}
639
ec10634e 640static int callback_log_stream_activity(void *data, int fd, char *buf, size_t bufsz)
54c6611d 641{
ec10634e
KZ
642 struct script_control *ctl = (struct script_control *) data;
643 ssize_t ssz = 0;
54c6611d 644
ec10634e 645 DBG(IO, ul_debug("stream activity callback"));
b2bff066 646
ec10634e
KZ
647 /* from stdin (user) to command */
648 if (fd == STDIN_FILENO)
649 ssz = log_stream_activity(ctl, &ctl->in, buf, (size_t) bufsz);
364cda48 650
ec10634e
KZ
651 /* from command (master) to stdout and log */
652 else if (fd == ul_pty_get_childfd(ctl->pty))
653 ssz = log_stream_activity(ctl, &ctl->out, buf, (size_t) bufsz);
da26af4e 654
ec10634e
KZ
655 if (ssz < 0)
656 return (int) ssz;
54c6611d 657
ec10634e
KZ
658 DBG(IO, ul_debug(" append %ld bytes [summary=%zu, max=%zu]", ssz,
659 ctl->outsz, ctl->maxsz));
a2b4dec5 660
ec10634e 661 ctl->outsz += ssz;
da26af4e 662
aefe9893 663
596f4202
KZ
664 /* check output limit */
665 if (ctl->maxsz != 0 && ctl->outsz >= ctl->maxsz) {
666 if (!ctl->quiet)
667 printf(_("Script terminated, max output files size %"PRIu64" exceeded.\n"), ctl->maxsz);
668 DBG(IO, ul_debug("output size %"PRIu64", exceeded limit %"PRIu64, ctl->outsz, ctl->maxsz));
9e9b3d65 669 logging_done(ctl, _("max output size exceeded"));
ec10634e 670 return 1;
a2b4dec5 671 }
ec10634e 672 return 0;
a8896ad5
SK
673}
674
ec10634e 675static int callback_log_signal(void *data, struct signalfd_siginfo *info, void *sigdata)
a8896ad5 676{
ec10634e
KZ
677 struct script_control *ctl = (struct script_control *) data;
678 ssize_t ssz = 0;
a8896ad5 679
ec10634e 680 switch (info->ssi_signo) {
a8896ad5 681 case SIGWINCH:
ec10634e
KZ
682 {
683 struct winsize *win = (struct winsize *) sigdata;
684 ssz = log_signal(ctl, info->ssi_signo, "ROWS=%d COLS=%d",
685 win->ws_row, win->ws_col);
a8896ad5 686 break;
ec10634e 687 }
5860c45e
KZ
688 case SIGTERM:
689 /* fallthrough */
690 case SIGINT:
691 /* fallthrough */
692 case SIGQUIT:
ec10634e
KZ
693 ssz = log_signal(ctl, info->ssi_signo, NULL);
694 break;
a8896ad5 695 default:
ec10634e
KZ
696 /* no log */
697 break;
93af8d8b 698 }
a17f3264 699
ec10634e 700 return ssz < 0 ? ssz : 0;
6dbe3af9
KZ
701}
702
ec10634e 703static void die_if_link(struct script_control *ctl, const char *filename)
93af8d8b 704{
ec10634e 705 struct stat s;
54c6611d 706
ec10634e
KZ
707 if (ctl->force)
708 return;
709 if (lstat(filename, &s) == 0 && (S_ISLNK(s.st_mode) || s.st_nlink > 1))
710 errx(EXIT_FAILURE,
711 _("output file `%s' is a link\n"
712 "Use --force if you really want to use it.\n"
713 "Program not started."), filename);
6dbe3af9
KZ
714}
715
93af8d8b
SK
716int main(int argc, char **argv)
717{
edc7e420 718 struct script_control ctl = {
c1c2ee0b
KZ
719 .out = { .ident = 'O' },
720 .in = { .ident = 'I' },
edc7e420 721 };
ec10634e
KZ
722 struct ul_pty_callbacks *cb;
723 int ch, format = 0, caught_signal = 0, rc = 0;
70062aad 724 const char *outfile = NULL, *infile = NULL;
ec10634e 725 const char *timingfile = NULL, *shell = NULL, *command = NULL;
93af8d8b
SK
726
727 enum { FORCE_OPTION = CHAR_MAX + 1 };
728
729 static const struct option longopts[] = {
edc7e420
SK
730 {"append", no_argument, NULL, 'a'},
731 {"command", required_argument, NULL, 'c'},
732 {"return", no_argument, NULL, 'e'},
733 {"flush", no_argument, NULL, 'f'},
734 {"force", no_argument, NULL, FORCE_OPTION,},
70062aad 735 {"log-in", required_argument, NULL, 'I'},
ddbdb792 736 {"log-out", required_argument, NULL, 'O'},
c1c2ee0b 737 {"log-io", required_argument, NULL, 'B'},
fc58044f 738 {"log-timing", required_argument, NULL, 'T'},
daee4d95 739 {"logging-format", required_argument, NULL, 'm'},
aefe9893 740 {"output-limit", required_argument, NULL, 'o'},
edc7e420
SK
741 {"quiet", no_argument, NULL, 'q'},
742 {"timing", optional_argument, NULL, 't'},
743 {"version", no_argument, NULL, 'V'},
744 {"help", no_argument, NULL, 'h'},
745 {NULL, 0, NULL, 0}
93af8d8b 746 };
fc58044f
KZ
747 static const ul_excl_t excl[] = { /* rows and cols in ASCII order */
748 { 'T', 't' },
749 { 0 }
750 };
751 int excl_st[ARRAY_SIZE(excl)] = UL_EXCL_STATUS_INIT;
93af8d8b 752 setlocale(LC_ALL, "");
b09feab9
SK
753 /*
754 * script -t prints time delays as floating point numbers. The example
755 * program (scriptreplay) that we provide to handle this timing output
756 * is a perl script, and does not handle numbers in locale format (not
757 * even when "use locale;" is added). So, since these numbers are not
758 * for human consumption, it seems easiest to set LC_NUMERIC here.
759 */
760 setlocale(LC_NUMERIC, "C");
93af8d8b
SK
761 bindtextdomain(PACKAGE, LOCALEDIR);
762 textdomain(PACKAGE);
2c308875 763 close_stdout_atexit();
93af8d8b 764
a2b4dec5 765 script_init_debug();
ec10634e 766 ON_DBG(PTY, ul_pty_init_debug(0xFFFF));
a2b4dec5 767
daee4d95 768 while ((ch = getopt_long(argc, argv, "aB:c:efI:O:o:qm:T:t::Vh", longopts, NULL)) != -1) {
fc58044f
KZ
769
770 err_exclusive_options(ch, longopts, excl, excl_st);
771
edc7e420 772 switch (ch) {
93af8d8b 773 case 'a':
3f19b85f 774 ctl.append = 1;
93af8d8b
SK
775 break;
776 case 'c':
ec10634e 777 command = optarg;
93af8d8b
SK
778 break;
779 case 'e':
7e5796c9 780 ctl.rc_wanted = 1;
93af8d8b
SK
781 break;
782 case 'f':
3f19b85f 783 ctl.flush = 1;
93af8d8b
SK
784 break;
785 case FORCE_OPTION:
3f19b85f 786 ctl.force = 1;
93af8d8b 787 break;
c1c2ee0b
KZ
788 case 'B':
789 log_associate(&ctl, &ctl.in, optarg, SCRIPT_FMT_RAW);
790 log_associate(&ctl, &ctl.out, optarg, SCRIPT_FMT_RAW);
791 infile = outfile = optarg;
792 break;
70062aad
KZ
793 case 'I':
794 log_associate(&ctl, &ctl.in, optarg, SCRIPT_FMT_RAW);
795 infile = optarg;
796 break;
ddbdb792 797 case 'O':
70062aad
KZ
798 log_associate(&ctl, &ctl.out, optarg, SCRIPT_FMT_RAW);
799 outfile = optarg;
ddbdb792 800 break;
aefe9893
FM
801 case 'o':
802 ctl.maxsz = strtosize_or_err(optarg, _("failed to parse output limit size"));
803 break;
93af8d8b 804 case 'q':
3f19b85f 805 ctl.quiet = 1;
93af8d8b 806 break;
daee4d95
KZ
807 case 'm':
808 if (strcasecmp(optarg, "classic") == 0)
809 format = SCRIPT_FMT_TIMING_SIMPLE;
810 else if (strcasecmp(optarg, "advanced") == 0)
811 format = SCRIPT_FMT_TIMING_MULTI;
812 else
813 errx(EXIT_FAILURE, _("unssuported logging format: '%s'"), optarg);
814 break;
93af8d8b 815 case 't':
4f7521d6
KZ
816 if (optarg && *optarg == '=')
817 optarg++;
596f4202
KZ
818 log_associate(&ctl, &ctl.out,
819 optarg ? optarg : "/dev/stderr",
820 SCRIPT_FMT_TIMING_SIMPLE);
d805688a
KZ
821 /* used for message only */
822 timingfile = optarg ? optarg : "stderr";
93af8d8b 823 break;
fc58044f 824 case 'T' :
fc58044f
KZ
825 timingfile = optarg;
826 break;
93af8d8b 827 case 'V':
2c308875 828 print_version(EXIT_SUCCESS);
93af8d8b 829 case 'h':
86be6a32 830 usage();
93af8d8b 831 default:
677ec86c 832 errtryhelp(EXIT_FAILURE);
93af8d8b 833 }
fc58044f 834 }
93af8d8b
SK
835 argc -= optind;
836 argv += optind;
837
70062aad
KZ
838 /* default if no --log-* specified */
839 if (!outfile && !infile) {
ddbdb792 840 if (argc > 0)
70062aad
KZ
841 outfile = argv[0];
842 else {
ddbdb792 843 die_if_link(&ctl, DEFAULT_TYPESCRIPT_FILENAME);
70062aad
KZ
844 outfile = DEFAULT_TYPESCRIPT_FILENAME;
845 }
596f4202 846
70062aad
KZ
847 /* associate stdout with typescript file */
848 log_associate(&ctl, &ctl.out, outfile, SCRIPT_FMT_RAW);
849 }
93af8d8b 850
c1c2ee0b 851 if (timingfile) {
d628e9cf
KZ
852 /* the old SCRIPT_FMT_TIMING_SIMPLE should be used when
853 * recoding output only (just for backward compatibility),
854 * otherwise switch to new format. */
c1c2ee0b 855 if (!format)
d628e9cf 856 format = infile || (outfile && infile) ?
c1c2ee0b
KZ
857 SCRIPT_FMT_TIMING_MULTI :
858 SCRIPT_FMT_TIMING_SIMPLE;
daee4d95
KZ
859
860 else if (format == SCRIPT_FMT_TIMING_SIMPLE && outfile && infile)
861 errx(EXIT_FAILURE, _("log multiple streams is mutually "
862 "exclusive with 'classic' format"));
c1c2ee0b
KZ
863 if (outfile)
864 log_associate(&ctl, &ctl.out, timingfile, format);
865 if (infile)
866 log_associate(&ctl, &ctl.in, timingfile, format);
867 }
868
ec10634e
KZ
869 shell = getenv("SHELL");
870 if (!shell)
871 shell = _PATH_BSHELL;
93af8d8b 872
ec10634e
KZ
873 ctl.isterm = isatty(STDIN_FILENO);
874 ctl.pty = ul_new_pty(ctl.isterm);
875 if (!ctl.pty)
876 err(EXIT_FAILURE, "failed to allocate PTY handler");
877
878 ul_pty_set_callback_data(ctl.pty, (void *) &ctl);
879 cb = ul_pty_get_callbacks(ctl.pty);
bdd43357 880 cb->child_die = callback_child_die;
ec10634e
KZ
881 cb->child_sigstop = callback_child_sigstop;
882 cb->log_stream_activity = callback_log_stream_activity;
883 cb->log_signal = callback_log_signal;
3cecd176 884
d805688a 885 if (!ctl.quiet) {
70062aad
KZ
886 printf(_("Script started"));
887 if (outfile)
888 printf(_(", output log file is '%s'"), outfile);
889 if (infile)
890 printf(_(", input log file is '%s'"), infile);
891 if (timingfile)
892 printf(_(", timing file is '%s'"), timingfile);
893 printf(_(".\n"));
d805688a 894 }
ec10634e 895
b1154c4e
KZ
896#ifdef HAVE_LIBUTEMPTER
897 utempter_add_record(ul_pty_get_childfd(ctl.pty), NULL);
898#endif
899
ec10634e
KZ
900 if (ul_pty_setup(ctl.pty))
901 err(EXIT_FAILURE, _("failed to create pseudo-terminal"));
902
903 fflush(stdout);
904
905 /*
906 * We have terminal, do not use err() from now, use "goto done"
907 */
93af8d8b 908
ec10634e
KZ
909 switch ((int) (ctl.child = fork())) {
910 case -1: /* error */
911 warn(_("cannot create child process"));
912 rc = -errno;
913 goto done;
a2b4dec5 914
ec10634e
KZ
915 case 0: /* child */
916 {
917 const char *shname;
93af8d8b 918
ec10634e 919 ul_pty_init_slave(ctl.pty);
a2b4dec5 920
ec10634e 921 signal(SIGTERM, SIG_DFL); /* because /etc/csh.login */
93af8d8b 922
ec10634e
KZ
923 shname = strrchr(shell, '/');
924 shname = shname ? shname + 1 : shell;
925
926 if (command)
927 execl(shell, shname, "-c", command, NULL);
928 else
929 execl(shell, shname, "-i", NULL);
930 err(EXIT_FAILURE, "failed to execute %s", shell);
d35ffe80 931 break;
ec10634e
KZ
932 }
933 default:
d35ffe80 934 break;
ec10634e
KZ
935 }
936
937 /* parent */
938 ul_pty_set_child(ctl.pty, ctl.child);
939
9e9b3d65 940 rc = logging_start(&ctl);
ec10634e
KZ
941 if (rc)
942 goto done;
943
bdd43357 944 /* add extra info to advanced timing file */
ec10634e
KZ
945 if (timingfile && format == SCRIPT_FMT_TIMING_MULTI) {
946 char buf[FORMAT_TIMESTAMP_MAX];
947 time_t tvec = script_time((time_t *)NULL);
948
949 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
950 log_info(&ctl, "START_TIME", buf);
951
952 if (ctl.isterm) {
953 init_terminal_info(&ctl);
954 log_info(&ctl, "TERM", ctl.ttytype);
955 log_info(&ctl, "TTY", ctl.ttyname);
956 log_info(&ctl, "COLUMNS", "%d", ctl.ttycols);
957 log_info(&ctl, "LINES", "%d", ctl.ttylines);
fd42a45b 958 }
ec10634e
KZ
959 log_info(&ctl, "SHELL", shell);
960 if (command)
961 log_info(&ctl, "COMMAND", command);
962 log_info(&ctl, "TIMING_LOG", timingfile);
963 if (outfile)
964 log_info(&ctl, "OUTPUT_LOG", outfile);
965 if (infile)
966 log_info(&ctl, "INPUT_LOG", infile);
967 }
968
969 /* this is the main loop */
970 rc = ul_pty_proxy_master(ctl.pty);
971
972 /* all done; cleanup and kill */
973 caught_signal = ul_pty_get_delivered_signal(ctl.pty);
974
975 if (!caught_signal && ctl.child != (pid_t)-1)
bdd43357 976 ul_pty_wait_for_child(ctl.pty); /* final wait */
ec10634e
KZ
977
978 if (caught_signal && ctl.child != (pid_t)-1) {
979 fprintf(stderr, "\nSession terminated, killing shell...");
980 kill(ctl.child, SIGTERM);
981 sleep(2);
982 kill(ctl.child, SIGKILL);
983 fprintf(stderr, " ...killed.\n");
984 }
985
986done:
987 ul_pty_cleanup(ctl.pty);
9e9b3d65 988 logging_done(&ctl, NULL);
ec10634e
KZ
989
990 if (!ctl.quiet)
991 printf(_("Script done.\n"));
992
993#ifdef HAVE_LIBUTEMPTER
994 if (ul_pty_get_childfd(ctl.pty) >= 0)
995 utempter_remove_record(ul_pty_get_childfd(ctl.pty));
996#endif
997 ul_free_pty(ctl.pty);
998
999 /* default exit code */
1000 rc = rc ? EXIT_FAILURE : EXIT_SUCCESS;
1001
1002 /* exit code based on child status */
1003 if (ctl.rc_wanted && rc == EXIT_SUCCESS) {
1004 if (WIFSIGNALED(ctl.childstatus))
1005 rc = WTERMSIG(ctl.childstatus) + 0x80;
1006 else
1007 rc = WEXITSTATUS(ctl.childstatus);
93af8d8b 1008 }
d35ffe80 1009
ec10634e
KZ
1010 DBG(MISC, ul_debug("done [rc=%d]", rc));
1011 return rc;
6dbe3af9 1012}