]> git.ipfire.org Git - thirdparty/util-linux.git/blob - term-utils/script.c
script: cleanup done timestamp message
[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
76 #include "debug.h"
77
78 static UL_DEBUG_DEFINE_MASK(script);
79 UL_DEBUG_DEFINE_MASKNAMES(script) = UL_DEBUG_EMPTY_MASKNAMES;
80
81 #define SCRIPT_DEBUG_INIT (1 << 1)
82 #define SCRIPT_DEBUG_POLL (1 << 2)
83 #define SCRIPT_DEBUG_SIGNAL (1 << 3)
84 #define SCRIPT_DEBUG_IO (1 << 4)
85 #define SCRIPT_DEBUG_MISC (1 << 5)
86 #define SCRIPT_DEBUG_ALL 0xFFFF
87
88 #define DBG(m, x) __UL_DBG(script, SCRIPT_DEBUG_, m, x)
89 #define ON_DBG(m, x) __UL_DBG_CALL(script, SCRIPT_DEBUG_, m, x)
90
91 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
92 # include <pty.h>
93 #endif
94
95 #ifdef HAVE_LIBUTEMPTER
96 # include <utempter.h>
97 #endif
98
99 #define DEFAULT_TYPESCRIPT_FILENAME "typescript"
100
101 struct script_control {
102 char *shell; /* shell to be executed */
103 char *command; /* command to be executed */
104 char *fname; /* output file path */
105 FILE *typescriptfp; /* output file pointer */
106 char *tname; /* timing file path */
107 FILE *timingfp; /* timing file pointer */
108 uint64_t outsz; /* current output file size */
109 uint64_t maxsz; /* maximum output file size */
110 struct timeval oldtime; /* previous write or command start time */
111 int master; /* pseudoterminal master file descriptor */
112 int slave; /* pseudoterminal slave file descriptor */
113 int poll_timeout; /* poll() timeout, used in end of execution */
114 pid_t child; /* child pid */
115 int childstatus; /* child process exit value */
116 struct termios attrs; /* slave terminal runtime attributes */
117 struct winsize win; /* terminal window size */
118 #if !HAVE_LIBUTIL || !HAVE_PTY_H
119 char *line; /* terminal line */
120 #endif
121 unsigned int
122 append:1, /* append output */
123 rc_wanted:1, /* return child exit value */
124 flush:1, /* flush after each write */
125 quiet:1, /* suppress most output */
126 timing:1, /* include timing file */
127 force:1, /* write output to links */
128 isterm:1, /* is child process running as terminal */
129 die:1; /* terminate program */
130
131 sigset_t sigset; /* catch SIGCHLD and SIGWINCH with signalfd() */
132 sigset_t sigorg; /* original signal mask */
133 int sigfd; /* file descriptor for signalfd() */
134 };
135
136 static void script_init_debug(void)
137 {
138 __UL_INIT_DEBUG_FROM_ENV(script, SCRIPT_DEBUG_, 0, SCRIPT_DEBUG);
139 }
140
141 /*
142 * For tests we want to be able to control time output
143 */
144 #ifdef TEST_SCRIPT
145 static inline time_t script_time(time_t *t)
146 {
147 const char *str = getenv("SCRIPT_TEST_SECOND_SINCE_EPOCH");
148 int64_t sec;
149
150 if (!str || sscanf(str, "%"SCNi64, &sec) != 1)
151 return time(t);
152 if (t)
153 *t = (time_t)sec;
154 return (time_t)sec;
155 }
156 #else /* !TEST_SCRIPT */
157 # define script_time(x) time(x)
158 #endif
159
160 static void __attribute__((__noreturn__)) usage(void)
161 {
162 FILE *out = stdout;
163 fputs(USAGE_HEADER, out);
164 fprintf(out, _(" %s [options] [file]\n"), program_invocation_short_name);
165
166 fputs(USAGE_SEPARATOR, out);
167 fputs(_("Make a typescript of a terminal session.\n"), out);
168
169 fputs(USAGE_OPTIONS, out);
170 fputs(_(" -a, --append append the output\n"
171 " -c, --command <command> run command rather than interactive shell\n"
172 " -e, --return return exit code of the child process\n"
173 " -f, --flush run flush after each write\n"
174 " --force use output file even when it is a link\n"
175 " -o, --output-limit <size> terminate if output files exceed size\n"
176 " -q, --quiet be quiet\n"
177 " -t[<file>], --timing[=<file>] output timing data to stderr or to FILE\n"
178 ), out);
179 printf(USAGE_HELP_OPTIONS(31));
180
181 printf(USAGE_MAN_TAIL("script(1)"));
182 exit(EXIT_SUCCESS);
183 }
184
185 static void die_if_link(const struct script_control *ctl)
186 {
187 struct stat s;
188
189 if (ctl->force)
190 return;
191 if (lstat(ctl->fname, &s) == 0 && (S_ISLNK(s.st_mode) || s.st_nlink > 1))
192 errx(EXIT_FAILURE,
193 _("output file `%s' is a link\n"
194 "Use --force if you really want to use it.\n"
195 "Program not started."), ctl->fname);
196 }
197
198 static void restore_tty(struct script_control *ctl, int mode)
199 {
200 struct termios rtt;
201
202 if (!ctl->isterm)
203 return;
204
205 rtt = ctl->attrs;
206 tcsetattr(STDIN_FILENO, mode, &rtt);
207 }
208
209 static void enable_rawmode_tty(struct script_control *ctl)
210 {
211 struct termios rtt;
212
213 if (!ctl->isterm)
214 return;
215
216 rtt = ctl->attrs;
217 cfmakeraw(&rtt);
218 rtt.c_lflag &= ~ECHO;
219 tcsetattr(STDIN_FILENO, TCSANOW, &rtt);
220 }
221
222 static void __attribute__((__noreturn__)) done(struct script_control *ctl)
223 {
224 DBG(MISC, ul_debug("done!"));
225
226 restore_tty(ctl, TCSADRAIN);
227
228 if (ctl->typescriptfp) {
229 char buf[FORMAT_TIMESTAMP_MAX];
230 time_t tvec = script_time((time_t *)NULL);
231
232 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
233 fprintf(ctl->typescriptfp, _("\nScript done on %s\n"), buf);
234 }
235
236 if (!ctl->quiet && ctl->typescriptfp)
237 printf(_("Script done, file is %s\n"), ctl->fname);
238 #ifdef HAVE_LIBUTEMPTER
239 if (ctl->master >= 0)
240 utempter_remove_record(ctl->master);
241 #endif
242 kill(ctl->child, SIGTERM); /* make sure we don't create orphans */
243
244 if (ctl->timingfp && close_stream(ctl->timingfp) != 0)
245 err(EXIT_FAILURE, "write failed: %s", ctl->tname);
246 if (ctl->typescriptfp && close_stream(ctl->typescriptfp) != 0)
247 err(EXIT_FAILURE, "write failed: %s", ctl->fname);
248
249 if (ctl->rc_wanted) {
250 if (WIFSIGNALED(ctl->childstatus))
251 exit(WTERMSIG(ctl->childstatus) + 0x80);
252 else
253 exit(WEXITSTATUS(ctl->childstatus));
254 }
255 exit(EXIT_SUCCESS);
256 }
257
258 static void __attribute__((__noreturn__)) fail(struct script_control *ctl)
259 {
260 DBG(MISC, ul_debug("fail!"));
261 kill(0, SIGTERM);
262 done(ctl);
263 }
264
265 static void wait_for_child(struct script_control *ctl, int wait)
266 {
267 int status;
268 pid_t pid;
269 int options = wait ? 0 : WNOHANG;
270
271 DBG(MISC, ul_debug("waiting for child"));
272
273 while ((pid = wait3(&status, options, NULL)) > 0)
274 if (pid == ctl->child)
275 ctl->childstatus = status;
276 }
277
278 static void write_output(struct script_control *ctl, char *obuf,
279 ssize_t bytes)
280 {
281 int timing_bytes = 0;
282
283 DBG(IO, ul_debug(" writing output"));
284
285 if (ctl->timing && ctl->timingfp) {
286 struct timeval now, delta;
287
288 DBG(IO, ul_debug(" writing timing info"));
289
290 gettime_monotonic(&now);
291 timersub(&now, &ctl->oldtime, &delta);
292 timing_bytes = fprintf(ctl->timingfp, "%ld.%06ld %zd\n",
293 (long)delta.tv_sec, (long)delta.tv_usec, bytes);
294 if (ctl->flush)
295 fflush(ctl->timingfp);
296 ctl->oldtime = now;
297 if (timing_bytes < 0)
298 timing_bytes = 0;
299 }
300
301 DBG(IO, ul_debug(" writing to script file"));
302
303 if (fwrite_all(obuf, 1, bytes, ctl->typescriptfp)) {
304 warn(_("cannot write script file"));
305 fail(ctl);
306 }
307 if (ctl->flush)
308 fflush(ctl->typescriptfp);
309
310 DBG(IO, ul_debug(" writing to output"));
311
312 if (write_all(STDOUT_FILENO, obuf, bytes)) {
313 DBG(IO, ul_debug(" writing output *failed*"));
314 warn(_("write failed"));
315 fail(ctl);
316 }
317
318 if (ctl->maxsz != 0)
319 ctl->outsz += bytes + timing_bytes;
320
321 DBG(IO, ul_debug(" writing output *done*"));
322 }
323
324 static int write_to_shell(struct script_control *ctl,
325 char *buf, size_t bufsz)
326 {
327 return write_all(ctl->master, buf, bufsz);
328 }
329
330 /*
331 * The script(1) is usually faster than shell, so it's a good idea to wait until
332 * the previous message has been already read by shell from slave before we
333 * write to master. This is necessary especially for EOF situation when we can
334 * send EOF to master before shell is fully initialized, to workaround this
335 * problem we wait until slave is empty. For example:
336 *
337 * echo "date" | script
338 *
339 * Unfortunately, the child (usually shell) can ignore stdin at all, so we
340 * don't wait forever to avoid dead locks...
341 *
342 * Note that script is primarily designed for interactive sessions as it
343 * maintains master+slave tty stuff within the session. Use pipe to write to
344 * script(1) and assume non-interactive (tee-like) behavior is NOT well
345 * supported.
346 */
347 static void write_eof_to_shell(struct script_control *ctl)
348 {
349 unsigned int tries = 0;
350 struct pollfd fds[] = {
351 { .fd = ctl->slave, .events = POLLIN }
352 };
353 char c = DEF_EOF;
354
355 DBG(IO, ul_debug(" waiting for empty slave"));
356 while (poll(fds, 1, 10) == 1 && tries < 8) {
357 DBG(IO, ul_debug(" slave is not empty"));
358 xusleep(250000);
359 tries++;
360 }
361 if (tries < 8)
362 DBG(IO, ul_debug(" slave is empty now"));
363
364 DBG(IO, ul_debug(" sending EOF to master"));
365 write_to_shell(ctl, &c, sizeof(char));
366 }
367
368 static void handle_io(struct script_control *ctl, int fd, int *eof)
369 {
370 char buf[BUFSIZ];
371 ssize_t bytes;
372 DBG(IO, ul_debug("%d FD active", fd));
373 *eof = 0;
374
375 /* read from active FD */
376 bytes = read(fd, buf, sizeof(buf));
377 if (bytes < 0) {
378 if (errno == EAGAIN || errno == EINTR)
379 return;
380 fail(ctl);
381 }
382
383 if (bytes == 0) {
384 *eof = 1;
385 return;
386 }
387
388 /* from stdin (user) to command */
389 if (fd == STDIN_FILENO) {
390 DBG(IO, ul_debug(" stdin --> master %zd bytes", bytes));
391
392 if (write_to_shell(ctl, buf, bytes)) {
393 warn(_("write failed"));
394 fail(ctl);
395 }
396 /* without sync write_output() will write both input &
397 * shell output that looks like double echoing */
398 fdatasync(ctl->master);
399
400 /* from command (master) to stdout and log */
401 } else if (fd == ctl->master) {
402 DBG(IO, ul_debug(" master --> stdout %zd bytes", bytes));
403 write_output(ctl, buf, bytes);
404
405 /* check output limit */
406 if (ctl->maxsz != 0 && ctl->outsz >= ctl->maxsz) {
407 if (!ctl->quiet)
408 printf(_("Script terminated, max output file size %zd exceeded.\n"), ctl->maxsz);
409 DBG(IO, ul_debug("output size %zd, exceeded limit %zd", ctl->outsz, ctl->maxsz));
410 done(ctl);
411 }
412 }
413 }
414
415 static void handle_signal(struct script_control *ctl, int fd)
416 {
417 struct signalfd_siginfo info;
418 ssize_t bytes;
419
420 DBG(SIGNAL, ul_debug("signal FD %d active", fd));
421
422 bytes = read(fd, &info, sizeof(info));
423 if (bytes != sizeof(info)) {
424 if (bytes < 0 && (errno == EAGAIN || errno == EINTR))
425 return;
426 fail(ctl);
427 }
428
429 switch (info.ssi_signo) {
430 case SIGCHLD:
431 DBG(SIGNAL, ul_debug(" get signal SIGCHLD"));
432 if (info.ssi_code == CLD_EXITED) {
433 wait_for_child(ctl, 0);
434 ctl->poll_timeout = 10;
435 } else if (info.ssi_status == SIGSTOP && ctl->child) {
436 DBG(SIGNAL, ul_debug(" child stop by SIGSTOP -- stop parent too"));
437 kill(getpid(), SIGSTOP);
438 DBG(SIGNAL, ul_debug(" resume"));
439 kill(ctl->child, SIGCONT);
440 }
441 return;
442 case SIGWINCH:
443 DBG(SIGNAL, ul_debug(" get signal SIGWINCH"));
444 if (ctl->isterm) {
445 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ctl->win);
446 ioctl(ctl->slave, TIOCSWINSZ, (char *)&ctl->win);
447 }
448 break;
449 case SIGTERM:
450 /* fallthrough */
451 case SIGINT:
452 /* fallthrough */
453 case SIGQUIT:
454 DBG(SIGNAL, ul_debug(" get signal SIG{TERM,INT,QUIT}"));
455 fprintf(stderr, _("\nSession terminated.\n"));
456 /* Child termination is going to generate SIGCHILD (see above) */
457 kill(ctl->child, SIGTERM);
458 return;
459 default:
460 abort();
461 }
462 }
463
464 static void do_io(struct script_control *ctl)
465 {
466 int ret, eof = 0;
467 time_t tvec = script_time((time_t *)NULL);
468 enum {
469 POLLFD_SIGNAL = 0,
470 POLLFD_MASTER,
471 POLLFD_STDIN
472
473 };
474 struct pollfd pfd[] = {
475 [POLLFD_SIGNAL] = { .fd = ctl->sigfd, .events = POLLIN | POLLERR | POLLHUP },
476 [POLLFD_MASTER] = { .fd = ctl->master, .events = POLLIN | POLLERR | POLLHUP },
477 [POLLFD_STDIN] = { .fd = STDIN_FILENO, .events = POLLIN | POLLERR | POLLHUP }
478 };
479
480
481 if ((ctl->typescriptfp =
482 fopen(ctl->fname, ctl->append ? "a" UL_CLOEXECSTR : "w" UL_CLOEXECSTR)) == NULL) {
483
484 restore_tty(ctl, TCSANOW);
485 warn(_("cannot open %s"), ctl->fname);
486 fail(ctl);
487 }
488 if (ctl->timing) {
489 const char *tname = ctl->tname ? ctl->tname : "/dev/stderr";
490
491 if (!(ctl->timingfp = fopen(tname, "w" UL_CLOEXECSTR))) {
492 restore_tty(ctl, TCSANOW);
493 warn(_("cannot open %s"), tname);
494 fail(ctl);
495 }
496 }
497
498
499 if (ctl->typescriptfp) {
500 char buf[FORMAT_TIMESTAMP_MAX];
501 strtime_iso(&tvec, ISO_TIMESTAMP, buf, sizeof(buf));
502 fprintf(ctl->typescriptfp, _("Script started on %s\n"), buf);
503 }
504 gettime_monotonic(&ctl->oldtime);
505
506 while (!ctl->die) {
507 size_t i;
508 int errsv;
509
510 DBG(POLL, ul_debug("calling poll()"));
511
512 /* wait for input or signal */
513 ret = poll(pfd, ARRAY_SIZE(pfd), ctl->poll_timeout);
514 errsv = errno;
515 DBG(POLL, ul_debug("poll() rc=%d", ret));
516
517 if (ret < 0) {
518 if (errsv == EAGAIN)
519 continue;
520 warn(_("poll failed"));
521 fail(ctl);
522 }
523 if (ret == 0) {
524 DBG(POLL, ul_debug("setting die=1"));
525 ctl->die = 1;
526 break;
527 }
528
529 for (i = 0; i < ARRAY_SIZE(pfd); i++) {
530 if (pfd[i].revents == 0)
531 continue;
532
533 DBG(POLL, ul_debug(" active pfd[%s].fd=%d %s %s %s",
534 i == POLLFD_STDIN ? "stdin" :
535 i == POLLFD_MASTER ? "master" :
536 i == POLLFD_SIGNAL ? "signal" : "???",
537 pfd[i].fd,
538 pfd[i].revents & POLLIN ? "POLLIN" : "",
539 pfd[i].revents & POLLHUP ? "POLLHUP" : "",
540 pfd[i].revents & POLLERR ? "POLLERR" : ""));
541 switch (i) {
542 case POLLFD_STDIN:
543 case POLLFD_MASTER:
544 /* data */
545 if (pfd[i].revents & POLLIN)
546 handle_io(ctl, pfd[i].fd, &eof);
547 /* EOF maybe detected by two ways:
548 * A) poll() return POLLHUP event after close()
549 * B) read() returns 0 (no data) */
550 if ((pfd[i].revents & POLLHUP) || eof) {
551 DBG(POLL, ul_debug(" ignore FD"));
552 pfd[i].fd = -1;
553 if (i == POLLFD_STDIN) {
554 write_eof_to_shell(ctl);
555 DBG(POLL, ul_debug(" ignore STDIN"));
556 }
557 }
558 continue;
559 case POLLFD_SIGNAL:
560 handle_signal(ctl, pfd[i].fd);
561 break;
562 }
563 }
564 }
565
566 DBG(POLL, ul_debug("poll() done"));
567
568 if (!ctl->die)
569 wait_for_child(ctl, 1);
570
571 done(ctl);
572 }
573
574 static void getslave(struct script_control *ctl)
575 {
576 #ifndef HAVE_LIBUTIL
577 ctl->line[strlen("/dev/")] = 't';
578 ctl->slave = open(ctl->line, O_RDWR | O_CLOEXEC);
579 if (ctl->slave < 0) {
580 warn(_("cannot open %s"), ctl->line);
581 fail(ctl);
582 }
583 if (ctl->isterm) {
584 tcsetattr(ctl->slave, TCSANOW, &ctl->attrs);
585 ioctl(ctl->slave, TIOCSWINSZ, (char *)&ctl->win);
586 }
587 #endif
588 setsid();
589 ioctl(ctl->slave, TIOCSCTTY, 0);
590 }
591
592 /* don't use DBG() stuff here otherwise it will be in the typescript file */
593 static void __attribute__((__noreturn__)) do_shell(struct script_control *ctl)
594 {
595 char *shname;
596
597 getslave(ctl);
598
599 /* close things irrelevant for this process */
600 close(ctl->master);
601 close(ctl->sigfd);
602
603 dup2(ctl->slave, STDIN_FILENO);
604 dup2(ctl->slave, STDOUT_FILENO);
605 dup2(ctl->slave, STDERR_FILENO);
606 close(ctl->slave);
607
608 ctl->master = -1;
609
610 shname = strrchr(ctl->shell, '/');
611 if (shname)
612 shname++;
613 else
614 shname = ctl->shell;
615
616 sigprocmask(SIG_SETMASK, &ctl->sigorg, NULL);
617
618 /*
619 * When invoked from within /etc/csh.login, script spawns a csh shell
620 * that spawns programs that cannot be killed with a SIGTERM. This is
621 * because csh has a documented behavior wherein it disables all
622 * signals when processing the /etc/csh.* files.
623 *
624 * Let's restore the default behavior.
625 */
626 signal(SIGTERM, SIG_DFL);
627
628 if (access(ctl->shell, X_OK) == 0) {
629 if (ctl->command)
630 execl(ctl->shell, shname, "-c", ctl->command, NULL);
631 else
632 execl(ctl->shell, shname, "-i", NULL);
633 } else {
634 if (ctl->command)
635 execlp(shname, "-c", ctl->command, NULL);
636 else
637 execlp(shname, "-i", NULL);
638 }
639 warn(_("failed to execute %s"), ctl->shell);
640 fail(ctl);
641 }
642
643
644 static void getmaster(struct script_control *ctl)
645 {
646 #if defined(HAVE_LIBUTIL) && defined(HAVE_PTY_H)
647 int rc;
648
649 ctl->isterm = isatty(STDIN_FILENO);
650
651 if (ctl->isterm) {
652 if (tcgetattr(STDIN_FILENO, &ctl->attrs) != 0)
653 err(EXIT_FAILURE, _("failed to get terminal attributes"));
654 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ctl->win);
655 rc = openpty(&ctl->master, &ctl->slave, NULL, &ctl->attrs, &ctl->win);
656 } else
657 rc = openpty(&ctl->master, &ctl->slave, NULL, NULL, NULL);
658
659 if (rc < 0) {
660 warn(_("openpty failed"));
661 fail(ctl);
662 }
663 #else
664 char *pty, *bank, *cp;
665
666 ctl->isterm = isatty(STDIN_FILENO);
667
668 pty = &ctl->line[strlen("/dev/ptyp")];
669 for (bank = "pqrs"; *bank; bank++) {
670 ctl->line[strlen("/dev/pty")] = *bank;
671 *pty = '0';
672 if (access(ctl->line, F_OK) != 0)
673 break;
674 for (cp = "0123456789abcdef"; *cp; cp++) {
675 *pty = *cp;
676 ctl->master = open(ctl->line, O_RDWR | O_CLOEXEC);
677 if (ctl->master >= 0) {
678 char *tp = &ctl->line[strlen("/dev/")];
679 int ok;
680
681 /* verify slave side is usable */
682 *tp = 't';
683 ok = access(ctl->line, R_OK | W_OK) == 0;
684 *tp = 'p';
685 if (ok) {
686 if (ctl->isterm) {
687 tcgetattr(STDIN_FILENO, &ctl->attrs);
688 ioctl(STDIN_FILENO, TIOCGWINSZ, (char *)&ctl->win);
689 }
690 return;
691 }
692 close(ctl->master);
693 ctl->master = -1;
694 }
695 }
696 }
697 ctl->master = -1;
698 warn(_("out of pty's"));
699 fail(ctl);
700 #endif /* not HAVE_LIBUTIL */
701
702 DBG(IO, ul_debug("master fd: %d", ctl->master));
703 }
704
705 int main(int argc, char **argv)
706 {
707 struct script_control ctl = {
708 #if !HAVE_LIBUTIL || !HAVE_PTY_H
709 .line = "/dev/ptyXX",
710 #endif
711 .master = -1,
712 .poll_timeout = -1
713 };
714 int ch;
715
716 enum { FORCE_OPTION = CHAR_MAX + 1 };
717
718 static const struct option longopts[] = {
719 {"append", no_argument, NULL, 'a'},
720 {"command", required_argument, NULL, 'c'},
721 {"return", no_argument, NULL, 'e'},
722 {"flush", no_argument, NULL, 'f'},
723 {"force", no_argument, NULL, FORCE_OPTION,},
724 {"output-limit", required_argument, NULL, 'o'},
725 {"quiet", no_argument, NULL, 'q'},
726 {"timing", optional_argument, NULL, 't'},
727 {"version", no_argument, NULL, 'V'},
728 {"help", no_argument, NULL, 'h'},
729 {NULL, 0, NULL, 0}
730 };
731
732 setlocale(LC_ALL, "");
733 /*
734 * script -t prints time delays as floating point numbers. The example
735 * program (scriptreplay) that we provide to handle this timing output
736 * is a perl script, and does not handle numbers in locale format (not
737 * even when "use locale;" is added). So, since these numbers are not
738 * for human consumption, it seems easiest to set LC_NUMERIC here.
739 */
740 setlocale(LC_NUMERIC, "C");
741 bindtextdomain(PACKAGE, LOCALEDIR);
742 textdomain(PACKAGE);
743 atexit(close_stdout);
744
745 script_init_debug();
746
747 while ((ch = getopt_long(argc, argv, "ac:efo:qt::Vh", longopts, NULL)) != -1)
748 switch (ch) {
749 case 'a':
750 ctl.append = 1;
751 break;
752 case 'c':
753 ctl.command = optarg;
754 break;
755 case 'e':
756 ctl.rc_wanted = 1;
757 break;
758 case 'f':
759 ctl.flush = 1;
760 break;
761 case FORCE_OPTION:
762 ctl.force = 1;
763 break;
764 case 'o':
765 ctl.maxsz = strtosize_or_err(optarg, _("failed to parse output limit size"));
766 break;
767 case 'q':
768 ctl.quiet = 1;
769 break;
770 case 't':
771 if (optarg)
772 ctl.tname = optarg;
773 ctl.timing = 1;
774 break;
775 case 'V':
776 printf(UTIL_LINUX_VERSION);
777 exit(EXIT_SUCCESS);
778 break;
779 case 'h':
780 usage();
781 break;
782 default:
783 errtryhelp(EXIT_FAILURE);
784 }
785 argc -= optind;
786 argv += optind;
787
788 if (argc > 0)
789 ctl.fname = argv[0];
790 else {
791 ctl.fname = DEFAULT_TYPESCRIPT_FILENAME;
792 die_if_link(&ctl);
793 }
794
795 ctl.shell = getenv("SHELL");
796 if (ctl.shell == NULL)
797 ctl.shell = _PATH_BSHELL;
798
799 getmaster(&ctl);
800 if (!ctl.quiet)
801 printf(_("Script started, file is %s\n"), ctl.fname);
802 enable_rawmode_tty(&ctl);
803
804 #ifdef HAVE_LIBUTEMPTER
805 utempter_add_record(ctl.master, NULL);
806 #endif
807 /* setup signal handler */
808 sigemptyset(&ctl.sigset);
809 sigaddset(&ctl.sigset, SIGCHLD);
810 sigaddset(&ctl.sigset, SIGWINCH);
811 sigaddset(&ctl.sigset, SIGTERM);
812 sigaddset(&ctl.sigset, SIGINT);
813 sigaddset(&ctl.sigset, SIGQUIT);
814
815 /* block signals used for signalfd() to prevent the signals being
816 * handled according to their default dispositions */
817 sigprocmask(SIG_BLOCK, &ctl.sigset, &ctl.sigorg);
818
819 if ((ctl.sigfd = signalfd(-1, &ctl.sigset, SFD_CLOEXEC)) < 0)
820 err(EXIT_FAILURE, _("cannot set signal handler"));
821
822 DBG(SIGNAL, ul_debug("signal fd=%d", ctl.sigfd));
823
824 fflush(stdout);
825 ctl.child = fork();
826
827 switch (ctl.child) {
828 case -1: /* error */
829 warn(_("fork failed"));
830 fail(&ctl);
831 break;
832 case 0: /* child */
833 do_shell(&ctl);
834 break;
835 default: /* parent */
836 do_io(&ctl);
837 break;
838 }
839
840 /* should not happen, all used functions are non-return */
841 return EXIT_FAILURE;
842 }