xref: /freebsd-14.2/usr.bin/script/script.c (revision 7b245cb8)
1 /*
2  * Copyright (c) 2010, 2012  David E. O'Brien
3  * Copyright (c) 1980, 1992, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 4. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 #include <sys/param.h>
32 __FBSDID("$FreeBSD$");
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1980, 1992, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif
38 #ifndef lint
39 static const char sccsid[] = "@(#)script.c	8.1 (Berkeley) 6/6/93";
40 #endif
41 
42 #include <sys/wait.h>
43 #include <sys/stat.h>
44 #include <sys/ioctl.h>
45 #include <sys/time.h>
46 #include <sys/uio.h>
47 #include <sys/endian.h>
48 #include <dev/filemon/filemon.h>
49 
50 #include <err.h>
51 #include <errno.h>
52 #include <fcntl.h>
53 #include <libutil.h>
54 #include <paths.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <termios.h>
60 #include <unistd.h>
61 
62 #define DEF_BUF 65536
63 
64 struct stamp {
65 	uint64_t scr_len;	/* amount of data */
66 	uint64_t scr_sec;	/* time it arrived in seconds... */
67 	uint32_t scr_usec;	/* ...and microseconds */
68 	uint32_t scr_direction; /* 'i', 'o', etc (also indicates endianness) */
69 };
70 
71 static FILE *fscript;
72 static int master, slave;
73 static int child;
74 static const char *fname;
75 static char *fmfname;
76 static int fflg, qflg, ttyflg;
77 static int usesleep, rawout;
78 
79 static struct termios tt;
80 
81 static void done(int) __dead2;
82 static void doshell(char **);
83 static void fail(void);
84 static void finish(void);
85 static void record(FILE *, char *, size_t, int);
86 static void consume(FILE *, off_t, char *, int);
87 static void playback(FILE *) __dead2;
88 static void usage(void);
89 
90 int
91 main(int argc, char *argv[])
92 {
93 	int cc;
94 	struct termios rtt, stt;
95 	struct winsize win;
96 	struct timeval tv, *tvp;
97 	time_t tvec, start;
98 	char obuf[BUFSIZ];
99 	char ibuf[BUFSIZ];
100 	fd_set rfd;
101 	int aflg, Fflg, kflg, pflg, ch, k, n;
102 	int flushtime, readstdin;
103 	int fm_fd, fm_log;
104 
105 	aflg = Fflg = kflg = pflg = 0;
106 	usesleep = 1;
107 	rawout = 0;
108 	flushtime = 30;
109 	fm_fd = -1;	/* Shut up stupid "may be used uninitialized" GCC
110 			   warning. (not needed w/clang) */
111 
112 	while ((ch = getopt(argc, argv, "adFfkpqrt:")) != -1)
113 		switch(ch) {
114 		case 'a':
115 			aflg = 1;
116 			break;
117 		case 'd':
118 			usesleep = 0;
119 			break;
120 		case 'F':
121 			Fflg = 1;
122 			break;
123 		case 'f':
124 			fflg = 1;
125 			break;
126 		case 'k':
127 			kflg = 1;
128 			break;
129 		case 'p':
130 			pflg = 1;
131 			break;
132 		case 'q':
133 			qflg = 1;
134 			break;
135 		case 'r':
136 			rawout = 1;
137 			break;
138 		case 't':
139 			flushtime = atoi(optarg);
140 			if (flushtime < 0)
141 				err(1, "invalid flush time %d", flushtime);
142 			break;
143 		case '?':
144 		default:
145 			usage();
146 		}
147 	argc -= optind;
148 	argv += optind;
149 
150 	if (argc > 0) {
151 		fname = argv[0];
152 		argv++;
153 		argc--;
154 	} else
155 		fname = "typescript";
156 
157 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
158 		err(1, "%s", fname);
159 
160 	if (fflg) {
161 		asprintf(&fmfname, "%s.filemon", fname);
162 		if (!fmfname)
163 			err(1, "%s.filemon", fname);
164 		if ((fm_fd = open("/dev/filemon", O_RDWR)) == -1)
165 			err(1, "open(\"/dev/filemon\", O_RDWR)");
166 		if ((fm_log = open(fmfname, O_WRONLY | O_CREAT | O_TRUNC,
167 		    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
168 			err(1, "open(%s)", fmfname);
169 		if (ioctl(fm_fd, FILEMON_SET_FD, &fm_log) < 0)
170 			err(1, "Cannot set filemon log file descriptor");
171 
172 		/* Set up these two fd's to close on exec. */
173 		(void)fcntl(fm_fd, F_SETFD, FD_CLOEXEC);
174 		(void)fcntl(fm_log, F_SETFD, FD_CLOEXEC);
175 	}
176 
177 	if (pflg)
178 		playback(fscript);
179 
180 	if ((ttyflg = isatty(STDIN_FILENO)) != 0) {
181 		if (tcgetattr(STDIN_FILENO, &tt) == -1)
182 			err(1, "tcgetattr");
183 		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1)
184 			err(1, "ioctl");
185 		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
186 			err(1, "openpty");
187 	} else {
188 		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
189 			err(1, "openpty");
190 	}
191 
192 	if (rawout)
193 		record(fscript, NULL, 0, 's');
194 
195 	if (!qflg) {
196 		tvec = time(NULL);
197 		(void)printf("Script started, output file is %s\n", fname);
198 		if (!rawout) {
199 			(void)fprintf(fscript, "Script started on %s",
200 			    ctime(&tvec));
201 			if (argv[0]) {
202 				fprintf(fscript, "command: ");
203 				for (k = 0 ; argv[k] ; ++k)
204 					fprintf(fscript, "%s%s", k ? " " : "",
205 						argv[k]);
206 				fprintf(fscript, "\n");
207 			}
208 		}
209 		fflush(fscript);
210 		if (fflg) {
211 			(void)printf("Filemon started, output file is %s\n",
212 			    fmfname);
213 		}
214 	}
215 	if (ttyflg) {
216 		rtt = tt;
217 		cfmakeraw(&rtt);
218 		rtt.c_lflag &= ~ECHO;
219 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
220 	}
221 
222 	child = fork();
223 	if (child < 0) {
224 		warn("fork");
225 		done(1);
226 	}
227 	if (child == 0) {
228 		if (fflg) {
229 			int pid;
230 
231 			pid = getpid();
232 			if (ioctl(fm_fd, FILEMON_SET_PID, &pid) < 0)
233 				err(1, "Cannot set filemon PID");
234 		}
235 
236 		doshell(argv);
237 	}
238 	close(slave);
239 
240 	start = tvec = time(0);
241 	readstdin = 1;
242 	for (;;) {
243 		FD_ZERO(&rfd);
244 		FD_SET(master, &rfd);
245 		if (readstdin)
246 			FD_SET(STDIN_FILENO, &rfd);
247 		if (!readstdin && ttyflg) {
248 			tv.tv_sec = 1;
249 			tv.tv_usec = 0;
250 			tvp = &tv;
251 			readstdin = 1;
252 		} else if (flushtime > 0) {
253 			tv.tv_sec = flushtime - (tvec - start);
254 			tv.tv_usec = 0;
255 			tvp = &tv;
256 		} else {
257 			tvp = NULL;
258 		}
259 		n = select(master + 1, &rfd, 0, 0, tvp);
260 		if (n < 0 && errno != EINTR)
261 			break;
262 		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
263 			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
264 			if (cc < 0)
265 				break;
266 			if (cc == 0) {
267 				if (tcgetattr(master, &stt) == 0 &&
268 				    (stt.c_lflag & ICANON) != 0) {
269 					(void)write(master, &stt.c_cc[VEOF], 1);
270 				}
271 				readstdin = 0;
272 			}
273 			if (cc > 0) {
274 				if (rawout)
275 					record(fscript, ibuf, cc, 'i');
276 				(void)write(master, ibuf, cc);
277 				if (kflg && tcgetattr(master, &stt) >= 0 &&
278 				    ((stt.c_lflag & ECHO) == 0)) {
279 					(void)fwrite(ibuf, 1, cc, fscript);
280 				}
281 			}
282 		}
283 		if (n > 0 && FD_ISSET(master, &rfd)) {
284 			cc = read(master, obuf, sizeof (obuf));
285 			if (cc <= 0)
286 				break;
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 		}
293 		tvec = time(0);
294 		if (tvec - start >= flushtime) {
295 			fflush(fscript);
296 			start = tvec;
297 		}
298 		if (Fflg)
299 			fflush(fscript);
300 	}
301 	finish();
302 	done(0);
303 }
304 
305 static void
306 usage(void)
307 {
308 	(void)fprintf(stderr,
309 	    "usage: script [-adfkpqr] [-t time] [file [command ...]]\n");
310 	exit(1);
311 }
312 
313 static void
314 finish(void)
315 {
316 	int e, status;
317 
318 	if (waitpid(child, &status, 0) == child) {
319 		if (WIFEXITED(status))
320 			e = WEXITSTATUS(status);
321 		else if (WIFSIGNALED(status))
322 			e = WTERMSIG(status);
323 		else /* can't happen */
324 			e = 1;
325 		done(e);
326 	}
327 }
328 
329 static void
330 doshell(char **av)
331 {
332 	const char *shell;
333 
334 	shell = getenv("SHELL");
335 	if (shell == NULL)
336 		shell = _PATH_BSHELL;
337 
338 	(void)close(master);
339 	(void)fclose(fscript);
340 	free(fmfname);
341 	login_tty(slave);
342 	setenv("SCRIPT", fname, 1);
343 	if (av[0]) {
344 		execvp(av[0], av);
345 		warn("%s", av[0]);
346 	} else {
347 		execl(shell, shell, "-i", (char *)NULL);
348 		warn("%s", shell);
349 	}
350 	fail();
351 }
352 
353 static void
354 fail(void)
355 {
356 	(void)kill(0, SIGTERM);
357 	done(1);
358 }
359 
360 static void
361 done(int eno)
362 {
363 	time_t tvec;
364 
365 	if (ttyflg)
366 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
367 	tvec = time(NULL);
368 	if (rawout)
369 		record(fscript, NULL, 0, 'e');
370 	if (!qflg) {
371 		if (!rawout)
372 			(void)fprintf(fscript,"\nScript done on %s",
373 			    ctime(&tvec));
374 		(void)printf("\nScript done, output file is %s\n", fname);
375 		if (fflg) {
376 			(void)printf("Filemon done, output file is %s\n",
377 			    fmfname);
378 		}
379 	}
380 	(void)fclose(fscript);
381 	(void)close(master);
382 	exit(eno);
383 }
384 
385 static void
386 record(FILE *fp, char *buf, size_t cc, int direction)
387 {
388 	struct iovec iov[2];
389 	struct stamp stamp;
390 	struct timeval tv;
391 
392 	(void)gettimeofday(&tv, NULL);
393 	stamp.scr_len = cc;
394 	stamp.scr_sec = tv.tv_sec;
395 	stamp.scr_usec = tv.tv_usec;
396 	stamp.scr_direction = direction;
397 	iov[0].iov_len = sizeof(stamp);
398 	iov[0].iov_base = &stamp;
399 	iov[1].iov_len = cc;
400 	iov[1].iov_base = buf;
401 	if (writev(fileno(fp), &iov[0], 2) == -1)
402 		err(1, "writev");
403 }
404 
405 static void
406 consume(FILE *fp, off_t len, char *buf, int reg)
407 {
408 	size_t l;
409 
410 	if (reg) {
411 		if (fseeko(fp, len, SEEK_CUR) == -1)
412 			err(1, NULL);
413 	}
414 	else {
415 		while (len > 0) {
416 			l = MIN(DEF_BUF, len);
417 			if (fread(buf, sizeof(char), l, fp) != l)
418 				err(1, "cannot read buffer");
419 			len -= l;
420 		}
421 	}
422 }
423 
424 #define swapstamp(stamp) do { \
425 	if (stamp.scr_direction > 0xff) { \
426 		stamp.scr_len = bswap64(stamp.scr_len); \
427 		stamp.scr_sec = bswap64(stamp.scr_sec); \
428 		stamp.scr_usec = bswap32(stamp.scr_usec); \
429 		stamp.scr_direction = bswap32(stamp.scr_direction); \
430 	} \
431 } while (0/*CONSTCOND*/)
432 
433 static void
434 playback(FILE *fp)
435 {
436 	struct timespec tsi, tso;
437 	struct stamp stamp;
438 	struct stat pst;
439 	char buf[DEF_BUF];
440 	off_t nread, save_len;
441 	size_t l;
442 	time_t tclock;
443 	int reg;
444 
445 	if (fstat(fileno(fp), &pst) == -1)
446 		err(1, "fstat failed");
447 
448 	reg = S_ISREG(pst.st_mode);
449 
450 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
451 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
452 			if (reg)
453 				err(1, "reading playback header");
454 			else
455 				break;
456 		}
457 		swapstamp(stamp);
458 		save_len = sizeof(stamp);
459 
460 		if (reg && stamp.scr_len >
461 		    (uint64_t)(pst.st_size - save_len) - nread)
462 			errx(1, "invalid stamp");
463 
464 		save_len += stamp.scr_len;
465 		tclock = stamp.scr_sec;
466 		tso.tv_sec = stamp.scr_sec;
467 		tso.tv_nsec = stamp.scr_usec * 1000;
468 
469 		switch (stamp.scr_direction) {
470 		case 's':
471 			if (!qflg)
472 			    (void)printf("Script started on %s",
473 				ctime(&tclock));
474 			tsi = tso;
475 			(void)consume(fp, stamp.scr_len, buf, reg);
476 			break;
477 		case 'e':
478 			if (!qflg)
479 				(void)printf("\nScript done on %s",
480 				    ctime(&tclock));
481 			(void)consume(fp, stamp.scr_len, buf, reg);
482 			break;
483 		case 'i':
484 			/* throw input away */
485 			(void)consume(fp, stamp.scr_len, buf, reg);
486 			break;
487 		case 'o':
488 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
489 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
490 			if (tsi.tv_nsec < 0) {
491 				tsi.tv_sec -= 1;
492 				tsi.tv_nsec += 1000000000;
493 			}
494 			if (usesleep)
495 				(void)nanosleep(&tsi, NULL);
496 			tsi = tso;
497 			while (stamp.scr_len > 0) {
498 				l = MIN(DEF_BUF, stamp.scr_len);
499 				if (fread(buf, sizeof(char), l, fp) != l)
500 					err(1, "cannot read buffer");
501 
502 				(void)write(STDOUT_FILENO, buf, l);
503 				stamp.scr_len -= l;
504 			}
505 			break;
506 		default:
507 			errx(1, "invalid direction");
508 		}
509 	}
510 	(void)fclose(fp);
511 	exit(0);
512 }
513