xref: /freebsd-14.2/usr.bin/script/script.c (revision 95d13d1b)
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 finish(void);
84 static void record(FILE *, char *, size_t, int);
85 static void consume(FILE *, off_t, char *, int);
86 static void playback(FILE *) __dead2;
87 static void usage(void);
88 
89 int
90 main(int argc, char *argv[])
91 {
92 	int cc;
93 	struct termios rtt, stt;
94 	struct winsize win;
95 	struct timeval tv, *tvp;
96 	time_t tvec, start;
97 	char obuf[BUFSIZ];
98 	char ibuf[BUFSIZ];
99 	fd_set rfd;
100 	int aflg, Fflg, kflg, pflg, ch, k, n;
101 	int flushtime, readstdin;
102 	int fm_fd, fm_log;
103 
104 	aflg = Fflg = kflg = pflg = 0;
105 	usesleep = 1;
106 	rawout = 0;
107 	flushtime = 30;
108 	fm_fd = -1;	/* Shut up stupid "may be used uninitialized" GCC
109 			   warning. (not needed w/clang) */
110 
111 	while ((ch = getopt(argc, argv, "adFfkpqrt:")) != -1)
112 		switch(ch) {
113 		case 'a':
114 			aflg = 1;
115 			break;
116 		case 'd':
117 			usesleep = 0;
118 			break;
119 		case 'F':
120 			Fflg = 1;
121 			break;
122 		case 'f':
123 			fflg = 1;
124 			break;
125 		case 'k':
126 			kflg = 1;
127 			break;
128 		case 'p':
129 			pflg = 1;
130 			break;
131 		case 'q':
132 			qflg = 1;
133 			break;
134 		case 'r':
135 			rawout = 1;
136 			break;
137 		case 't':
138 			flushtime = atoi(optarg);
139 			if (flushtime < 0)
140 				err(1, "invalid flush time %d", flushtime);
141 			break;
142 		case '?':
143 		default:
144 			usage();
145 		}
146 	argc -= optind;
147 	argv += optind;
148 
149 	if (argc > 0) {
150 		fname = argv[0];
151 		argv++;
152 		argc--;
153 	} else
154 		fname = "typescript";
155 
156 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
157 		err(1, "%s", fname);
158 
159 	if (fflg) {
160 		asprintf(&fmfname, "%s.filemon", fname);
161 		if (!fmfname)
162 			err(1, "%s.filemon", fname);
163 		if ((fm_fd = open("/dev/filemon", O_RDWR)) == -1)
164 			err(1, "open(\"/dev/filemon\", O_RDWR)");
165 		if ((fm_log = open(fmfname, O_WRONLY | O_CREAT | O_TRUNC,
166 		    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
167 			err(1, "open(%s)", fmfname);
168 		if (ioctl(fm_fd, FILEMON_SET_FD, &fm_log) < 0)
169 			err(1, "Cannot set filemon log file descriptor");
170 
171 		/* Set up these two fd's to close on exec. */
172 		(void)fcntl(fm_fd, F_SETFD, FD_CLOEXEC);
173 		(void)fcntl(fm_log, F_SETFD, FD_CLOEXEC);
174 	}
175 
176 	if (pflg)
177 		playback(fscript);
178 
179 	if ((ttyflg = isatty(STDIN_FILENO)) != 0) {
180 		if (tcgetattr(STDIN_FILENO, &tt) == -1)
181 			err(1, "tcgetattr");
182 		if (ioctl(STDIN_FILENO, TIOCGWINSZ, &win) == -1)
183 			err(1, "ioctl");
184 		if (openpty(&master, &slave, NULL, &tt, &win) == -1)
185 			err(1, "openpty");
186 	} else {
187 		if (openpty(&master, &slave, NULL, NULL, NULL) == -1)
188 			err(1, "openpty");
189 	}
190 
191 	if (rawout)
192 		record(fscript, NULL, 0, 's');
193 
194 	if (!qflg) {
195 		tvec = time(NULL);
196 		(void)printf("Script started, output file is %s\n", fname);
197 		if (!rawout) {
198 			(void)fprintf(fscript, "Script started on %s",
199 			    ctime(&tvec));
200 			if (argv[0]) {
201 				fprintf(fscript, "command: ");
202 				for (k = 0 ; argv[k] ; ++k)
203 					fprintf(fscript, "%s%s", k ? " " : "",
204 						argv[k]);
205 				fprintf(fscript, "\n");
206 			}
207 		}
208 		fflush(fscript);
209 		if (fflg) {
210 			(void)printf("Filemon started, output file is %s\n",
211 			    fmfname);
212 		}
213 	}
214 	if (ttyflg) {
215 		rtt = tt;
216 		cfmakeraw(&rtt);
217 		rtt.c_lflag &= ~ECHO;
218 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &rtt);
219 	}
220 
221 	child = fork();
222 	if (child < 0) {
223 		warn("fork");
224 		done(1);
225 	}
226 	if (child == 0) {
227 		if (fflg) {
228 			int pid;
229 
230 			pid = getpid();
231 			if (ioctl(fm_fd, FILEMON_SET_PID, &pid) < 0)
232 				err(1, "Cannot set filemon PID");
233 		}
234 
235 		doshell(argv);
236 	}
237 	close(slave);
238 
239 	start = tvec = time(0);
240 	readstdin = 1;
241 	for (;;) {
242 		FD_ZERO(&rfd);
243 		FD_SET(master, &rfd);
244 		if (readstdin)
245 			FD_SET(STDIN_FILENO, &rfd);
246 		if (!readstdin && ttyflg) {
247 			tv.tv_sec = 1;
248 			tv.tv_usec = 0;
249 			tvp = &tv;
250 			readstdin = 1;
251 		} else if (flushtime > 0) {
252 			tv.tv_sec = flushtime - (tvec - start);
253 			tv.tv_usec = 0;
254 			tvp = &tv;
255 		} else {
256 			tvp = NULL;
257 		}
258 		n = select(master + 1, &rfd, 0, 0, tvp);
259 		if (n < 0 && errno != EINTR)
260 			break;
261 		if (n > 0 && FD_ISSET(STDIN_FILENO, &rfd)) {
262 			cc = read(STDIN_FILENO, ibuf, BUFSIZ);
263 			if (cc < 0)
264 				break;
265 			if (cc == 0) {
266 				if (tcgetattr(master, &stt) == 0 &&
267 				    (stt.c_lflag & ICANON) != 0) {
268 					(void)write(master, &stt.c_cc[VEOF], 1);
269 				}
270 				readstdin = 0;
271 			}
272 			if (cc > 0) {
273 				if (rawout)
274 					record(fscript, ibuf, cc, 'i');
275 				(void)write(master, ibuf, cc);
276 				if (kflg && tcgetattr(master, &stt) >= 0 &&
277 				    ((stt.c_lflag & ECHO) == 0)) {
278 					(void)fwrite(ibuf, 1, cc, fscript);
279 				}
280 			}
281 		}
282 		if (n > 0 && FD_ISSET(master, &rfd)) {
283 			cc = read(master, obuf, sizeof (obuf));
284 			if (cc <= 0)
285 				break;
286 			(void)write(STDOUT_FILENO, obuf, cc);
287 			if (rawout)
288 				record(fscript, obuf, cc, 'o');
289 			else
290 				(void)fwrite(obuf, 1, cc, fscript);
291 		}
292 		tvec = time(0);
293 		if (tvec - start >= flushtime) {
294 			fflush(fscript);
295 			start = tvec;
296 		}
297 		if (Fflg)
298 			fflush(fscript);
299 	}
300 	finish();
301 	done(0);
302 }
303 
304 static void
305 usage(void)
306 {
307 	(void)fprintf(stderr,
308 	    "usage: script [-adfkpqr] [-t time] [file [command ...]]\n");
309 	exit(1);
310 }
311 
312 static void
313 finish(void)
314 {
315 	int e, status;
316 
317 	if (waitpid(child, &status, 0) == child) {
318 		if (WIFEXITED(status))
319 			e = WEXITSTATUS(status);
320 		else if (WIFSIGNALED(status))
321 			e = WTERMSIG(status);
322 		else /* can't happen */
323 			e = 1;
324 		done(e);
325 	}
326 }
327 
328 static void
329 doshell(char **av)
330 {
331 	const char *shell;
332 
333 	shell = getenv("SHELL");
334 	if (shell == NULL)
335 		shell = _PATH_BSHELL;
336 
337 	(void)close(master);
338 	(void)fclose(fscript);
339 	free(fmfname);
340 	login_tty(slave);
341 	setenv("SCRIPT", fname, 1);
342 	if (av[0]) {
343 		execvp(av[0], av);
344 		warn("%s", av[0]);
345 	} else {
346 		execl(shell, shell, "-i", (char *)NULL);
347 		warn("%s", shell);
348 	}
349 	exit(1);
350 }
351 
352 static void
353 done(int eno)
354 {
355 	time_t tvec;
356 
357 	if (ttyflg)
358 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
359 	tvec = time(NULL);
360 	if (rawout)
361 		record(fscript, NULL, 0, 'e');
362 	if (!qflg) {
363 		if (!rawout)
364 			(void)fprintf(fscript,"\nScript done on %s",
365 			    ctime(&tvec));
366 		(void)printf("\nScript done, output file is %s\n", fname);
367 		if (fflg) {
368 			(void)printf("Filemon done, output file is %s\n",
369 			    fmfname);
370 		}
371 	}
372 	(void)fclose(fscript);
373 	(void)close(master);
374 	exit(eno);
375 }
376 
377 static void
378 record(FILE *fp, char *buf, size_t cc, int direction)
379 {
380 	struct iovec iov[2];
381 	struct stamp stamp;
382 	struct timeval tv;
383 
384 	(void)gettimeofday(&tv, NULL);
385 	stamp.scr_len = cc;
386 	stamp.scr_sec = tv.tv_sec;
387 	stamp.scr_usec = tv.tv_usec;
388 	stamp.scr_direction = direction;
389 	iov[0].iov_len = sizeof(stamp);
390 	iov[0].iov_base = &stamp;
391 	iov[1].iov_len = cc;
392 	iov[1].iov_base = buf;
393 	if (writev(fileno(fp), &iov[0], 2) == -1)
394 		err(1, "writev");
395 }
396 
397 static void
398 consume(FILE *fp, off_t len, char *buf, int reg)
399 {
400 	size_t l;
401 
402 	if (reg) {
403 		if (fseeko(fp, len, SEEK_CUR) == -1)
404 			err(1, NULL);
405 	}
406 	else {
407 		while (len > 0) {
408 			l = MIN(DEF_BUF, len);
409 			if (fread(buf, sizeof(char), l, fp) != l)
410 				err(1, "cannot read buffer");
411 			len -= l;
412 		}
413 	}
414 }
415 
416 #define swapstamp(stamp) do { \
417 	if (stamp.scr_direction > 0xff) { \
418 		stamp.scr_len = bswap64(stamp.scr_len); \
419 		stamp.scr_sec = bswap64(stamp.scr_sec); \
420 		stamp.scr_usec = bswap32(stamp.scr_usec); \
421 		stamp.scr_direction = bswap32(stamp.scr_direction); \
422 	} \
423 } while (0/*CONSTCOND*/)
424 
425 static void
426 playback(FILE *fp)
427 {
428 	struct timespec tsi, tso;
429 	struct stamp stamp;
430 	struct stat pst;
431 	char buf[DEF_BUF];
432 	off_t nread, save_len;
433 	size_t l;
434 	time_t tclock;
435 	int reg;
436 
437 	if (fstat(fileno(fp), &pst) == -1)
438 		err(1, "fstat failed");
439 
440 	reg = S_ISREG(pst.st_mode);
441 
442 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
443 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
444 			if (reg)
445 				err(1, "reading playback header");
446 			else
447 				break;
448 		}
449 		swapstamp(stamp);
450 		save_len = sizeof(stamp);
451 
452 		if (reg && stamp.scr_len >
453 		    (uint64_t)(pst.st_size - save_len) - nread)
454 			errx(1, "invalid stamp");
455 
456 		save_len += stamp.scr_len;
457 		tclock = stamp.scr_sec;
458 		tso.tv_sec = stamp.scr_sec;
459 		tso.tv_nsec = stamp.scr_usec * 1000;
460 
461 		switch (stamp.scr_direction) {
462 		case 's':
463 			if (!qflg)
464 			    (void)printf("Script started on %s",
465 				ctime(&tclock));
466 			tsi = tso;
467 			(void)consume(fp, stamp.scr_len, buf, reg);
468 			break;
469 		case 'e':
470 			if (!qflg)
471 				(void)printf("\nScript done on %s",
472 				    ctime(&tclock));
473 			(void)consume(fp, stamp.scr_len, buf, reg);
474 			break;
475 		case 'i':
476 			/* throw input away */
477 			(void)consume(fp, stamp.scr_len, buf, reg);
478 			break;
479 		case 'o':
480 			tsi.tv_sec = tso.tv_sec - tsi.tv_sec;
481 			tsi.tv_nsec = tso.tv_nsec - tsi.tv_nsec;
482 			if (tsi.tv_nsec < 0) {
483 				tsi.tv_sec -= 1;
484 				tsi.tv_nsec += 1000000000;
485 			}
486 			if (usesleep)
487 				(void)nanosleep(&tsi, NULL);
488 			tsi = tso;
489 			while (stamp.scr_len > 0) {
490 				l = MIN(DEF_BUF, stamp.scr_len);
491 				if (fread(buf, sizeof(char), l, fp) != l)
492 					err(1, "cannot read buffer");
493 
494 				(void)write(STDOUT_FILENO, buf, l);
495 				stamp.scr_len -= l;
496 			}
497 			break;
498 		default:
499 			errx(1, "invalid direction");
500 		}
501 	}
502 	(void)fclose(fp);
503 	exit(0);
504 }
505