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