1/* $NetBSD: script.c,v 1.34 2023/05/09 15:43:39 hgutch Exp $ */
2
3/*
4 * Copyright (c) 1980, 1992, 1993
5 * The Regents of the University of California. 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. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32#include <sys/cdefs.h>
33#ifndef lint
34__COPYRIGHT("@(#) Copyright (c) 1980, 1992, 1993\
35 The Regents of the University of California. All rights reserved.");
36#endif /* not lint */
37
38#ifndef lint
39#if 0
40static char sccsid[] = "@(#)script.c 8.1 (Berkeley) 6/6/93";
41#endif
42__RCSID("$NetBSD: script.c,v 1.34 2023/05/09 15:43:39 hgutch Exp $");
43#endif /* not lint */
44
45#include <sys/types.h>
46#include <sys/wait.h>
47#include <sys/stat.h>
48#include <sys/ioctl.h>
49#include <sys/time.h>
50#include <sys/param.h>
51#include <sys/uio.h>
52
53#include <err.h>
54#include <byteswap.h>
55#include <errno.h>
56#include <fcntl.h>
57#include <paths.h>
58#include <signal.h>
59#include <stdio.h>
60#include <stdlib.h>
61#include <string.h>
62#include <termios.h>
63#include <time.h>
64#include <tzfile.h>
65#include <unistd.h>
66#include <pty.h>
67#include <utmp.h>
68
69#define DEF_BUF 65536
70
71struct stamp {
72 uint64_t scr_len; /* amount of data */
73 uint64_t scr_sec; /* time it arrived in seconds... */
74 uint32_t scr_usec; /* ...and microseconds */
75 uint32_t scr_direction; /* 'i', 'o', etc (also indicates endianness) */
76};
77
78static FILE *fscript;
79static int master, slave;
80static int child, subchild;
81static size_t outcc;
82static int usesleep, rawout;
83static int quiet, flush;
84static const char *fname;
85
86static volatile sig_atomic_t die = 0; /* exit if 1 */
87static int cstat = EXIT_SUCCESS; /* cmd. exit status */
88static int eflag;
89static int isterm;
90static struct termios tt;
91
92__dead static void done(int);
93__dead static void doshell(const char *);
94__dead static void fail(void);
95static sig_t xsignal(int, sig_t);
96__dead static void dooutput(void);
97static void finish(int);
98static void scriptflush(int);
99static void record(FILE *, char *, size_t, int);
100static void consume(FILE *, off_t, char *, int);
101__dead static void playback(FILE *);
102
103int
104main(int argc, char *argv[])
105{
106 ssize_t scc;
107 size_t cc;
108 struct termios rtt;
109 struct winsize win;
110 int aflg, pflg, ch;
111 char ibuf[BUFSIZ];
112 const char *command;
113
114 aflg = 0;
115 pflg = 0;
116 usesleep = 1;
117 rawout = 0;
118 quiet = 0;
119 flush = 0;
120 command = NULL;
121 while ((ch = getopt(argc, argv, "ac:defpqr")) != -1)
122 switch(ch) {
123 case 'a':
124 aflg = 1;
125 break;
126 case 'c':
127 command = optarg;
128 break;
129 case 'd':
130 usesleep = 0;
131 break;
132 case 'e':
133 eflag = 1;
134 break;
135 case 'f':
136 flush = 1;
137 break;
138 case 'p':
139 pflg = 1;
140 break;
141 case 'q':
142 quiet = 1;
143 break;
144 case 'r':
145 rawout = 1;
146 break;
147 case '?':
148 default:
149 (void)fprintf(stderr,
150 "Usage: %s [-c <command>][-adefpqr] [file]\n",
151 getprogname());
152 exit(EXIT_FAILURE);
153 }
154 argc -= optind;
155 argv += optind;
156
157 if (argc > 0)
158 fname = argv[0];
159 else
160 fname = "typescript";
161
162 if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
163 err(EXIT_FAILURE, "fopen %s", fname);
164
165 if (pflg)
166 playback(fscript);
167
168 if (tcgetattr(STDIN_FILENO, &tt) == -1 ||
169 ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1) {
170 if (errno != ENOTTY) /* For debugger. */
171 err(EXIT_FAILURE, "tcgetattr/ioctl");
172 if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
173 err(EXIT_FAILURE, "openpty");
174 } else {
175 if (openpty(&master, &slave, NULL, &tt, &win) == -1)
176 err(EXIT_FAILURE, "openpty");
177 isterm = 1;
178 }
179
180 if (!quiet)
181 (void)printf("Script started, output file is %s\n", fname);
182
183 if (isterm) {
184 rtt = tt;
185 cfmakeraw(&rtt);
186 rtt.c_lflag &= ~ECHO;
187 (void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
188 }
189
190 (void)xsignal(SIGCHLD, finish);
191 child = fork();
192 if (child == -1) {
193 warn("fork");
194 fail();
195 }
196 if (child == 0) {
197 (void)xsignal(SIGCHLD, SIG_DFL);
198 subchild = child = fork();
199 if (child == -1) {
200 warn("fork");
201 fail();
202 }
203 if (child)
204 dooutput();
205 else
206 doshell(command);
207 }
208
209 if (!rawout)
210 (void)fclose(fscript);
211 while (!die && (scc = read(STDIN_FILENO, ibuf, BUFSIZ)) > 0) {
212 cc = (size_t)scc;
213 if (rawout)
214 record(fscript, ibuf, cc, 'i');
215 (void)write(master, ibuf, cc);
216 }
217 done(cstat);
218}
219
220/**
221 * wrapper around sigaction() because we want POSIX semantics:
222 * no auto-restarting of interrupted slow syscalls.
223 */
224static sig_t
225xsignal(int signo, sig_t handler)
226{
227 struct sigaction sa, osa;
228
229 sa.sa_handler = handler;
230 sa.sa_flags = 0;
231 sigemptyset(&sa.sa_mask);
232 if (sigaction(signo, &sa, &osa) == -1)
233 return SIG_ERR;
234 return osa.sa_handler;
235}
236
237static int
238getshellstatus(int status)
239{
240 if (WIFEXITED(status))
241 return WEXITSTATUS(status);
242 if (WIFSIGNALED(status))
243 return 128 + WTERMSIG(status);
244 return EXIT_FAILURE;
245}
246
247static void
248finish(int signo)
249{
250 int pid, status;
251
252 die = 0;
253 while ((pid = wait(&status)) > 0)
254 if (pid == child) {
255 die = 1;
256 }
257
258 if (!die)
259 return;
260 done(eflag ? getshellstatus(status) : EXIT_SUCCESS);
261}
262
263static void
264dooutput(void)
265{
266 struct itimerval value;
267 ssize_t scc;
268 size_t cc;
269 time_t tvec;
270 char obuf[BUFSIZ];
271
272 (void)close(STDIN_FILENO);
273 tvec = time(NULL);
274 if (rawout)
275 record(fscript, NULL, 0, 's');
276 else if (!quiet)
277 (void)fprintf(fscript, "Script started on %s", ctime(&tvec));
278
279 (void)signal(SIGALRM, scriptflush);
280 value.it_interval.tv_sec = SECSPERMIN / 2;
281 value.it_interval.tv_usec = 0;
282 value.it_value = value.it_interval;
283 (void)setitimer(ITIMER_REAL, &value, NULL);
284 for (;;) {
285 scc = read(master, obuf, sizeof(obuf));
286 if (scc <= 0)
287 break;
288 cc = (size_t)scc;
289 (void)write(STDOUT_FILENO, obuf, cc);
290 if (rawout)
291 record(fscript, obuf, cc, 'o');
292 else
293 (void)fwrite(obuf, 1, cc, fscript);
294 outcc += cc;
295 if (flush)
296 (void)fflush(fscript);
297 }
298 done(cstat);
299}
300
301static void
302scriptflush(int signo)
303{
304 if (outcc) {
305 (void)fflush(fscript);
306 outcc = 0;
307 }
308}
309
310static void
311doshell(const char *command)
312{
313 const char *shell;
314
315 (void)close(master);
316 (void)fclose(fscript);
317 login_tty(slave);
318 if (command == NULL) {
319 shell = getenv("SHELL");
320 if (shell == NULL)
321 shell = _PATH_BSHELL;
322 execl(shell, shell, "-i", NULL);
323 warn("execl `%s'", shell);
324 } else {
325 int ret = system(command);
326 if (ret == -1)
327 warn("system `%s'", command);
328 else
329 exit(eflag ? getshellstatus(ret) : EXIT_FAILURE);
330 }
331
332 fail();
333}
334
335static void
336fail(void)
337{
338
339 (void)kill(0, SIGTERM);
340 done(EXIT_FAILURE);
341}
342
343static void
344done(int status)
345{
346 time_t tvec;
347
348 if (subchild) {
349 tvec = time(NULL);
350 if (rawout)
351 record(fscript, NULL, 0, 'e');
352 else if (!quiet)
353 (void)fprintf(fscript,"\nScript done on %s",
354 ctime(&tvec));
355 (void)fclose(fscript);
356 (void)close(master);
357 } else {
358 if (isterm)
359 (void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
360 if (!quiet)
361 (void)printf("Script done, output file is %s\n", fname);
362 }
363 exit(status);
364}
365
366static void
367record(FILE *fp, char *buf, size_t cc, int direction)
368{
369 struct iovec iov[2];
370 struct stamp stamp;
371 struct timeval tv;
372
373 (void)gettimeofday(&tv, NULL);
374 stamp.scr_len = cc;
375 stamp.scr_sec = tv.tv_sec;
376 stamp.scr_usec = tv.tv_usec;
377 stamp.scr_direction = direction;
378 iov[0].iov_len = sizeof(stamp);
379 iov[0].iov_base = &stamp;
380 iov[1].iov_len = cc;
381 iov[1].iov_base = buf;
382 if (writev(fileno(fp), &iov[0], 2) == -1)
383 err(EXIT_FAILURE, "writev");
384}
385
386static void
387consume(FILE *fp, off_t len, char *buf, int reg)
388{
389 size_t l;
390
391 if (reg) {
392 if (fseeko(fp, len, SEEK_CUR) == -1)
393 err(EXIT_FAILURE, NULL);
394 }
395 else {
396 while (len > 0) {
397 l = MIN(DEF_BUF, len);
398 if (fread(buf, sizeof(char), l, fp) != l)
399 err(EXIT_FAILURE, "cannot read buffer");
400 len -= l;
401 }
402 }
403}
404
405#define swapstamp(stamp) do { \
406 if (stamp.scr_direction > 0xff) { \
407 stamp.scr_len = bswap64(stamp.scr_len); \
408 stamp.scr_sec = bswap64(stamp.scr_sec); \
409 stamp.scr_usec = bswap32(stamp.scr_usec); \
410 stamp.scr_direction = bswap32(stamp.scr_direction); \
411 } \
412} while (0/*CONSTCOND*/)
413
414static void
415termset(void)
416{
417 struct termios traw;
418
419 if (tcgetattr(STDOUT_FILENO, &tt) == -1) {
420 if (errno != ENOTTY) /* For debugger. */
421 err(EXIT_FAILURE, "tcgetattr");
422 return;
423 }
424 isterm = 1;
425 traw = tt;
426 cfmakeraw(&traw);
427 traw.c_lflag |= ISIG;
428 (void)tcsetattr(STDOUT_FILENO, TCSANOW, &traw);
429}
430
431static void
432termreset(void)
433{
434 if (isterm)
435 (void)tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
436
437 isterm = 0;
438}
439
440static void
441playback(FILE *fp)
442{
443 struct timespec tsi, tso;
444 struct stamp stamp;
445 struct stat pst;
446 char buf[DEF_BUF];
447 off_t nread, save_len;
448 size_t l;
449 time_t tclock;
450 int reg;
451
452 if (fstat(fileno(fp), &pst) == -1)
453 err(EXIT_FAILURE, "fstat failed");
454
455 reg = S_ISREG(pst.st_mode);
456
457 for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
458 if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
459 if (reg)
460 err(EXIT_FAILURE, "reading playback header");
461 else
462 break;
463 }
464 swapstamp(stamp);
465 save_len = sizeof(stamp);
466
467 if (reg && stamp.scr_len >
468 (uint64_t)(pst.st_size - save_len) - nread)
469 errx(EXIT_FAILURE, "invalid stamp");
470
471 save_len += stamp.scr_len;
472 tclock = stamp.scr_sec;
473 tso.tv_sec = stamp.scr_sec;
474 tso.tv_nsec = stamp.scr_usec * 1000;
475
476 switch (stamp.scr_direction) {
477 case 's':
478 if (!quiet)
479 (void)printf("Script started on %s",
480 ctime(&tclock));
481 tsi = tso;
482 (void)consume(fp, stamp.scr_len, buf, reg);
483 termset();
484 atexit(termreset);
485 break;
486 case 'e':
487 termreset();
488 if (!quiet)
489 (void)printf("\nScript done on %s",
490 ctime(&tclock));
491 (void)consume(fp, stamp.scr_len, buf, reg);
492 break;
493 case 'i':
494 /* throw input away */
495 (void)consume(fp, stamp.scr_len, buf, reg);
496 break;
497 case 'o':
498 tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
499 tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
500 if (tsi.tv_nsec < 0) {
501 tsi.tv_sec -= 1;
502 tsi.tv_nsec += 1000000000;
503 }
504 if (usesleep)
505 (void)nanosleep(&tsi, NULL);
506 tsi = tso;
507 while (stamp.scr_len > 0) {
508 l = MIN(DEF_BUF, stamp.scr_len);
509 if (fread(buf, sizeof(char), l, fp) != l)
510 err(EXIT_FAILURE, "cannot read buffer");
511
512 (void)write(STDOUT_FILENO, buf, l);
513 stamp.scr_len -= l;
514 }
515 break;
516 default:
517 errx(EXIT_FAILURE, "invalid direction %u",
518 stamp.scr_direction);
519 }
520 }
521 (void)fclose(fp);
522 exit(EXIT_SUCCESS);
523}