xref: /netbsd-src/usr.bin/script/script.c (revision c3c5452ebd8b748669ab3dedf8e848a4637f7bf4)
1 /*	$NetBSD: script.c,v 1.31 2022/02/11 21:15:25 christos 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.31 2022/02/11 21:15:25 christos 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 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 		subchild = child = fork();
196 		if (child == -1) {
197 			warn("fork");
198 			fail();
199 		}
200 		if (child)
201 			dooutput();
202 		else
203 			doshell(command);
204 	}
205 
206 	if (!rawout)
207 		(void)fclose(fscript);
208 	while (!die && (scc = read(STDIN_FILENO, ibuf, BUFSIZ)) > 0) {
209 		cc = (size_t)scc;
210 		if (rawout)
211 			record(fscript, ibuf, cc, 'i');
212 		(void)write(master, ibuf, cc);
213 	}
214 	done(cstat);
215 }
216 
217 /**
218  * wrapper around sigaction() because we want POSIX semantics:
219  * no auto-restarting of interrupted slow syscalls.
220  */
221 static sig_t
222 xsignal(int signo, sig_t handler)
223 {
224 	struct sigaction sa, osa;
225 
226 	sa.sa_handler = handler;
227 	sa.sa_flags = 0;
228 	sigemptyset(&sa.sa_mask);
229 	if (sigaction(signo, &sa, &osa) == -1)
230 		return SIG_ERR;
231 	return osa.sa_handler;
232 }
233 
234 static void
235 finish(int signo)
236 {
237 	int pid, status;
238 
239 	while ((pid = wait(&status)) > 0)
240 		if (pid == child) {
241 			cstat = status;
242 			die = 1;
243 		}
244 
245 	if (!eflag)
246 		cstat = EXIT_SUCCESS;
247 	else if (WIFEXITED(cstat))
248 		cstat = WEXITSTATUS(cstat);
249 	else
250 		cstat = 128 + WTERMSIG(cstat);
251 }
252 
253 static void
254 dooutput(void)
255 {
256 	struct itimerval value;
257 	ssize_t scc;
258 	size_t cc;
259 	time_t tvec;
260 	char obuf[BUFSIZ];
261 
262 	(void)close(STDIN_FILENO);
263 	tvec = time(NULL);
264 	if (rawout)
265 		record(fscript, NULL, 0, 's');
266 	else if (!quiet)
267 		(void)fprintf(fscript, "Script started on %s", ctime(&tvec));
268 
269 	(void)signal(SIGALRM, scriptflush);
270 	value.it_interval.tv_sec = SECSPERMIN / 2;
271 	value.it_interval.tv_usec = 0;
272 	value.it_value = value.it_interval;
273 	(void)setitimer(ITIMER_REAL, &value, NULL);
274 	for (;;) {
275 		scc = read(master, obuf, sizeof(obuf));
276 		if (scc <= 0)
277 			break;
278 		cc = (size_t)scc;
279 		(void)write(STDOUT_FILENO, obuf, cc);
280 		if (rawout)
281 			record(fscript, obuf, cc, 'o');
282 		else
283 			(void)fwrite(obuf, 1, cc, fscript);
284 		outcc += cc;
285 		if (flush)
286 			(void)fflush(fscript);
287 	}
288 	done(cstat);
289 }
290 
291 static void
292 scriptflush(int signo)
293 {
294 	if (outcc) {
295 		(void)fflush(fscript);
296 		outcc = 0;
297 	}
298 }
299 
300 static void
301 doshell(const char *command)
302 {
303 	const char *shell;
304 
305 	(void)close(master);
306 	(void)fclose(fscript);
307 	login_tty(slave);
308 	if (command == NULL) {
309 		shell = getenv("SHELL");
310 		if (shell == NULL)
311 			shell = _PATH_BSHELL;
312 		execl(shell, shell, "-i", NULL);
313 		warn("execl `%s'", shell);
314 	} else {
315 		if (system(command) == -1)
316 			warn("system `%s'", command);
317 	}
318 
319 	fail();
320 }
321 
322 static void
323 fail(void)
324 {
325 
326 	(void)kill(0, SIGTERM);
327 	done(EXIT_FAILURE);
328 }
329 
330 static void
331 done(int status)
332 {
333 	time_t tvec;
334 
335 	if (subchild) {
336 		tvec = time(NULL);
337 		if (rawout)
338 			record(fscript, NULL, 0, 'e');
339 		else if (!quiet)
340 			(void)fprintf(fscript,"\nScript done on %s",
341 			    ctime(&tvec));
342 		(void)fclose(fscript);
343 		(void)close(master);
344 	} else {
345 		if (isterm)
346 			(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
347 		if (!quiet)
348 			(void)printf("Script done, output file is %s\n", fname);
349 	}
350 	exit(status);
351 }
352 
353 static void
354 record(FILE *fp, char *buf, size_t cc, int direction)
355 {
356 	struct iovec iov[2];
357 	struct stamp stamp;
358 	struct timeval tv;
359 
360 	(void)gettimeofday(&tv, NULL);
361 	stamp.scr_len = cc;
362 	stamp.scr_sec = tv.tv_sec;
363 	stamp.scr_usec = tv.tv_usec;
364 	stamp.scr_direction = direction;
365 	iov[0].iov_len = sizeof(stamp);
366 	iov[0].iov_base = &stamp;
367 	iov[1].iov_len = cc;
368 	iov[1].iov_base = buf;
369 	if (writev(fileno(fp), &iov[0], 2) == -1)
370 		err(EXIT_FAILURE, "writev");
371 }
372 
373 static void
374 consume(FILE *fp, off_t len, char *buf, int reg)
375 {
376 	size_t l;
377 
378 	if (reg) {
379 		if (fseeko(fp, len, SEEK_CUR) == -1)
380 			err(EXIT_FAILURE, NULL);
381 	}
382 	else {
383 		while (len > 0) {
384 			l = MIN(DEF_BUF, len);
385 			if (fread(buf, sizeof(char), l, fp) != l)
386 				err(EXIT_FAILURE, "cannot read buffer");
387 			len -= l;
388 		}
389 	}
390 }
391 
392 #define swapstamp(stamp) do { \
393 	if (stamp.scr_direction > 0xff) { \
394 		stamp.scr_len = bswap64(stamp.scr_len); \
395 		stamp.scr_sec = bswap64(stamp.scr_sec); \
396 		stamp.scr_usec = bswap32(stamp.scr_usec); \
397 		stamp.scr_direction = bswap32(stamp.scr_direction); \
398 	} \
399 } while (0/*CONSTCOND*/)
400 
401 static void
402 termset(void)
403 {
404 	struct termios traw;
405 
406 	if (tcgetattr(STDOUT_FILENO, &tt) == -1) {
407 		if (errno != ENOTTY) /* For debugger. */
408 			err(EXIT_FAILURE, "tcgetattr");
409 		return;
410 	}
411 	isterm = 1;
412 	traw = tt;
413 	cfmakeraw(&traw);
414 	traw.c_lflag |= ISIG;
415         (void)tcsetattr(STDOUT_FILENO, TCSANOW, &traw);
416 }
417 
418 static void
419 termreset(void)
420 {
421 	if (isterm)
422 		(void)tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
423 
424 	isterm = 0;
425 }
426 
427 static void
428 playback(FILE *fp)
429 {
430 	struct timespec tsi, tso;
431 	struct stamp stamp;
432 	struct stat pst;
433 	char buf[DEF_BUF];
434 	off_t nread, save_len;
435 	size_t l;
436 	time_t tclock;
437 	int reg;
438 
439 	if (fstat(fileno(fp), &pst) == -1)
440 		err(EXIT_FAILURE, "fstat failed");
441 
442 	reg = S_ISREG(pst.st_mode);
443 
444 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
445 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
446 			if (reg)
447 				err(EXIT_FAILURE, "reading playback header");
448 			else
449 				break;
450 		}
451 		swapstamp(stamp);
452 		save_len = sizeof(stamp);
453 
454 		if (reg && stamp.scr_len >
455 		    (uint64_t)(pst.st_size - save_len) - nread)
456 			errx(EXIT_FAILURE, "invalid stamp");
457 
458 		save_len += stamp.scr_len;
459 		tclock = stamp.scr_sec;
460 		tso.tv_sec = stamp.scr_sec;
461 		tso.tv_nsec = stamp.scr_usec * 1000;
462 
463 		switch (stamp.scr_direction) {
464 		case 's':
465 			if (!quiet)
466 			    (void)printf("Script started on %s",
467 				ctime(&tclock));
468 			tsi = tso;
469 			(void)consume(fp, stamp.scr_len, buf, reg);
470 			termset();
471 			atexit(termreset);
472 			break;
473 		case 'e':
474 			termreset();
475 			if (!quiet)
476 				(void)printf("\nScript done on %s",
477 				    ctime(&tclock));
478 			(void)consume(fp, stamp.scr_len, buf, reg);
479 			break;
480 		case 'i':
481 			/* throw input away */
482 			(void)consume(fp, stamp.scr_len, buf, reg);
483 			break;
484 		case 'o':
485 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
486 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
487 			if (tsi.tv_nsec < 0) {
488 				tsi.tv_sec -= 1;
489 				tsi.tv_nsec += 1000000000;
490 			}
491 			if (usesleep)
492 				(void)nanosleep(&tsi, NULL);
493 			tsi = tso;
494 			while (stamp.scr_len > 0) {
495 				l = MIN(DEF_BUF, stamp.scr_len);
496 				if (fread(buf, sizeof(char), l, fp) != l)
497 					err(EXIT_FAILURE, "cannot read buffer");
498 
499 				(void)write(STDOUT_FILENO, buf, l);
500 				stamp.scr_len -= l;
501 			}
502 			break;
503 		default:
504 			errx(EXIT_FAILURE, "invalid direction %u",
505 			    stamp.scr_direction);
506 		}
507 	}
508 	(void)fclose(fp);
509 	exit(EXIT_SUCCESS);
510 }
511