xref: /freebsd/usr.bin/script/script.c (revision 13ea0450a9c8742119d36f3bf8f47accdce46e54)
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, "adFfkpqrt:")) != -1)
115 		switch(ch) {
116 		case 'a':
117 			aflg = 1;
118 			break;
119 		case 'd':
120 			usesleep = 0;
121 			break;
122 		case 'F':
123 			Fflg = 1;
124 			break;
125 		case 'f':
126 			fflg = 1;
127 			break;
128 		case 'k':
129 			kflg = 1;
130 			break;
131 		case 'p':
132 			pflg = 1;
133 			break;
134 		case 'q':
135 			qflg = 1;
136 			break;
137 		case 'r':
138 			rawout = 1;
139 			break;
140 		case 't':
141 			flushtime = atoi(optarg);
142 			if (flushtime < 0)
143 				err(1, "invalid flush time %d", flushtime);
144 			break;
145 		case '?':
146 		default:
147 			usage();
148 		}
149 	argc -= optind;
150 	argv += optind;
151 
152 	if (argc > 0) {
153 		fname = argv[0];
154 		argv++;
155 		argc--;
156 	} else
157 		fname = "typescript";
158 
159 	if ((fscript = fopen(fname, pflg ? "r" : aflg ? "a" : "w")) == NULL)
160 		err(1, "%s", fname);
161 
162 	if (fflg) {
163 		asprintf(&fmfname, "%s.filemon", fname);
164 		if (!fmfname)
165 			err(1, "%s.filemon", fname);
166 		if ((fm_fd = open("/dev/filemon", O_RDWR | O_CLOEXEC)) == -1)
167 			err(1, "open(\"/dev/filemon\", O_RDWR)");
168 		if ((fm_log = open(fmfname,
169 		    O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
170 		    S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)) == -1)
171 			err(1, "open(%s)", fmfname);
172 		if (ioctl(fm_fd, FILEMON_SET_FD, &fm_log) < 0)
173 			err(1, "Cannot set filemon log file descriptor");
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 				showexit = 1;
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 	exit(1);
351 }
352 
353 static void
354 done(int eno)
355 {
356 	time_t tvec;
357 
358 	if (ttyflg)
359 		(void)tcsetattr(STDIN_FILENO, TCSAFLUSH, &tt);
360 	tvec = time(NULL);
361 	if (rawout)
362 		record(fscript, NULL, 0, 'e');
363 	if (!qflg) {
364 		if (!rawout) {
365 			if (showexit)
366 				(void)fprintf(fscript, "\nCommand exit status:"
367 				    " %d", eno);
368 			(void)fprintf(fscript,"\nScript done on %s",
369 			    ctime(&tvec));
370 		}
371 		(void)printf("\nScript done, output file is %s\n", fname);
372 		if (fflg) {
373 			(void)printf("Filemon done, output file is %s\n",
374 			    fmfname);
375 		}
376 	}
377 	(void)fclose(fscript);
378 	(void)close(master);
379 	exit(eno);
380 }
381 
382 static void
383 record(FILE *fp, char *buf, size_t cc, int direction)
384 {
385 	struct iovec iov[2];
386 	struct stamp stamp;
387 	struct timeval tv;
388 
389 	(void)gettimeofday(&tv, NULL);
390 	stamp.scr_len = cc;
391 	stamp.scr_sec = tv.tv_sec;
392 	stamp.scr_usec = tv.tv_usec;
393 	stamp.scr_direction = direction;
394 	iov[0].iov_len = sizeof(stamp);
395 	iov[0].iov_base = &stamp;
396 	iov[1].iov_len = cc;
397 	iov[1].iov_base = buf;
398 	if (writev(fileno(fp), &iov[0], 2) == -1)
399 		err(1, "writev");
400 }
401 
402 static void
403 consume(FILE *fp, off_t len, char *buf, int reg)
404 {
405 	size_t l;
406 
407 	if (reg) {
408 		if (fseeko(fp, len, SEEK_CUR) == -1)
409 			err(1, NULL);
410 	}
411 	else {
412 		while (len > 0) {
413 			l = MIN(DEF_BUF, len);
414 			if (fread(buf, sizeof(char), l, fp) != l)
415 				err(1, "cannot read buffer");
416 			len -= l;
417 		}
418 	}
419 }
420 
421 #define swapstamp(stamp) do { \
422 	if (stamp.scr_direction > 0xff) { \
423 		stamp.scr_len = bswap64(stamp.scr_len); \
424 		stamp.scr_sec = bswap64(stamp.scr_sec); \
425 		stamp.scr_usec = bswap32(stamp.scr_usec); \
426 		stamp.scr_direction = bswap32(stamp.scr_direction); \
427 	} \
428 } while (0/*CONSTCOND*/)
429 
430 static void
431 playback(FILE *fp)
432 {
433 	struct timespec tsi, tso;
434 	struct stamp stamp;
435 	struct stat pst;
436 	char buf[DEF_BUF];
437 	off_t nread, save_len;
438 	size_t l;
439 	time_t tclock;
440 	int reg;
441 
442 	if (fstat(fileno(fp), &pst) == -1)
443 		err(1, "fstat failed");
444 
445 	reg = S_ISREG(pst.st_mode);
446 
447 	for (nread = 0; !reg || nread < pst.st_size; nread += save_len) {
448 		if (fread(&stamp, sizeof(stamp), 1, fp) != 1) {
449 			if (reg)
450 				err(1, "reading playback header");
451 			else
452 				break;
453 		}
454 		swapstamp(stamp);
455 		save_len = sizeof(stamp);
456 
457 		if (reg && stamp.scr_len >
458 		    (uint64_t)(pst.st_size - save_len) - nread)
459 			errx(1, "invalid stamp");
460 
461 		save_len += stamp.scr_len;
462 		tclock = stamp.scr_sec;
463 		tso.tv_sec = stamp.scr_sec;
464 		tso.tv_nsec = stamp.scr_usec * 1000;
465 
466 		switch (stamp.scr_direction) {
467 		case 's':
468 			if (!qflg)
469 			    (void)printf("Script started on %s",
470 				ctime(&tclock));
471 			tsi = tso;
472 			(void)consume(fp, stamp.scr_len, buf, reg);
473 			break;
474 		case 'e':
475 			if (!qflg)
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(1, "cannot read buffer");
498 
499 				(void)write(STDOUT_FILENO, buf, l);
500 				stamp.scr_len -= l;
501 			}
502 			break;
503 		default:
504 			errx(1, "invalid direction");
505 		}
506 	}
507 	(void)fclose(fp);
508 	exit(0);
509 }
510