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