xref: /netbsd-src/usr.bin/script/script.c (revision 4f5bb74d628166d93d2d53fc6ca055f8b77af0c4)
1 /*	$NetBSD: script.c,v 1.23 2020/08/02 16:23:33 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.23 2020/08/02 16:23:33 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 int	isterm;
85 static struct	termios tt;
86 
87 __dead static void	done(void);
88 __dead static void	dooutput(void);
89 __dead static void	doshell(const char *);
90 __dead static void	fail(void);
91 static void	finish(int);
92 static void	scriptflush(int);
93 static void	record(FILE *, char *, size_t, int);
94 static void	consume(FILE *, off_t, char *, int);
95 __dead static void	playback(FILE *);
96 
97 int
98 main(int argc, char *argv[])
99 {
100 	ssize_t scc;
101 	size_t cc;
102 	struct termios rtt;
103 	struct winsize win;
104 	int aflg, pflg, ch;
105 	char ibuf[BUFSIZ];
106 	const char *command;
107 
108 	aflg = 0;
109 	pflg = 0;
110 	usesleep = 1;
111 	rawout = 0;
112 	quiet = 0;
113 	flush = 0;
114 	command = NULL;
115 	while ((ch = getopt(argc, argv, "ac:dfpqr")) != -1)
116 		switch(ch) {
117 		case 'a':
118 			aflg = 1;
119 			break;
120 		case 'c':
121 			command = optarg;
122 			break;
123 		case 'd':
124 			usesleep = 0;
125 			break;
126 		case 'f':
127 			flush = 1;
128 			break;
129 		case 'p':
130 			pflg = 1;
131 			break;
132 		case 'q':
133 			quiet = 1;
134 			break;
135 		case 'r':
136 			rawout = 1;
137 			break;
138 		case '?':
139 		default:
140 			(void)fprintf(stderr,
141 			    "Usage: %s [-c <command>][-adfpqr] [file]\n",
142 			    getprogname());
143 			exit(EXIT_FAILURE);
144 		}
145 	argc -= optind;
146 	argv += optind;
147 
148 	if (argc > 0)
149 		fname = argv[0];
150 	else
151 		fname = "typescript";
152 
153 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
154 		err(EXIT_FAILURE, "fopen %s", fname);
155 
156 	if (pflg)
157 		playback(fscript);
158 
159 	isterm = isatty(STDIN_FILENO);
160 	if (isterm) {
161 		if (tcgetattr(STDIN_FILENO, &tt) == -1)
162 			err(EXIT_FAILURE, "tcgetattr");
163 		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1)
164 			err(EXIT_FAILURE, "ioctl");
165 		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
166 			err(EXIT_FAILURE, "openpty");
167 	} else {
168 		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
169 			err(EXIT_FAILURE, "openpty");
170 	}
171 
172 	if (!quiet)
173 		(void)printf("Script started, output file is %s\n", fname);
174 
175 	if (isterm) {
176 		rtt = tt;
177 		cfmakeraw(&rtt);
178 		rtt.c_lflag &= ~ECHO;
179 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
180 	}
181 
182 	(void)signal(SIGCHLD, finish);
183 	child = fork();
184 	if (child == -1) {
185 		warn("fork");
186 		fail();
187 	}
188 	if (child == 0) {
189 		subchild = child = fork();
190 		if (child == -1) {
191 			warn("fork");
192 			fail();
193 		}
194 		if (child)
195 			dooutput();
196 		else
197 			doshell(command);
198 	}
199 
200 	if (!rawout)
201 		(void)fclose(fscript);
202 	while ((scc = read(STDIN_FILENO, ibuf, BUFSIZ)) > 0) {
203 		cc = (size_t)scc;
204 		if (rawout)
205 			record(fscript, ibuf, cc, 'i');
206 		(void)write(master, ibuf, cc);
207 	}
208 	done();
209 	/* NOTREACHED */
210 	return EXIT_SUCCESS;
211 }
212 
213 static void
214 finish(int signo)
215 {
216 	int die, pid, status;
217 
218 	die = 0;
219 	while ((pid = wait3(&status, WNOHANG, 0)) > 0)
220 		if (pid == child)
221 			die = 1;
222 
223 	if (die)
224 		done();
225 }
226 
227 static void
228 dooutput(void)
229 {
230 	struct itimerval value;
231 	ssize_t scc;
232 	size_t cc;
233 	time_t tvec;
234 	char obuf[BUFSIZ];
235 
236 	(void)close(STDIN_FILENO);
237 	tvec = time(NULL);
238 	if (rawout)
239 		record(fscript, NULL, 0, 's');
240 	else if (!quiet)
241 		(void)fprintf(fscript, "Script started on %s", ctime(&tvec));
242 
243 	(void)signal(SIGALRM, scriptflush);
244 	value.it_interval.tv_sec = SECSPERMIN / 2;
245 	value.it_interval.tv_usec = 0;
246 	value.it_value = value.it_interval;
247 	(void)setitimer(ITIMER_REAL, &value, NULL);
248 	for (;;) {
249 		scc = read(master, obuf, sizeof(obuf));
250 		if (scc <= 0)
251 			break;
252 		cc = (size_t)scc;
253 		(void)write(1, obuf, cc);
254 		if (rawout)
255 			record(fscript, obuf, cc, 'o');
256 		else
257 			(void)fwrite(obuf, 1, cc, fscript);
258 		outcc += cc;
259 		if (flush)
260 			(void)fflush(fscript);
261 	}
262 	done();
263 }
264 
265 static void
266 scriptflush(int signo)
267 {
268 	if (outcc) {
269 		(void)fflush(fscript);
270 		outcc = 0;
271 	}
272 }
273 
274 static void
275 doshell(const char *command)
276 {
277 	const char *shell;
278 
279 	(void)close(master);
280 	(void)fclose(fscript);
281 	login_tty(slave);
282 	if (command == NULL) {
283 		shell = getenv("SHELL");
284 		if (shell == NULL)
285 			shell = _PATH_BSHELL;
286 		execl(shell, shell, "-i", NULL);
287 		warn("execl `%s'", shell);
288 	} else {
289 		if (system(command) == -1)
290 			warn("system `%s'", command);
291 	}
292 
293 	fail();
294 }
295 
296 static void
297 fail(void)
298 {
299 
300 	(void)kill(0, SIGTERM);
301 	done();
302 }
303 
304 static void
305 done(void)
306 {
307 	time_t tvec;
308 
309 	if (subchild) {
310 		tvec = time(NULL);
311 		if (rawout)
312 			record(fscript, NULL, 0, 'e');
313 		else if (!quiet)
314 			(void)fprintf(fscript,"\nScript done on %s",
315 			    ctime(&tvec));
316 		(void)fclose(fscript);
317 		(void)close(master);
318 	} else {
319 		if (isterm)
320 			(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
321 		if (!quiet)
322 			(void)printf("Script done, output file is %s\n", fname);
323 	}
324 	exit(EXIT_SUCCESS);
325 }
326 
327 static void
328 record(FILE *fp, char *buf, size_t cc, int direction)
329 {
330 	struct iovec iov[2];
331 	struct stamp stamp;
332 	struct timeval tv;
333 
334 	(void)gettimeofday(&tv, NULL);
335 	stamp.scr_len = cc;
336 	stamp.scr_sec = tv.tv_sec;
337 	stamp.scr_usec = tv.tv_usec;
338 	stamp.scr_direction = direction;
339 	iov[0].iov_len = sizeof(stamp);
340 	iov[0].iov_base = &stamp;
341 	iov[1].iov_len = cc;
342 	iov[1].iov_base = buf;
343 	if (writev(fileno(fp), &iov[0], 2) == -1)
344 		err(EXIT_FAILURE, "writev");
345 }
346 
347 static void
348 consume(FILE *fp, off_t len, char *buf, int reg)
349 {
350 	size_t l;
351 
352 	if (reg) {
353 		if (fseeko(fp, len, SEEK_CUR) == -1)
354 			err(EXIT_FAILURE, NULL);
355 	}
356 	else {
357 		while (len > 0) {
358 			l = MIN(DEF_BUF, len);
359 			if (fread(buf, sizeof(char), l, fp) != l)
360 				err(EXIT_FAILURE, "cannot read buffer");
361 			len -= l;
362 		}
363 	}
364 }
365 
366 #define swapstamp(stamp) do { \
367 	if (stamp.scr_direction > 0xff) { \
368 		stamp.scr_len = bswap64(stamp.scr_len); \
369 		stamp.scr_sec = bswap64(stamp.scr_sec); \
370 		stamp.scr_usec = bswap32(stamp.scr_usec); \
371 		stamp.scr_direction = bswap32(stamp.scr_direction); \
372 	} \
373 } while (0/*CONSTCOND*/)
374 
375 static void
376 termset(void)
377 {
378 	struct termios traw;
379 
380 	isterm = isatty(STDOUT_FILENO);
381 	if (!isterm)
382 		return;
383 
384 	if (tcgetattr(STDOUT_FILENO, &tt) == -1)
385 		err(EXIT_FAILURE, "tcgetattr");
386 
387 	traw = tt;
388 	cfmakeraw(&traw);
389 	traw.c_lflag |= ISIG;
390 	if (tcsetattr(STDOUT_FILENO, TCSANOW, &traw) == -1)
391 		err(EXIT_FAILURE, "tcsetattr");
392 }
393 
394 static void
395 termreset(void)
396 {
397 	if (isterm)
398 		(void)tcsetattr(STDOUT_FILENO, TCSADRAIN, &tt);
399 
400 	isterm = 0;
401 }
402 
403 static void
404 playback(FILE *fp)
405 {
406 	struct timespec tsi, tso;
407 	struct stamp stamp;
408 	struct stat pst;
409 	char buf[DEF_BUF];
410 	off_t nread, save_len;
411 	size_t l;
412 	time_t tclock;
413 	int reg;
414 
415 	if (fstat(fileno(fp), &pst) == -1)
416 		err(EXIT_FAILURE, "fstat failed");
417 
418 	reg = S_ISREG(pst.st_mode);
419 
420 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
421 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
422 			if (reg)
423 				err(EXIT_FAILURE, "reading playback header");
424 			else
425 				break;
426 		}
427 		swapstamp(stamp);
428 		save_len = sizeof(stamp);
429 
430 		if (reg && stamp.scr_len >
431 		    (uint64_t)(pst.st_size - save_len) - nread)
432 			errx(EXIT_FAILURE, "invalid stamp");
433 
434 		save_len += stamp.scr_len;
435 		tclock = stamp.scr_sec;
436 		tso.tv_sec = stamp.scr_sec;
437 		tso.tv_nsec = stamp.scr_usec * 1000;
438 
439 		switch (stamp.scr_direction) {
440 		case 's':
441 			if (!quiet)
442 			    (void)printf("Script started on %s",
443 				ctime(&tclock));
444 			tsi = tso;
445 			(void)consume(fp, stamp.scr_len, buf, reg);
446 			termset();
447 			atexit(termreset);
448 			break;
449 		case 'e':
450 			termreset();
451 			if (!quiet)
452 				(void)printf("\nScript done on %s",
453 				    ctime(&tclock));
454 			(void)consume(fp, stamp.scr_len, buf, reg);
455 			break;
456 		case 'i':
457 			/* throw input away */
458 			(void)consume(fp, stamp.scr_len, buf, reg);
459 			break;
460 		case 'o':
461 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
462 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
463 			if (tsi.tv_nsec < 0) {
464 				tsi.tv_sec -= 1;
465 				tsi.tv_nsec += 1000000000;
466 			}
467 			if (usesleep)
468 				(void)nanosleep(&tsi, NULL);
469 			tsi = tso;
470 			while (stamp.scr_len > 0) {
471 				l = MIN(DEF_BUF, stamp.scr_len);
472 				if (fread(buf, sizeof(char), l, fp) != l)
473 					err(EXIT_FAILURE, "cannot read buffer");
474 
475 				(void)write(STDOUT_FILENO, buf, l);
476 				stamp.scr_len -= l;
477 			}
478 			break;
479 		default:
480 			errx(EXIT_FAILURE, "invalid direction %u",
481 			    stamp.scr_direction);
482 		}
483 	}
484 	(void)fclose(fp);
485 	exit(EXIT_SUCCESS);
486 }
487